blob: 0a70bafb830d312f4c65b9e687ee014f349c010c [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale37af4b32021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Drysdale42fe1892021-10-14 14:43:46 +010025#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027#include <openssl/evp.h>
28#include <openssl/mem.h>
David Drysdalead785f52023-03-27 19:53:01 +010029#include <openssl/x509.h>
David Zeuthene0c40892021-01-08 12:54:11 -050030#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070031
32#include <cutils/properties.h>
33
David Drysdale4dc01072021-04-01 12:17:35 +010034#include <android/binder_manager.h>
35
36#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080037#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070038
Shawn Willden08a7e432020-12-11 13:05:27 +000039#include <keymint_support/key_param_output.h>
40#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070041
42#include "KeyMintAidlTestBase.h"
43
Janis Danisevskis24c04702020-12-16 18:28:39 -080044using aidl::android::hardware::security::keymint::AuthorizationSet;
45using aidl::android::hardware::security::keymint::KeyCharacteristics;
46using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070047
Selene Huang31ab4042020-04-29 04:22:39 -070048namespace std {
49
Janis Danisevskis24c04702020-12-16 18:28:39 -080050using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070051
52template <>
53struct std::equal_to<KeyCharacteristics> {
54 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070055 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070056
Shawn Willden7f424372021-01-10 18:06:50 -070057 // this isn't very efficient. Oh, well.
58 AuthorizationSet a_auths(a.authorizations);
59 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070060
Shawn Willden7f424372021-01-10 18:06:50 -070061 a_auths.Sort();
62 b_auths.Sort();
63
64 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070065 }
66};
67
68} // namespace std
69
Janis Danisevskis24c04702020-12-16 18:28:39 -080070namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000071
Selene Huang31ab4042020-04-29 04:22:39 -070072namespace {
73
David Drysdalefeab5d92022-01-06 15:46:23 +000074// Maximum supported Ed25519 message size.
75const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
76
David Drysdaledbbbe2e2021-12-02 07:44:23 +000077// Whether to check that BOOT_PATCHLEVEL is populated.
78bool check_boot_pl = true;
79
Seth Moore7a55ae32021-06-23 14:28:11 -070080// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000081// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070082// is a small (roughly 1/256) chance that corrupting ciphertext still results
83// in valid PKCS7 padding.
84constexpr size_t kMaxPaddingCorruptionRetries = 8;
85
Selene Huang31ab4042020-04-29 04:22:39 -070086template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000087bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
88 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070089 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080090 if (auto p = authorizationValue(ttag, param)) {
91 return *p == expected_value;
92 }
93 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070094 });
95 return (it != set.end());
96}
97
98template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000099bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -0700100 auto it = std::find_if(set.begin(), set.end(),
101 [&](const KeyParameter& param) { return param.tag == tag; });
102 return (it != set.end());
103}
104
105constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
108 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
109 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
110 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
111 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
115 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
120 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
121
122string hex2str(string a) {
123 string b;
124 size_t num = a.size() / 2;
125 b.resize(num);
126 for (size_t i = 0; i < num; i++) {
127 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
128 }
129 return b;
130}
131
David Drysdaled2cc8c22021-04-15 13:29:45 +0100132string rsa_key = hex2str(
133 // RFC 5208 s5
134 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
135 "020100" // INTEGER length 1 value 0x00 (version)
136 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
137 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
138 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
139 "0500" // NULL (parameters)
140 // } end SEQUENCE (AlgorithmIdentifier)
141 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
142 // RFC 8017 A.1.2
143 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
144 "020100" // INTEGER length 1 value 0x00 (version)
145 "028181" // INTEGER length 0x81 value (modulus) ...
146 "00c6095409047d8634812d5a218176e4"
147 "5c41d60a75b13901f234226cffe77652"
148 "1c5a77b9e389417b71c0b6a44d13afe4"
149 "e4a2805d46c9da2935adb1ff0c1f24ea"
150 "06e62b20d776430a4d435157233c6f91"
151 "6783c30e310fcbd89b85c2d567711697"
152 "85ac12bca244abda72bfb19fc44d27c8"
153 "1e1d92de284f4061edfd99280745ea6d"
154 "25"
155 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
156 "028180" // INTEGER length 0x80 (privateExponent) value...
157 "1be0f04d9cae3718691f035338308e91"
158 "564b55899ffb5084d2460e6630257e05"
159 "b3ceab02972dfabcd6ce5f6ee2589eb6"
160 "7911ed0fac16e43a444b8c861e544a05"
161 "93365772f8baf6b22fc9e3c5f1024b06"
162 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
163 "ace7240290bef16c0b3f7f3cdd64ce3a"
164 "b5912cf6e32f39ab188358afcccd8081"
165 "0241" // INTEGER length 0x41 (prime1)
166 "00e4b49ef50f765d3b24dde01aceaaf1"
167 "30f2c76670a91a61ae08af497b4a82be"
168 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
169 "8c92bfab137fba2285227b83c342ff7c"
170 "55"
171 "0241" // INTEGER length 0x41 (prime2)
172 "00ddabb5839c4c7f6bf3d4183231f005"
173 "b31aa58affdda5c79e4cce217f6bc930"
174 "dbe563d480706c24e9ebfcab28a6cdef"
175 "d324b77e1bf7251b709092c24ff501fd"
176 "91"
177 "0240" // INTEGER length 0x40 (exponent1)
178 "23d4340eda3445d8cd26c14411da6fdc"
179 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
180 "842c1d280405bc2f6c1bea214a1d742a"
181 "b996b35b63a82a5e470fa88dbf823cdd"
182 "0240" // INTEGER length 0x40 (exponent2)
183 "1b7b57449ad30d1518249a5f56bb9829"
184 "4d4b6ac12ffc86940497a5a5837a6cf9"
185 "46262b494526d328c11e1126380fde04"
186 "c24f916dec250892db09a6d77cdba351"
187 "0240" // INTEGER length 0x40 (coefficient)
188 "7762cd8f4d050da56bd591adb515d24d"
189 "7ccd32cca0d05f866d583514bd7324d5"
190 "f33645e8ed8b4a1cb3cc4a1d67987399"
191 "f2a09f5b3fb68c88d5e5d90ac33492d6"
192 // } end SEQUENCE (PrivateKey)
193 // } end SEQUENCE (PrivateKeyInfo)
194);
Selene Huang31ab4042020-04-29 04:22:39 -0700195
Selene Huange5727e62021-04-13 22:41:20 -0700196/*
197 * DER-encoded PKCS#8 format RSA key. Generated using:
198 *
199 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
200 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100201string rsa_2048_key = hex2str(
202 // RFC 5208 s5
203 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
204 "020100" // INTEGER length 1 value 0x00 (version)
205 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
206 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
207 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
208 "0500" // NULL (parameters)
209 // } end SEQUENCE (AlgorithmIdentifier)
210 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
211 // RFC 8017 A.1.2
212 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
213 "020100" // INTEGER length 1 value 0x00 (version)
214 "02820101" // INTEGER length 0x101 value (modulus) ...
215 "00BEBC342B56D443B1299F9A6A7056E8"
216 "0A897E318476A5A18029E63B2ED739A6"
217 "1791D339F58DC763D9D14911F2EDEC38"
218 "3DEE11F6319B44510E7A3ECD9B79B973"
219 "82E49500ACF8117DC89CAF0E621F7775"
220 "6554A2FD4664BFE7AB8B59AB48340DBF"
221 "A27B93B5A81F6ECDEB02D0759307128D"
222 "F3E3BAD4055C8B840216DFAA5700670E"
223 "6C5126F0962FCB70FF308F25049164CC"
224 "F76CC2DA66A7DD9A81A714C2809D6918"
225 "6133D29D84568E892B6FFBF3199BDB14"
226 "383EE224407F190358F111A949552ABA"
227 "6714227D1BD7F6B20DD0CB88F9467B71"
228 "9339F33BFF35B3870B3F62204E4286B0"
229 "948EA348B524544B5F9838F29EE643B0"
230 "79EEF8A713B220D7806924CDF7295070"
231 "C5"
232 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
233 "02820100" // INTEGER length 0x100 (privateExponent) value...
234 "69F377F35F2F584EF075353CCD1CA997"
235 "38DB3DBC7C7FF35F9366CE176DFD1B13"
236 "5AB10030344ABF5FBECF1D4659FDEF1C"
237 "0FC430834BE1BE3911951377BB3D563A"
238 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
239 "2686C7B4B3C09A7B8354133E6F93F790"
240 "D59EAEB92E84C9A4339302CCE28FDF04"
241 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
242 "6AB706645BF074A4E4090D06FB163124"
243 "365FD5EE7A20D350E9958CC30D91326E"
244 "1B292E9EF5DB408EC42DAF737D201497"
245 "04D0A678A0FB5B5446863B099228A352"
246 "D604BA8091A164D01D5AB05397C71EAD"
247 "20BE2A08FC528FE442817809C787FEE4"
248 "AB97F97B9130D022153EDC6EB6CBE7B0"
249 "F8E3473F2E901209B5DB10F93604DB01"
250 "028181" // INTEGER length 0x81 (prime1)
251 "00E83C0998214941EA4F9293F1B77E2E"
252 "99E6CF305FAF358238E126124FEAF2EB"
253 "9724B2EA7B78E6032343821A80E55D1D"
254 "88FB12D220C3F41A56142FEC85796D19"
255 "17F1E8C774F142B67D3D6E7B7E6B4383"
256 "E94DB5929089DBB346D5BDAB40CC2D96"
257 "EE0409475E175C63BF78CFD744136740"
258 "838127EA723FF3FE7FA368C1311B4A4E"
259 "05"
260 "028181" // INTEGER length 0x81 (prime2)
261 "00D240FCC0F5D7715CDE21CB2DC86EA1"
262 "46132EA3B06F61FF2AF54BF38473F59D"
263 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
264 "B1B58C39F95E4798CCBB43E83D0119AC"
265 "F532F359CA743C85199F0286610E2009"
266 "97D7312917179AC9B67558773212EC96"
267 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
268 "94D94E066A0900B7B70E82A44FB30053"
269 "C1"
270 "028181" // INTEGER length 0x81 (exponent1)
271 "00AD15DA1CBD6A492B66851BA8C316D3"
272 "8AB700E2CFDDD926A658003513C54BAA"
273 "152B30021D667D20078F500F8AD3E7F3"
274 "945D74A891ED1A28EAD0FEEAEC8C14A8"
275 "E834CF46A13D1378C99D18940823CFDD"
276 "27EC5810D59339E0C34198AC638E09C8"
277 "7CBB1B634A9864AE9F4D5EB2D53514F6"
278 "7B4CAEC048C8AB849A02E397618F3271"
279 "35"
280 "028180" // INTEGER length 0x80 (exponent2)
281 "1FA2C1A5331880A92D8F3E281C617108"
282 "BF38244F16E352E69ED417C7153F9EC3"
283 "18F211839C643DCF8B4DD67CE2AC312E"
284 "95178D5D952F06B1BF779F4916924B70"
285 "F582A23F11304E02A5E7565AE22A35E7"
286 "4FECC8B6FDC93F92A1A37703E4CF0E63"
287 "783BD02EB716A7ECBBFA606B10B74D01"
288 "579522E7EF84D91FC522292108D902C1"
289 "028180" // INTEGER length 0x80 (coefficient)
290 "796FE3825F9DCC85DF22D58690065D93"
291 "898ACD65C087BEA8DA3A63BF4549B795"
292 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
293 "0D74F40DED8E1102C52152A31B6165F8"
294 "3A6722AECFCC35A493D7634664B888A0"
295 "8D3EB034F12EA28BFEE346E205D33482"
296 "7F778B16ED40872BD29FCB36536B6E93"
297 "FFB06778696B4A9D81BB0A9423E63DE5"
298 // } end SEQUENCE (PrivateKey)
299 // } end SEQUENCE (PrivateKeyInfo)
300);
Selene Huange5727e62021-04-13 22:41:20 -0700301
David Drysdaled2cc8c22021-04-15 13:29:45 +0100302string ec_256_key = hex2str(
303 // RFC 5208 s5
304 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
305 "020100" // INTEGER length 1 value 0 (version)
306 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
307 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
308 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
309 "0608" // OBJECT IDENTIFIER length 8 (param)
310 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
311 // } end SEQUENCE (AlgorithmIdentifier)
312 "046d" // OCTET STRING length 0x6d (privateKey) holding...
313 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
314 "020101" // INTEGER length 1 value 1 (version)
315 "0420" // OCTET STRING length 0x20 (privateKey)
316 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
317 "941eed09366bc03299986481f3a4d859"
318 "a144" // TAG [1] len 0x44 (publicKey) {
319 "03420004bf85d7720d07c25461683bc6"
320 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
321 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
322 "bcc41c6eb00083cf3376d11fd44949e0"
323 "b2183bfe"
324 // } end SEQUENCE (ECPrivateKey)
325 // } end SEQUENCE (PrivateKeyInfo)
326);
Selene Huang31ab4042020-04-29 04:22:39 -0700327
David Drysdaled2cc8c22021-04-15 13:29:45 +0100328string ec_521_key = hex2str(
329 // RFC 5208 s5
330 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
331 "020100" // INTEGER length 1 value 0 (version)
332 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
333 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
334 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
335 "0605" // OBJECT IDENTIFIER length 5 (param)
336 "2B81040023" // 1.3.132.0.35 (secp521r1)
337 // } end SEQUENCE (AlgorithmIdentifier)
338 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
339 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
340 "020101" // INTEGER length 1 value 1 (version)
341 "0442" // OCTET STRING length 0x42 (privateKey)
342 "0011458C586DB5DAA92AFAB03F4FE46A"
343 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
344 "9D18D7D08B5BCFA0E53C75B064AD51C4"
345 "49BAE0258D54B94B1E885DED08ED4FB2"
346 "5CE9"
347 "A18189" // TAG [1] len 0x89 (publicKey) {
348 "03818600040149EC11C6DF0FA122C6A9"
349 "AFD9754A4FA9513A627CA329E349535A"
350 "5629875A8ADFBE27DCB932C051986377"
351 "108D054C28C6F39B6F2C9AF81802F9F3"
352 "26B842FF2E5F3C00AB7635CFB36157FC"
353 "0882D574A10D839C1A0C049DC5E0D775"
354 "E2EE50671A208431BB45E78E70BEFE93"
355 "0DB34818EE4D5C26259F5C6B8E28A652"
356 "950F9F88D7B4B2C9D9"
357 // } end SEQUENCE (ECPrivateKey)
358 // } end SEQUENCE (PrivateKeyInfo)
359);
Selene Huang31ab4042020-04-29 04:22:39 -0700360
David Drysdaled2cc8c22021-04-15 13:29:45 +0100361string ec_256_key_rfc5915 = hex2str(
362 // RFC 5208 s5
363 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
364 "020100" // INTEGER length 1 value 0 (version)
365 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
366 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
367 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
368 "0608" // OBJECT IDENTIFIER length 8 (param)
369 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
370 // } end SEQUENCE (AlgorithmIdentifier)
371 "0479" // OCTET STRING length 0x79 (privateKey) holding...
372 // RFC 5915 s3
373 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
374 "020101" // INTEGER length 1 value 1 (version)
375 "0420" // OCTET STRING length 0x42 (privateKey)
376 "782370a8c8ce5537baadd04dcff079c8"
377 "158cfa9c67b818b38e8d21c9fa750c1d"
378 "a00a" // TAG [0] length 0xa (parameters)
379 "0608" // OBJECT IDENTIFIER length 8
380 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
381 // } end TAG [0]
382 "a144" // TAG [1] length 0x44 (publicKey) {
383 "0342" // BIT STRING length 0x42
384 "00" // no pad bits
385 "04e2cc561ee701da0ad0ef0d176bb0c9"
386 "19d42e79c393fdc1bd6c4010d85cf2cf"
387 "8e68c905464666f98dad4f01573ba810"
388 "78b3428570a439ba3229fbc026c55068"
389 "2f"
390 // } end SEQUENCE (ECPrivateKey)
391 // } end SEQUENCE (PrivateKeyInfo)
392);
Selene Huang31ab4042020-04-29 04:22:39 -0700393
David Drysdaled2cc8c22021-04-15 13:29:45 +0100394string ec_256_key_sec1 = hex2str(
395 // RFC 5208 s5
396 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
397 "020100" // INTEGER length 1 value 0 (version)
398 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
399 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
400 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
401 "0608" // OBJECT IDENTIFIER length 8 (param)
402 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
403 // } end SEQUENCE (AlgorithmIdentifier)
404 "046d" // OCTET STRING length 0x6d (privateKey) holding...
405 // SEC1-v2 C.4
406 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
407 "020101" // INTEGER length 1 value 0x01 (version)
408 "0420" // OCTET STRING length 0x20 (privateKey)
409 "782370a8c8ce5537baadd04dcff079c8"
410 "158cfa9c67b818b38e8d21c9fa750c1d"
411 "a144" // TAG [1] length 0x44 (publicKey) {
412 "0342" // BIT STRING length 0x42
413 "00" // no pad bits
414 "04e2cc561ee701da0ad0ef0d176bb0c9"
415 "19d42e79c393fdc1bd6c4010d85cf2cf"
416 "8e68c905464666f98dad4f01573ba810"
417 "78b3428570a439ba3229fbc026c55068"
418 "2f"
419 // } end TAG [1] (publicKey)
420 // } end SEQUENCE (PrivateKeyInfo)
421);
Selene Huang31ab4042020-04-29 04:22:39 -0700422
David Drysdale42fe1892021-10-14 14:43:46 +0100423/**
424 * Ed25519 key pair generated as follows:
425 * ```
426 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
427 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
428 * Generating a ED25519 private key writing new private key to
429 * 'ed25519_priv.key'
430 * -----
431 * % cat ed25519_priv.key
432 * -----BEGIN PRIVATE KEY-----
433 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
434 * -----END PRIVATE KEY-----
435 * % der2ascii -pem -i ed25519_priv.key
436 * SEQUENCE {
437 * INTEGER { 0 }
438 * SEQUENCE {
439 * # ed25519
440 * OBJECT_IDENTIFIER { 1.3.101.112 }
441 * }
442 * OCTET_STRING {
443 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
444 * }
445 * }
446 * % cat ed25519.pem
447 * -----BEGIN CERTIFICATE-----
448 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
449 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
450 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
451 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
452 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
453 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
454 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
455 * -----END CERTIFICATE-----
456 * % openssl x509 -in ed25519.pem -text -noout
457 * Certificate:
458 * Data:
459 * Version: 3 (0x2)
460 * Serial Number:
461 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
462 * Signature Algorithm: ED25519
463 * Issuer: CN = fake.ed25519.com
464 * Validity
465 * Not Before: Oct 20 08:27:42 2021 GMT
466 * Not After : Sep 20 08:27:42 2023 GMT
467 * Subject: CN = fake.ed25519.com
468 * Subject Public Key Info:
469 * Public Key Algorithm: ED25519
470 * ED25519 Public-Key:
471 * pub:
472 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
473 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
474 * 56:91
475 * X509v3 extensions:
476 * X509v3 Subject Key Identifier:
477 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
478 * X509v3 Authority Key Identifier:
479 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
480 *
481 * X509v3 Basic Constraints: critical
482 * CA:TRUE
483 * Signature Algorithm: ED25519
484 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
485 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
486 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
487 * e7:07:32:60:32:8d:bb:eb:f6:0f
488 * ```
489 */
490string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
491string ed25519_pkcs8_key = hex2str(
492 // RFC 5208 s5
493 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
494 "0201" // INTEGER length 1 (Version)
495 "00" // version 0
496 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
497 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
498 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
499 // } end SEQUENCE (AlgorithmIdentifier)
500 "0422" // OCTET STRING length 0x22 (PrivateKey)
501 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
502 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
503 // } end SEQUENCE (PrivateKeyInfo)
504);
505string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
506
507/**
508 * X25519 key pair generated as follows:
509 * ```
510 * % openssl genpkey -algorithm X25519 > x25519_priv.key
511 * % cat x25519_priv.key
512 * -----BEGIN PRIVATE KEY-----
513 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
514 * -----END PRIVATE KEY-----
515 * % der2ascii -pem -i x25519_priv.key
516 * SEQUENCE {
517 * INTEGER { 0 }
518 * SEQUENCE {
519 * # x25519
520 * OBJECT_IDENTIFIER { 1.3.101.110 }
521 * }
522 * OCTET_STRING {
523 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
524 * }
525 * }
526 * ```
527 */
528
529string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
530string x25519_pkcs8_key = hex2str(
531 // RFC 5208 s5
532 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
533 "0201" // INTEGER length 1 (Version)
534 "00" // version 0
535 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
536 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
537 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
538 "0422" // OCTET STRING length 0x22 (PrivateKey)
539 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
540 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
541string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
542
Selene Huang31ab4042020-04-29 04:22:39 -0700543struct RSA_Delete {
544 void operator()(RSA* p) { RSA_free(p); }
545};
546
Selene Huang31ab4042020-04-29 04:22:39 -0700547std::string make_string(const uint8_t* data, size_t length) {
548 return std::string(reinterpret_cast<const char*>(data), length);
549}
550
551template <size_t N>
552std::string make_string(const uint8_t (&a)[N]) {
553 return make_string(a, N);
554}
555
556class AidlBuf : public vector<uint8_t> {
557 typedef vector<uint8_t> super;
558
559 public:
560 AidlBuf() {}
561 AidlBuf(const super& other) : super(other) {}
562 AidlBuf(super&& other) : super(std::move(other)) {}
563 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
564
565 AidlBuf& operator=(const super& other) {
566 super::operator=(other);
567 return *this;
568 }
569
570 AidlBuf& operator=(super&& other) {
571 super::operator=(std::move(other));
572 return *this;
573 }
574
575 AidlBuf& operator=(const string& other) {
576 resize(other.size());
577 for (size_t i = 0; i < other.size(); ++i) {
578 (*this)[i] = static_cast<uint8_t>(other[i]);
579 }
580 return *this;
581 }
582
583 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
584};
585
David Drysdale4dc01072021-04-01 12:17:35 +0100586string device_suffix(const string& name) {
587 size_t pos = name.find('/');
588 if (pos == string::npos) {
589 return name;
590 }
591 return name.substr(pos + 1);
592}
593
Seth Moore5a0320f2023-03-24 12:29:08 -0700594std::shared_ptr<IRemotelyProvisionedComponent> matching_rp_instance(const std::string& km_name) {
David Drysdale4dc01072021-04-01 12:17:35 +0100595 string km_suffix = device_suffix(km_name);
596
597 vector<string> rp_names =
598 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
599 for (const string& rp_name : rp_names) {
600 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
601 // KeyMint instance, assume they match.
602 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
603 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
Seth Moore5a0320f2023-03-24 12:29:08 -0700604 return IRemotelyProvisionedComponent::fromBinder(binder);
David Drysdale4dc01072021-04-01 12:17:35 +0100605 }
606 }
Seth Moore5a0320f2023-03-24 12:29:08 -0700607 return nullptr;
David Drysdale4dc01072021-04-01 12:17:35 +0100608}
609
Selene Huang31ab4042020-04-29 04:22:39 -0700610} // namespace
611
612class NewKeyGenerationTest : public KeyMintAidlTestBase {
613 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700614 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000615 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
Selene Huang31ab4042020-04-29 04:22:39 -0700616 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700617
Selene Huang31ab4042020-04-29 04:22:39 -0700618 // Check that some unexpected tags/values are NOT present.
619 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
620 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000621 }
622
623 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000624 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
David Drysdale7de9feb2021-03-05 14:56:19 +0000625 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
626 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
627
628 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000629 }
630
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000631 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics,
632 const KeyOrigin expectedKeyOrigin) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000633 // TODO(swillden): Distinguish which params should be in which auth list.
634 AuthorizationSet auths;
635 for (auto& entry : keyCharacteristics) {
636 auths.push_back(AuthorizationSet(entry.authorizations));
637 }
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000638 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, expectedKeyOrigin));
David Drysdale7de9feb2021-03-05 14:56:19 +0000639
640 // Verify that App data, ROT and auth timeout are NOT included.
641 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
642 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700643 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
644
David Drysdaled2cc8c22021-04-15 13:29:45 +0100645 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
646 // never adds it.
647 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
648
David Drysdale7de9feb2021-03-05 14:56:19 +0000649 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700650 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000651 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700652 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700653 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000654 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700655 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000656
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000657 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100658 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
659 EXPECT_TRUE(vendor_pl);
660 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000661
662 // Should include boot patchlevel (but there are some test scenarios where this is not
663 // possible).
664 if (check_boot_pl) {
665 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
666 EXPECT_TRUE(boot_pl);
667 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100668
David Drysdale7de9feb2021-03-05 14:56:19 +0000669 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700670 }
671};
672
673/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000674 * NewKeyGenerationTest.Aes
675 *
676 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
677 * have correct characteristics.
678 */
679TEST_P(NewKeyGenerationTest, Aes) {
680 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
681 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
682 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
683 SCOPED_TRACE(testing::Message()
684 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
685 vector<uint8_t> key_blob;
686 vector<KeyCharacteristics> key_characteristics;
687 auto builder = AuthorizationSetBuilder()
688 .AesEncryptionKey(key_size)
689 .BlockMode(block_mode)
690 .Padding(padding_mode)
691 .SetDefaultValidity();
692 if (block_mode == BlockMode::GCM) {
693 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
694 }
695 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
696
697 EXPECT_GT(key_blob.size(), 0U);
698 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100699 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000700
701 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
702
703 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
704 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
705 << "Key size " << key_size << "missing";
706
707 CheckedDeleteKey(&key_blob);
708 }
709 }
710 }
711}
712
713/*
714 * NewKeyGenerationTest.AesInvalidSize
715 *
716 * Verifies that specifying an invalid key size for AES key generation returns
717 * UNSUPPORTED_KEY_SIZE.
718 */
719TEST_P(NewKeyGenerationTest, AesInvalidSize) {
720 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
721 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
722 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
723 SCOPED_TRACE(testing::Message()
724 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
725 vector<uint8_t> key_blob;
726 vector<KeyCharacteristics> key_characteristics;
727 auto builder = AuthorizationSetBuilder()
728 .AesEncryptionKey(key_size)
729 .BlockMode(block_mode)
730 .Padding(padding_mode)
731 .SetDefaultValidity();
732 if (block_mode == BlockMode::GCM) {
733 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
734 }
735 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
736 GenerateKey(builder, &key_blob, &key_characteristics));
737 }
738 }
739 }
740
741 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
742 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100743 SCOPED_TRACE(testing::Message() << "AES-unknown-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000744 vector<uint8_t> key_blob;
745 vector<KeyCharacteristics> key_characteristics;
746 // No key size specified
747 auto builder = AuthorizationSetBuilder()
748 .Authorization(TAG_ALGORITHM, Algorithm::AES)
749 .BlockMode(block_mode)
750 .Padding(padding_mode)
751 .SetDefaultValidity();
752 if (block_mode == BlockMode::GCM) {
753 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
754 }
755 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
756 GenerateKey(builder, &key_blob, &key_characteristics));
757 }
758 }
759}
760
761/*
762 * NewKeyGenerationTest.AesInvalidPadding
763 *
764 * Verifies that specifying an invalid padding on AES keys gives a failure
765 * somewhere along the way.
766 */
767TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
768 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
769 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
770 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
771 SCOPED_TRACE(testing::Message()
772 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000773 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800774 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000775 .AesEncryptionKey(key_size)
776 .BlockMode(block_mode)
777 .Padding(padding_mode)
778 .SetDefaultValidity();
779 if (block_mode == BlockMode::GCM) {
780 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
781 }
782
Tommy Chiu3950b452021-05-03 22:01:46 +0800783 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000784 if (result == ErrorCode::OK) {
785 // Key creation was OK but has generated a key that cannot be used.
786 auto params =
787 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800788 if (block_mode == BlockMode::GCM) {
789 params.Authorization(TAG_MAC_LENGTH, 128);
790 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000791 auto result = Begin(KeyPurpose::ENCRYPT, params);
792 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100793 result == ErrorCode::INVALID_KEY_BLOB)
794 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000795 } else {
796 // The KeyMint implementation detected that the generated key
797 // is unusable.
798 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
799 }
800 }
801 }
802 }
803}
804
805/*
806 * NewKeyGenerationTest.AesGcmMissingMinMac
807 *
808 * Verifies that specifying an invalid key size for AES key generation returns
809 * UNSUPPORTED_KEY_SIZE.
810 */
811TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
812 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
813 BlockMode block_mode = BlockMode::GCM;
814 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
815 SCOPED_TRACE(testing::Message()
816 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
817 vector<uint8_t> key_blob;
818 vector<KeyCharacteristics> key_characteristics;
819 // No MIN_MAC_LENGTH provided.
820 auto builder = AuthorizationSetBuilder()
821 .AesEncryptionKey(key_size)
822 .BlockMode(block_mode)
823 .Padding(padding_mode)
824 .SetDefaultValidity();
825 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
826 GenerateKey(builder, &key_blob, &key_characteristics));
827 }
828 }
829}
830
831/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100832 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
833 *
834 * Verifies that specifying an invalid min MAC size for AES key generation returns
835 * UNSUPPORTED_MIN_MAC_LENGTH.
836 */
837TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
838 for (size_t min_mac_len : {88, 136}) {
839 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
840 BlockMode block_mode = BlockMode::GCM;
841 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
842 SCOPED_TRACE(testing::Message()
843 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
844 vector<uint8_t> key_blob;
845 vector<KeyCharacteristics> key_characteristics;
846 auto builder = AuthorizationSetBuilder()
847 .AesEncryptionKey(key_size)
848 .BlockMode(block_mode)
849 .Padding(padding_mode)
850 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
851 .SetDefaultValidity();
852 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
853 GenerateKey(builder, &key_blob, &key_characteristics));
854 }
855 }
856 }
857}
858
859/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000860 * NewKeyGenerationTest.TripleDes
861 *
862 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
863 * have correct characteristics.
864 */
865TEST_P(NewKeyGenerationTest, TripleDes) {
866 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
867 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
868 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
869 SCOPED_TRACE(testing::Message()
870 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
871 vector<uint8_t> key_blob;
872 vector<KeyCharacteristics> key_characteristics;
873 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
874 .TripleDesEncryptionKey(key_size)
875 .BlockMode(block_mode)
876 .Padding(padding_mode)
877 .Authorization(TAG_NO_AUTH_REQUIRED)
878 .SetDefaultValidity(),
879 &key_blob, &key_characteristics));
880
881 EXPECT_GT(key_blob.size(), 0U);
882 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100883 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000884
885 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
886
887 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
888 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
889 << "Key size " << key_size << "missing";
890
891 CheckedDeleteKey(&key_blob);
892 }
893 }
894 }
895}
896
897/*
898 * NewKeyGenerationTest.TripleDesWithAttestation
899 *
900 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
901 * have correct characteristics.
902 *
903 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
904 * put in a certificate) but which isn't an error.
905 */
906TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
907 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
908 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
909 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
910 SCOPED_TRACE(testing::Message()
911 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
912
913 auto challenge = "hello";
914 auto app_id = "foo";
915
916 vector<uint8_t> key_blob;
917 vector<KeyCharacteristics> key_characteristics;
918 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
919 .TripleDesEncryptionKey(key_size)
920 .BlockMode(block_mode)
921 .Padding(padding_mode)
922 .Authorization(TAG_NO_AUTH_REQUIRED)
923 .AttestationChallenge(challenge)
924 .AttestationApplicationId(app_id)
925 .SetDefaultValidity(),
926 &key_blob, &key_characteristics));
927
928 EXPECT_GT(key_blob.size(), 0U);
929 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100930 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000931
932 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
933
934 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
935 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
936 << "Key size " << key_size << "missing";
937
938 CheckedDeleteKey(&key_blob);
939 }
940 }
941 }
942}
943
944/*
945 * NewKeyGenerationTest.TripleDesInvalidSize
946 *
947 * Verifies that specifying an invalid key size for 3-DES key generation returns
948 * UNSUPPORTED_KEY_SIZE.
949 */
950TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
951 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
952 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
953 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
954 SCOPED_TRACE(testing::Message()
955 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
956 vector<uint8_t> key_blob;
957 vector<KeyCharacteristics> key_characteristics;
958 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
959 GenerateKey(AuthorizationSetBuilder()
960 .TripleDesEncryptionKey(key_size)
961 .BlockMode(block_mode)
962 .Padding(padding_mode)
963 .Authorization(TAG_NO_AUTH_REQUIRED)
964 .SetDefaultValidity(),
965 &key_blob, &key_characteristics));
966 }
967 }
968 }
969
970 // Omitting the key size fails.
971 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
972 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
973 SCOPED_TRACE(testing::Message()
974 << "3DES-default-" << block_mode << "-" << padding_mode);
975 vector<uint8_t> key_blob;
976 vector<KeyCharacteristics> key_characteristics;
977 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
978 GenerateKey(AuthorizationSetBuilder()
979 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
980 .BlockMode(block_mode)
981 .Padding(padding_mode)
982 .Authorization(TAG_NO_AUTH_REQUIRED)
983 .SetDefaultValidity(),
984 &key_blob, &key_characteristics));
985 }
986 }
987}
988
989/*
Selene Huang31ab4042020-04-29 04:22:39 -0700990 * NewKeyGenerationTest.Rsa
991 *
992 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
993 * have correct characteristics.
994 */
995TEST_P(NewKeyGenerationTest, Rsa) {
996 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100997 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -0700998 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700999 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001000 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1001 .RsaSigningKey(key_size, 65537)
1002 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001003 .Padding(PaddingMode::NONE)
1004 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001005 &key_blob, &key_characteristics));
1006
1007 ASSERT_GT(key_blob.size(), 0U);
1008 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001009 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001010
Shawn Willden7f424372021-01-10 18:06:50 -07001011 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001012
1013 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1014 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1015 << "Key size " << key_size << "missing";
1016 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1017
1018 CheckedDeleteKey(&key_blob);
1019 }
1020}
1021
1022/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001023 * NewKeyGenerationTest.RsaWithMissingValidity
1024 *
1025 * Verifies that keymint returns an error while generating asymmetric key
1026 * without providing NOT_BEFORE and NOT_AFTER parameters.
1027 */
1028TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
Seth Moore7dc1fda2022-12-12 16:56:20 -08001029 if (AidlVersion() < 3) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001030 /*
1031 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1032 * specified for asymmetric key generation. However, this was not
1033 * checked at the time so we can only be strict about checking this for
1034 * implementations of KeyMint version 2 and above.
1035 */
1036 GTEST_SKIP() << "Validity strict since KeyMint v2";
1037 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001038 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1039 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1040 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1041
1042 vector<uint8_t> key_blob;
1043 vector<KeyCharacteristics> key_characteristics;
1044 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1045 GenerateKey(AuthorizationSetBuilder()
1046 .RsaSigningKey(2048, 65537)
1047 .Digest(Digest::NONE)
1048 .Padding(PaddingMode::NONE)
1049 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1050 kUndefinedExpirationDateTime),
1051 &key_blob, &key_characteristics));
1052
1053 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1054 GenerateKey(AuthorizationSetBuilder()
1055 .RsaSigningKey(2048, 65537)
1056 .Digest(Digest::NONE)
1057 .Padding(PaddingMode::NONE)
1058 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1059 &key_blob, &key_characteristics));
1060}
1061
1062/*
David Drysdalead785f52023-03-27 19:53:01 +01001063 * NewKeyGenerationTest.RsaWithSpecifiedValidity
1064 *
1065 * Verifies that KeyMint respects specified NOT_BEFORE and NOT_AFTER certificate dates.
1066 */
1067TEST_P(NewKeyGenerationTest, RsaWithSpecifiedValidity) {
1068 vector<uint8_t> key_blob;
1069 vector<KeyCharacteristics> key_characteristics;
1070 ASSERT_EQ(ErrorCode::OK,
1071 GenerateKey(AuthorizationSetBuilder()
1072 .RsaSigningKey(2048, 65537)
1073 .Digest(Digest::NONE)
1074 .Padding(PaddingMode::NONE)
1075 .Authorization(TAG_CERTIFICATE_NOT_BEFORE,
1076 1183806000000 /* 2007-07-07T11:00:00Z */)
1077 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1078 1916049600000 /* 2030-09-19T12:00:00Z */),
1079 &key_blob, &key_characteristics));
1080 ASSERT_GT(cert_chain_.size(), 0);
1081
1082 X509_Ptr cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1083 ASSERT_TRUE(!!cert.get());
1084
1085 const ASN1_TIME* not_before = X509_get0_notBefore(cert.get());
1086 ASSERT_NE(not_before, nullptr);
1087 time_t not_before_time;
1088 ASSERT_EQ(ASN1_TIME_to_time_t(not_before, &not_before_time), 1);
1089 EXPECT_EQ(not_before_time, 1183806000);
1090
1091 const ASN1_TIME* not_after = X509_get0_notAfter(cert.get());
1092 ASSERT_NE(not_after, nullptr);
1093 time_t not_after_time;
1094 ASSERT_EQ(ASN1_TIME_to_time_t(not_after, &not_after_time), 1);
1095 EXPECT_EQ(not_after_time, 1916049600);
1096}
1097
1098/*
Qi Wud22ec842020-11-26 13:27:53 +08001099 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001100 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001101 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1102 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001103 */
1104TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001105 auto challenge = "hello";
1106 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001107
Selene Huang6e46f142021-04-20 19:20:11 -07001108 auto subject = "cert subj 2";
1109 vector<uint8_t> subject_der(make_name_from_str(subject));
1110
1111 uint64_t serial_int = 66;
1112 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1113
Selene Huang4f64c222021-04-13 19:54:36 -07001114 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001115 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001116 vector<uint8_t> key_blob;
1117 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001118 auto builder = AuthorizationSetBuilder()
1119 .RsaSigningKey(key_size, 65537)
1120 .Digest(Digest::NONE)
1121 .Padding(PaddingMode::NONE)
1122 .AttestationChallenge(challenge)
1123 .AttestationApplicationId(app_id)
1124 .Authorization(TAG_NO_AUTH_REQUIRED)
1125 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1126 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1127 .SetDefaultValidity();
1128
1129 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001130 // Strongbox may not support factory provisioned attestation key.
1131 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001132 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1133 result = GenerateKeyWithSelfSignedAttestKey(
1134 AuthorizationSetBuilder()
1135 .RsaKey(key_size, 65537)
1136 .AttestKey()
1137 .SetDefaultValidity(), /* attest key params */
1138 builder, &key_blob, &key_characteristics);
1139 }
subrahmanyaman05642492022-02-05 07:10:56 +00001140 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001141 ASSERT_EQ(ErrorCode::OK, result);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001142 ASSERT_GT(key_blob.size(), 0U);
1143 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001144 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001145
1146 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1147
1148 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1149 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1150 << "Key size " << key_size << "missing";
1151 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1152
David Drysdalea8a888e2022-06-08 12:43:56 +01001153 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001154 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001155 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001156
1157 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1158 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001159 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001160 sw_enforced, hw_enforced, SecLevel(),
1161 cert_chain_[0].encodedCertificate));
1162
1163 CheckedDeleteKey(&key_blob);
1164 }
1165}
1166
1167/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001168 * NewKeyGenerationTest.RsaWithRkpAttestation
David Drysdale4dc01072021-04-01 12:17:35 +01001169 *
Seth Moore7dc1fda2022-12-12 16:56:20 -08001170 * Verifies that keymint can generate all required RSA key sizes using an attestation key
David Drysdale4dc01072021-04-01 12:17:35 +01001171 * that has been generated using an associate IRemotelyProvisionedComponent.
1172 */
Seth Moore7dc1fda2022-12-12 16:56:20 -08001173TEST_P(NewKeyGenerationTest, RsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001174 if (!IsRkpSupportRequired()) {
1175 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001176 }
1177
Seth Moore5a0320f2023-03-24 12:29:08 -07001178 // Check for an IRemotelyProvisionedComponent instance associated with the
1179 // KeyMint instance.
1180 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1181 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1182 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1183 }
1184 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1185 << GetParam();
David Drysdale4dc01072021-04-01 12:17:35 +01001186
1187 // Generate a P-256 keypair to use as an attestation key.
1188 MacedPublicKey macedPubKey;
1189 std::vector<uint8_t> privateKeyBlob;
1190 auto status =
1191 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1192 ASSERT_TRUE(status.isOk());
1193 vector<uint8_t> coseKeyData;
1194 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1195
1196 AttestationKey attestation_key;
1197 attestation_key.keyBlob = std::move(privateKeyBlob);
1198 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1199
1200 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001201 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdale4dc01072021-04-01 12:17:35 +01001202 auto challenge = "hello";
1203 auto app_id = "foo";
1204
1205 vector<uint8_t> key_blob;
1206 vector<KeyCharacteristics> key_characteristics;
1207 ASSERT_EQ(ErrorCode::OK,
1208 GenerateKey(AuthorizationSetBuilder()
1209 .RsaSigningKey(key_size, 65537)
1210 .Digest(Digest::NONE)
1211 .Padding(PaddingMode::NONE)
1212 .AttestationChallenge(challenge)
1213 .AttestationApplicationId(app_id)
1214 .Authorization(TAG_NO_AUTH_REQUIRED)
1215 .SetDefaultValidity(),
1216 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1217
1218 ASSERT_GT(key_blob.size(), 0U);
1219 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001220 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001221
1222 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1223
1224 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1225 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1226 << "Key size " << key_size << "missing";
1227 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1228
1229 // Attestation by itself is not valid (last entry is not self-signed).
1230 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1231
1232 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001233 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001234 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1235 ASSERT_TRUE(key_cert.get());
1236 EVP_PKEY_Ptr signing_pubkey;
1237 p256_pub_key(coseKeyData, &signing_pubkey);
1238 ASSERT_TRUE(signing_pubkey.get());
1239
1240 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1241 << "Verification of attested certificate failed "
1242 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1243
1244 CheckedDeleteKey(&key_blob);
1245 }
1246}
1247
1248/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001249 * NewKeyGenerationTest.EcdsaWithRkpAttestation
1250 *
1251 * Verifies that keymint can generate all required ECDSA key sizes using an attestation key
1252 * that has been generated using an associate IRemotelyProvisionedComponent.
1253 */
1254TEST_P(NewKeyGenerationTest, EcdsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001255 if (!IsRkpSupportRequired()) {
1256 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001257 }
1258
Seth Moore5a0320f2023-03-24 12:29:08 -07001259 // Check for an IRemotelyProvisionedComponent instance associated with the
1260 // KeyMint instance.
1261 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1262 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1263 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1264 }
1265 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1266 << GetParam();
Seth Moore7dc1fda2022-12-12 16:56:20 -08001267
1268 // Generate a P-256 keypair to use as an attestation key.
1269 MacedPublicKey macedPubKey;
1270 std::vector<uint8_t> privateKeyBlob;
1271 auto status =
1272 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1273 ASSERT_TRUE(status.isOk());
1274 vector<uint8_t> coseKeyData;
1275 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1276
1277 AttestationKey attestation_key;
1278 attestation_key.keyBlob = std::move(privateKeyBlob);
1279 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1280
1281 for (auto curve : ValidCurves()) {
1282 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
1283 auto challenge = "hello";
1284 auto app_id = "foo";
1285
1286 vector<uint8_t> key_blob;
1287 vector<KeyCharacteristics> key_characteristics;
1288 ASSERT_EQ(ErrorCode::OK,
1289 GenerateKey(AuthorizationSetBuilder()
1290 .EcdsaSigningKey(curve)
1291 .Digest(Digest::NONE)
1292 .AttestationChallenge(challenge)
1293 .AttestationApplicationId(app_id)
1294 .Authorization(TAG_NO_AUTH_REQUIRED)
1295 .SetDefaultValidity(),
1296 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1297
1298 ASSERT_GT(key_blob.size(), 0U);
1299 CheckBaseParams(key_characteristics);
1300 CheckCharacteristics(key_blob, key_characteristics);
1301
1302 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1303
1304 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1305 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1306
1307 // Attestation by itself is not valid (last entry is not self-signed).
1308 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1309
1310 // The signature over the attested key should correspond to the P256 public key.
1311 ASSERT_GT(cert_chain_.size(), 0);
1312 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1313 ASSERT_TRUE(key_cert.get());
1314 EVP_PKEY_Ptr signing_pubkey;
1315 p256_pub_key(coseKeyData, &signing_pubkey);
1316 ASSERT_TRUE(signing_pubkey.get());
1317
1318 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1319 << "Verification of attested certificate failed "
1320 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1321
1322 CheckedDeleteKey(&key_blob);
1323 }
1324}
1325
1326/*
Selene Huang4f64c222021-04-13 19:54:36 -07001327 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1328 *
1329 * Verifies that keymint attestation for RSA encryption keys with challenge and
1330 * app id is also successful.
1331 */
1332TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1333 auto key_size = 2048;
1334 auto challenge = "hello";
1335 auto app_id = "foo";
1336
Selene Huang6e46f142021-04-20 19:20:11 -07001337 auto subject = "subj 2";
1338 vector<uint8_t> subject_der(make_name_from_str(subject));
1339
1340 uint64_t serial_int = 111166;
1341 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1342
Selene Huang4f64c222021-04-13 19:54:36 -07001343 vector<uint8_t> key_blob;
1344 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001345 auto builder = AuthorizationSetBuilder()
1346 .RsaEncryptionKey(key_size, 65537)
1347 .Padding(PaddingMode::NONE)
1348 .AttestationChallenge(challenge)
1349 .AttestationApplicationId(app_id)
1350 .Authorization(TAG_NO_AUTH_REQUIRED)
1351 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1352 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1353 .SetDefaultValidity();
1354
1355 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001356 // Strongbox may not support factory provisioned attestation key.
1357 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001358 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1359 result = GenerateKeyWithSelfSignedAttestKey(
1360 AuthorizationSetBuilder()
1361 .RsaKey(key_size, 65537)
1362 .AttestKey()
1363 .SetDefaultValidity(), /* attest key params */
1364 builder, &key_blob, &key_characteristics);
1365 }
subrahmanyaman05642492022-02-05 07:10:56 +00001366 }
1367 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001368
1369 ASSERT_GT(key_blob.size(), 0U);
1370 AuthorizationSet auths;
1371 for (auto& entry : key_characteristics) {
1372 auths.push_back(AuthorizationSet(entry.authorizations));
1373 }
1374
1375 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1376 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1377
1378 // Verify that App data and ROT are NOT included.
1379 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1380 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1381
1382 // Check that some unexpected tags/values are NOT present.
1383 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1384 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1385
1386 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1387
1388 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1389 ASSERT_TRUE(os_ver);
1390 EXPECT_EQ(*os_ver, os_version());
1391
1392 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1393
1394 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1395 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1396 << "Key size " << key_size << "missing";
1397 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1398
David Drysdalea8a888e2022-06-08 12:43:56 +01001399 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001400 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001401 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001402
1403 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1404 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001405 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001406 sw_enforced, hw_enforced, SecLevel(),
1407 cert_chain_[0].encodedCertificate));
1408
1409 CheckedDeleteKey(&key_blob);
1410}
1411
1412/*
1413 * NewKeyGenerationTest.RsaWithSelfSign
1414 *
1415 * Verifies that attesting to RSA key generation is successful, and returns
1416 * self signed certificate if no challenge is provided. And signing etc
1417 * works as expected.
1418 */
1419TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001420 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1421 vector<uint8_t> subject_der(make_name_from_str(subject));
1422
1423 uint64_t serial_int = 0;
1424 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1425
Selene Huang4f64c222021-04-13 19:54:36 -07001426 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001427 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang4f64c222021-04-13 19:54:36 -07001428 vector<uint8_t> key_blob;
1429 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001430 ASSERT_EQ(ErrorCode::OK,
1431 GenerateKey(AuthorizationSetBuilder()
1432 .RsaSigningKey(key_size, 65537)
1433 .Digest(Digest::NONE)
1434 .Padding(PaddingMode::NONE)
1435 .Authorization(TAG_NO_AUTH_REQUIRED)
1436 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1437 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1438 .SetDefaultValidity(),
1439 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001440
1441 ASSERT_GT(key_blob.size(), 0U);
1442 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001443 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001444
1445 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1446
1447 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1448 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1449 << "Key size " << key_size << "missing";
1450 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1451
David Drysdalea8a888e2022-06-08 12:43:56 +01001452 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001453 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001454 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001455
1456 CheckedDeleteKey(&key_blob);
1457 }
1458}
1459
1460/*
1461 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1462 *
1463 * Verifies that attesting to RSA checks for missing app ID.
1464 */
1465TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1466 auto challenge = "hello";
1467 vector<uint8_t> key_blob;
1468 vector<KeyCharacteristics> key_characteristics;
1469
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001470 auto builder = AuthorizationSetBuilder()
1471 .RsaSigningKey(2048, 65537)
1472 .Digest(Digest::NONE)
1473 .Padding(PaddingMode::NONE)
1474 .AttestationChallenge(challenge)
1475 .Authorization(TAG_NO_AUTH_REQUIRED)
1476 .SetDefaultValidity();
1477
1478 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001479 // Strongbox may not support factory provisioned attestation key.
1480 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001481 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1482 result = GenerateKeyWithSelfSignedAttestKey(
1483 AuthorizationSetBuilder()
1484 .RsaKey(2048, 65537)
1485 .AttestKey()
1486 .SetDefaultValidity(), /* attest key params */
1487 builder, &key_blob, &key_characteristics);
1488 }
subrahmanyaman05642492022-02-05 07:10:56 +00001489 }
1490 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001491}
1492
1493/*
1494 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1495 *
1496 * Verifies that attesting to RSA ignores app id if challenge is missing.
1497 */
1498TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1499 auto key_size = 2048;
1500 auto app_id = "foo";
1501
Selene Huang6e46f142021-04-20 19:20:11 -07001502 auto subject = "cert subj 2";
1503 vector<uint8_t> subject_der(make_name_from_str(subject));
1504
1505 uint64_t serial_int = 1;
1506 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1507
Selene Huang4f64c222021-04-13 19:54:36 -07001508 vector<uint8_t> key_blob;
1509 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001510 ASSERT_EQ(ErrorCode::OK,
1511 GenerateKey(AuthorizationSetBuilder()
1512 .RsaSigningKey(key_size, 65537)
1513 .Digest(Digest::NONE)
1514 .Padding(PaddingMode::NONE)
1515 .AttestationApplicationId(app_id)
1516 .Authorization(TAG_NO_AUTH_REQUIRED)
1517 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1518 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1519 .SetDefaultValidity(),
1520 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001521
1522 ASSERT_GT(key_blob.size(), 0U);
1523 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001524 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001525
1526 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1527
1528 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1529 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1530 << "Key size " << key_size << "missing";
1531 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1532
David Drysdalea8a888e2022-06-08 12:43:56 +01001533 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001534 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001535 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1536 ASSERT_EQ(cert_chain_.size(), 1);
1537
1538 CheckedDeleteKey(&key_blob);
1539}
1540
1541/*
Qi Wud22ec842020-11-26 13:27:53 +08001542 * NewKeyGenerationTest.LimitedUsageRsa
1543 *
1544 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1545 * resulting keys have correct characteristics.
1546 */
1547TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1548 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001549 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wud22ec842020-11-26 13:27:53 +08001550 vector<uint8_t> key_blob;
1551 vector<KeyCharacteristics> key_characteristics;
1552 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1553 .RsaSigningKey(key_size, 65537)
1554 .Digest(Digest::NONE)
1555 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001556 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1557 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001558 &key_blob, &key_characteristics));
1559
1560 ASSERT_GT(key_blob.size(), 0U);
1561 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001562 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001563
1564 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1565
1566 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1567 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1568 << "Key size " << key_size << "missing";
1569 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1570
1571 // Check the usage count limit tag appears in the authorizations.
1572 AuthorizationSet auths;
1573 for (auto& entry : key_characteristics) {
1574 auths.push_back(AuthorizationSet(entry.authorizations));
1575 }
1576 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1577 << "key usage count limit " << 1U << " missing";
1578
1579 CheckedDeleteKey(&key_blob);
1580 }
1581}
1582
1583/*
Qi Wubeefae42021-01-28 23:16:37 +08001584 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1585 *
1586 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1587 * resulting keys have correct characteristics and attestation.
1588 */
1589TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001590 auto challenge = "hello";
1591 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001592
Selene Huang6e46f142021-04-20 19:20:11 -07001593 auto subject = "cert subj 2";
1594 vector<uint8_t> subject_der(make_name_from_str(subject));
1595
1596 uint64_t serial_int = 66;
1597 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1598
Selene Huang4f64c222021-04-13 19:54:36 -07001599 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001600 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wubeefae42021-01-28 23:16:37 +08001601 vector<uint8_t> key_blob;
1602 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001603 auto builder = AuthorizationSetBuilder()
1604 .RsaSigningKey(key_size, 65537)
1605 .Digest(Digest::NONE)
1606 .Padding(PaddingMode::NONE)
1607 .AttestationChallenge(challenge)
1608 .AttestationApplicationId(app_id)
1609 .Authorization(TAG_NO_AUTH_REQUIRED)
1610 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1611 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1612 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1613 .SetDefaultValidity();
1614
1615 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001616 // Strongbox may not support factory provisioned attestation key.
1617 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001618 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1619 result = GenerateKeyWithSelfSignedAttestKey(
1620 AuthorizationSetBuilder()
1621 .RsaKey(key_size, 65537)
1622 .AttestKey()
1623 .SetDefaultValidity(), /* attest key params */
1624 builder, &key_blob, &key_characteristics);
1625 }
subrahmanyaman05642492022-02-05 07:10:56 +00001626 }
1627 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001628
1629 ASSERT_GT(key_blob.size(), 0U);
1630 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001631 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001632
1633 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1634
1635 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1636 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1637 << "Key size " << key_size << "missing";
1638 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1639
1640 // Check the usage count limit tag appears in the authorizations.
1641 AuthorizationSet auths;
1642 for (auto& entry : key_characteristics) {
1643 auths.push_back(AuthorizationSet(entry.authorizations));
1644 }
1645 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1646 << "key usage count limit " << 1U << " missing";
1647
1648 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001649 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001650 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001651 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001652
1653 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1654 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001655 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001656 sw_enforced, hw_enforced, SecLevel(),
1657 cert_chain_[0].encodedCertificate));
1658
1659 CheckedDeleteKey(&key_blob);
1660 }
1661}
1662
1663/*
Selene Huang31ab4042020-04-29 04:22:39 -07001664 * NewKeyGenerationTest.NoInvalidRsaSizes
1665 *
1666 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1667 */
1668TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1669 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001670 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07001671 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001672 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001673 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1674 GenerateKey(AuthorizationSetBuilder()
1675 .RsaSigningKey(key_size, 65537)
1676 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001677 .Padding(PaddingMode::NONE)
1678 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001679 &key_blob, &key_characteristics));
1680 }
1681}
1682
1683/*
1684 * NewKeyGenerationTest.RsaNoDefaultSize
1685 *
1686 * Verifies that failing to specify a key size for RSA key generation returns
1687 * UNSUPPORTED_KEY_SIZE.
1688 */
1689TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1690 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1691 GenerateKey(AuthorizationSetBuilder()
1692 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1693 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001694 .SigningKey()
1695 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001696}
1697
1698/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001699 * NewKeyGenerationTest.RsaMissingParams
1700 *
1701 * Verifies that omitting optional tags works.
1702 */
1703TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1704 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001705 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdaled2cc8c22021-04-15 13:29:45 +01001706 ASSERT_EQ(ErrorCode::OK,
1707 GenerateKey(
1708 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1709 CheckedDeleteKey();
1710 }
1711}
1712
1713/*
Selene Huang31ab4042020-04-29 04:22:39 -07001714 * NewKeyGenerationTest.Ecdsa
1715 *
David Drysdale42fe1892021-10-14 14:43:46 +01001716 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001717 * have correct characteristics.
1718 */
1719TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001720 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001721 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07001722 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001723 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001724 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001725 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001726 .Digest(Digest::NONE)
1727 .SetDefaultValidity(),
1728 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001729 ASSERT_GT(key_blob.size(), 0U);
1730 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001731 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001732
Shawn Willden7f424372021-01-10 18:06:50 -07001733 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001734
1735 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001736 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001737
1738 CheckedDeleteKey(&key_blob);
1739 }
1740}
1741
1742/*
David Drysdale42fe1892021-10-14 14:43:46 +01001743 * NewKeyGenerationTest.EcdsaCurve25519
1744 *
1745 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1746 * has correct characteristics.
1747 */
1748TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1749 if (!Curve25519Supported()) {
1750 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1751 }
1752
1753 EcCurve curve = EcCurve::CURVE_25519;
1754 vector<uint8_t> key_blob;
1755 vector<KeyCharacteristics> key_characteristics;
1756 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1757 .EcdsaSigningKey(curve)
1758 .Digest(Digest::NONE)
1759 .SetDefaultValidity(),
1760 &key_blob, &key_characteristics);
1761 ASSERT_EQ(result, ErrorCode::OK);
1762 ASSERT_GT(key_blob.size(), 0U);
1763
1764 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1765 ASSERT_GT(cert_chain_.size(), 0);
1766
1767 CheckBaseParams(key_characteristics);
1768 CheckCharacteristics(key_blob, key_characteristics);
1769
1770 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1771
1772 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1773 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1774
1775 CheckedDeleteKey(&key_blob);
1776}
1777
1778/*
1779 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1780 *
1781 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1782 * SIGN and AGREE_KEY.
1783 */
1784TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1785 if (!Curve25519Supported()) {
1786 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1787 }
1788
1789 EcCurve curve = EcCurve::CURVE_25519;
1790 vector<uint8_t> key_blob;
1791 vector<KeyCharacteristics> key_characteristics;
1792 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1793 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1794 .EcdsaSigningKey(curve)
1795 .Digest(Digest::NONE)
1796 .SetDefaultValidity(),
1797 &key_blob, &key_characteristics);
1798 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1799}
1800
1801/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001802 * NewKeyGenerationTest.EcdsaWithMissingValidity
1803 *
1804 * Verifies that keymint returns an error while generating asymmetric key
1805 * without providing NOT_BEFORE and NOT_AFTER parameters.
1806 */
1807TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001808 if (AidlVersion() < 2) {
1809 /*
1810 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1811 * specified for asymmetric key generation. However, this was not
1812 * checked at the time so we can only be strict about checking this for
1813 * implementations of KeyMint version 2 and above.
1814 */
1815 GTEST_SKIP() << "Validity strict since KeyMint v2";
1816 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001817 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1818 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1819 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1820
1821 vector<uint8_t> key_blob;
1822 vector<KeyCharacteristics> key_characteristics;
1823 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1824 GenerateKey(AuthorizationSetBuilder()
1825 .EcdsaSigningKey(EcCurve::P_256)
1826 .Digest(Digest::NONE)
1827 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1828 kUndefinedExpirationDateTime),
1829 &key_blob, &key_characteristics));
1830
1831 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1832 GenerateKey(AuthorizationSetBuilder()
1833 .EcdsaSigningKey(EcCurve::P_256)
1834 .Digest(Digest::NONE)
1835 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1836 &key_blob, &key_characteristics));
1837}
1838
1839/*
Selene Huang4f64c222021-04-13 19:54:36 -07001840 * NewKeyGenerationTest.EcdsaAttestation
1841 *
1842 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1843 * an attestation will be generated.
1844 */
1845TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1846 auto challenge = "hello";
1847 auto app_id = "foo";
1848
Selene Huang6e46f142021-04-20 19:20:11 -07001849 auto subject = "cert subj 2";
1850 vector<uint8_t> subject_der(make_name_from_str(subject));
1851
1852 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1853 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1854
David Drysdaledf09e542021-06-08 15:46:11 +01001855 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001856 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07001857 vector<uint8_t> key_blob;
1858 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001859 auto builder = AuthorizationSetBuilder()
1860 .Authorization(TAG_NO_AUTH_REQUIRED)
1861 .EcdsaSigningKey(curve)
1862 .Digest(Digest::NONE)
1863 .AttestationChallenge(challenge)
1864 .AttestationApplicationId(app_id)
1865 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1866 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1867 .SetDefaultValidity();
1868
1869 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001870 // Strongbox may not support factory provisioned attestation key.
1871 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001872 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1873 result = GenerateKeyWithSelfSignedAttestKey(
1874 AuthorizationSetBuilder()
1875 .EcdsaKey(curve)
1876 .AttestKey()
1877 .SetDefaultValidity(), /* attest key params */
1878 builder, &key_blob, &key_characteristics);
1879 }
subrahmanyaman05642492022-02-05 07:10:56 +00001880 }
1881 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001882 ASSERT_GT(key_blob.size(), 0U);
1883 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001884 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001885
1886 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1887
1888 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001889 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001890
1891 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1892 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001893 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001894
1895 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1896 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001897 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001898 sw_enforced, hw_enforced, SecLevel(),
1899 cert_chain_[0].encodedCertificate));
1900
1901 CheckedDeleteKey(&key_blob);
1902 }
1903}
1904
1905/*
David Drysdale42fe1892021-10-14 14:43:46 +01001906 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1907 *
1908 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1909 * an attestation will be generated.
1910 */
1911TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1912 if (!Curve25519Supported()) {
1913 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1914 }
1915
1916 EcCurve curve = EcCurve::CURVE_25519;
1917 auto challenge = "hello";
1918 auto app_id = "foo";
1919
1920 auto subject = "cert subj 2";
1921 vector<uint8_t> subject_der(make_name_from_str(subject));
1922
1923 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1924 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1925
1926 vector<uint8_t> key_blob;
1927 vector<KeyCharacteristics> key_characteristics;
1928 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1929 .Authorization(TAG_NO_AUTH_REQUIRED)
1930 .EcdsaSigningKey(curve)
1931 .Digest(Digest::NONE)
1932 .AttestationChallenge(challenge)
1933 .AttestationApplicationId(app_id)
1934 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1935 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1936 .SetDefaultValidity(),
1937 &key_blob, &key_characteristics);
1938 ASSERT_EQ(ErrorCode::OK, result);
1939 ASSERT_GT(key_blob.size(), 0U);
1940 CheckBaseParams(key_characteristics);
1941 CheckCharacteristics(key_blob, key_characteristics);
1942
1943 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1944
1945 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1946 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1947
1948 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1949 ASSERT_GT(cert_chain_.size(), 0);
1950 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1951
1952 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1953 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1954 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1955 sw_enforced, hw_enforced, SecLevel(),
1956 cert_chain_[0].encodedCertificate));
1957
1958 CheckedDeleteKey(&key_blob);
1959}
1960
1961/*
David Drysdale37af4b32021-05-14 16:46:59 +01001962 * NewKeyGenerationTest.EcdsaAttestationTags
1963 *
1964 * Verifies that creation of an attested ECDSA key includes various tags in the
1965 * attestation extension.
1966 */
1967TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1968 auto challenge = "hello";
1969 auto app_id = "foo";
1970 auto subject = "cert subj 2";
1971 vector<uint8_t> subject_der(make_name_from_str(subject));
1972 uint64_t serial_int = 0x1010;
1973 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1974 const AuthorizationSetBuilder base_builder =
1975 AuthorizationSetBuilder()
1976 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001977 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001978 .Digest(Digest::NONE)
1979 .AttestationChallenge(challenge)
1980 .AttestationApplicationId(app_id)
1981 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1982 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1983 .SetDefaultValidity();
1984
1985 // Various tags that map to fields in the attestation extension ASN.1 schema.
1986 auto extra_tags = AuthorizationSetBuilder()
1987 .Authorization(TAG_ROLLBACK_RESISTANCE)
1988 .Authorization(TAG_EARLY_BOOT_ONLY)
1989 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1990 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1991 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1992 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1993 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1994 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1995 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1996 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1997 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1998 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001999
David Drysdale37af4b32021-05-14 16:46:59 +01002000 for (const KeyParameter& tag : extra_tags) {
2001 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2002 vector<uint8_t> key_blob;
2003 vector<KeyCharacteristics> key_characteristics;
2004 AuthorizationSetBuilder builder = base_builder;
2005 builder.push_back(tag);
2006 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
2007 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
2008 tag.tag == TAG_ROLLBACK_RESISTANCE) {
2009 continue;
2010 }
Seth Mooreb393b082021-07-12 14:18:28 -07002011 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
2012 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01002013 continue;
2014 }
subrahmanyaman05642492022-02-05 07:10:56 +00002015 // Strongbox may not support factory provisioned attestation key.
2016 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002017 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2018 result = GenerateKeyWithSelfSignedAttestKey(
2019 AuthorizationSetBuilder()
2020 .EcdsaKey(EcCurve::P_256)
2021 .AttestKey()
2022 .SetDefaultValidity(), /* attest key params */
2023 builder, &key_blob, &key_characteristics);
2024 }
subrahmanyaman05642492022-02-05 07:10:56 +00002025 }
David Drysdale37af4b32021-05-14 16:46:59 +01002026 ASSERT_EQ(result, ErrorCode::OK);
2027 ASSERT_GT(key_blob.size(), 0U);
2028
2029 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2030 ASSERT_GT(cert_chain_.size(), 0);
2031 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2032
2033 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2034 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07002035 // Some tags are optional, so don't require them to be in the enforcements.
2036 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01002037 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
2038 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
2039 }
2040
2041 // Verifying the attestation record will check for the specific tag because
2042 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002043 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2044 hw_enforced, SecLevel(),
2045 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002046
2047 CheckedDeleteKey(&key_blob);
2048 }
2049
David Drysdalec53b7d92021-10-11 12:35:58 +01002050 // Collection of invalid attestation ID tags.
2051 auto invalid_tags =
2052 AuthorizationSetBuilder()
2053 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
2054 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
2055 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
2056 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
2057 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
2058 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
2059 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
2060 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01002061 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01002062 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01002063 vector<uint8_t> key_blob;
2064 vector<KeyCharacteristics> key_characteristics;
2065 AuthorizationSetBuilder builder =
2066 AuthorizationSetBuilder()
2067 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002068 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01002069 .Digest(Digest::NONE)
2070 .AttestationChallenge(challenge)
2071 .AttestationApplicationId(app_id)
2072 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2073 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2074 .SetDefaultValidity();
2075 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002076
2077 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
2078 // Strongbox may not support factory provisioned attestation key.
2079 if (SecLevel() == SecurityLevel::STRONGBOX) {
2080 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2081 error = GenerateKeyWithSelfSignedAttestKey(
2082 AuthorizationSetBuilder()
2083 .EcdsaKey(EcCurve::P_256)
2084 .AttestKey()
2085 .SetDefaultValidity(), /* attest key params */
2086 builder, &key_blob, &key_characteristics);
2087 }
2088 }
2089 ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
David Drysdale37af4b32021-05-14 16:46:59 +01002090 }
2091}
2092
2093/*
David Drysdalec53b7d92021-10-11 12:35:58 +01002094 * NewKeyGenerationTest.EcdsaAttestationIdTags
2095 *
2096 * Verifies that creation of an attested ECDSA key includes various ID tags in the
2097 * attestation extension.
2098 */
2099TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01002100 if (is_gsi_image()) {
2101 // GSI sets up a standard set of device identifiers that may not match
2102 // the device identifiers held by the device.
2103 GTEST_SKIP() << "Test not applicable under GSI";
2104 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002105 auto challenge = "hello";
2106 auto app_id = "foo";
2107 auto subject = "cert subj 2";
2108 vector<uint8_t> subject_der(make_name_from_str(subject));
2109 uint64_t serial_int = 0x1010;
2110 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2111 const AuthorizationSetBuilder base_builder =
2112 AuthorizationSetBuilder()
2113 .Authorization(TAG_NO_AUTH_REQUIRED)
2114 .EcdsaSigningKey(EcCurve::P_256)
2115 .Digest(Digest::NONE)
2116 .AttestationChallenge(challenge)
2117 .AttestationApplicationId(app_id)
2118 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2119 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2120 .SetDefaultValidity();
2121
2122 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2123 auto extra_tags = AuthorizationSetBuilder();
Prashant Patil8d779bf2022-09-28 16:09:29 +01002124 // Use ro.product.brand_for_attestation property for attestation if it is present else fallback
2125 // to ro.product.brand
2126 std::string prop_value =
2127 ::android::base::GetProperty("ro.product.brand_for_attestation", /* default= */ "");
2128 if (!prop_value.empty()) {
2129 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND,
2130 "ro.product.brand_for_attestation");
2131 } else {
2132 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
2133 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002134 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
Prashant Patil8d779bf2022-09-28 16:09:29 +01002135 // Use ro.product.name_for_attestation property for attestation if it is present else fallback
2136 // to ro.product.name
2137 prop_value = ::android::base::GetProperty("ro.product.name_for_attestation", /* default= */ "");
2138 if (!prop_value.empty()) {
2139 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT,
2140 "ro.product.name_for_attestation");
2141 } else {
2142 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
2143 }
Tri Vo799e4352022-11-07 17:23:50 -08002144 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
David Drysdalec53b7d92021-10-11 12:35:58 +01002145 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
Prashant Patil8d779bf2022-09-28 16:09:29 +01002146 // Use ro.product.model_for_attestation property for attestation if it is present else fallback
2147 // to ro.product.model
2148 prop_value =
2149 ::android::base::GetProperty("ro.product.model_for_attestation", /* default= */ "");
2150 if (!prop_value.empty()) {
2151 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL,
2152 "ro.product.model_for_attestation");
2153 } else {
2154 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
2155 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002156
2157 for (const KeyParameter& tag : extra_tags) {
2158 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2159 vector<uint8_t> key_blob;
2160 vector<KeyCharacteristics> key_characteristics;
2161 AuthorizationSetBuilder builder = base_builder;
2162 builder.push_back(tag);
2163 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002164 // Strongbox may not support factory provisioned attestation key.
2165 if (SecLevel() == SecurityLevel::STRONGBOX) {
2166 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2167 }
Prashant Patil88ad1892022-03-15 16:31:02 +00002168 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2169 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002170 continue;
2171 }
2172 ASSERT_EQ(result, ErrorCode::OK);
2173 ASSERT_GT(key_blob.size(), 0U);
2174
2175 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2176 ASSERT_GT(cert_chain_.size(), 0);
2177 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2178
2179 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2180 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2181
2182 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2183 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2184 // attestation extension should contain them, so make sure the extra tag is added.
2185 hw_enforced.push_back(tag);
2186
2187 // Verifying the attestation record will check for the specific tag because
2188 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002189 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2190 hw_enforced, SecLevel(),
2191 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002192
2193 CheckedDeleteKey(&key_blob);
2194 }
2195}
2196
2197/*
David Drysdale565ccc72021-10-11 12:49:50 +01002198 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2199 *
2200 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2201 */
2202TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2203 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002204 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002205 auto challenge = "hello";
2206 auto subject = "cert subj 2";
2207 vector<uint8_t> subject_der(make_name_from_str(subject));
2208 uint64_t serial_int = 0x1010;
2209 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002210 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002211 AuthorizationSetBuilder()
2212 .Authorization(TAG_NO_AUTH_REQUIRED)
2213 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2214 .EcdsaSigningKey(EcCurve::P_256)
2215 .Digest(Digest::NONE)
2216 .AttestationChallenge(challenge)
2217 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2218 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2219 .AttestationApplicationId(app_id)
2220 .Authorization(TAG_CREATION_DATETIME, datetime)
2221 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002222 if (reset) {
2223 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2224 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002225 auto result = GenerateKey(builder);
2226 if (SecLevel() == SecurityLevel::STRONGBOX) {
2227 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2228 result = GenerateKeyWithSelfSignedAttestKey(
2229 AuthorizationSetBuilder()
2230 .EcdsaKey(EcCurve::P_256)
2231 .AttestKey()
2232 .SetDefaultValidity(), /* attest key params */
2233 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2234 }
2235 }
2236 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002237 ASSERT_GT(key_blob_.size(), 0U);
2238
2239 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2240 ASSERT_GT(cert_chain_.size(), 0);
2241 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2242
2243 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2244 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2245
2246 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002247 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2248 hw_enforced, SecLevel(),
2249 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002250 EXPECT_GT(unique_id->size(), 0);
2251 CheckedDeleteKey();
2252 };
2253
2254 // Generate unique ID
2255 auto app_id = "foo";
2256 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2257 vector<uint8_t> unique_id;
2258 get_unique_id(app_id, cert_date, &unique_id);
2259
2260 // Generating a new key with the same parameters should give the same unique ID.
2261 vector<uint8_t> unique_id2;
2262 get_unique_id(app_id, cert_date, &unique_id2);
2263 EXPECT_EQ(unique_id, unique_id2);
2264
2265 // Generating a new key with a slightly different date should give the same unique ID.
2266 uint64_t rounded_date = cert_date / 2592000000LLU;
2267 uint64_t min_date = rounded_date * 2592000000LLU;
2268 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2269
2270 vector<uint8_t> unique_id3;
2271 get_unique_id(app_id, min_date, &unique_id3);
2272 EXPECT_EQ(unique_id, unique_id3);
2273
2274 vector<uint8_t> unique_id4;
2275 get_unique_id(app_id, max_date, &unique_id4);
2276 EXPECT_EQ(unique_id, unique_id4);
2277
2278 // A different attestation application ID should yield a different unique ID.
2279 auto app_id2 = "different_foo";
2280 vector<uint8_t> unique_id5;
2281 get_unique_id(app_id2, cert_date, &unique_id5);
2282 EXPECT_NE(unique_id, unique_id5);
2283
2284 // A radically different date should yield a different unique ID.
2285 vector<uint8_t> unique_id6;
2286 get_unique_id(app_id, 1611621648000, &unique_id6);
2287 EXPECT_NE(unique_id, unique_id6);
2288
2289 vector<uint8_t> unique_id7;
2290 get_unique_id(app_id, max_date + 1, &unique_id7);
2291 EXPECT_NE(unique_id, unique_id7);
2292
2293 vector<uint8_t> unique_id8;
2294 get_unique_id(app_id, min_date - 1, &unique_id8);
2295 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002296
2297 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2298 vector<uint8_t> unique_id9;
2299 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2300 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002301}
2302
2303/*
David Drysdale37af4b32021-05-14 16:46:59 +01002304 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2305 *
2306 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2307 */
2308TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2309 auto challenge = "hello";
2310 auto attest_app_id = "foo";
2311 auto subject = "cert subj 2";
2312 vector<uint8_t> subject_der(make_name_from_str(subject));
2313 uint64_t serial_int = 0x1010;
2314 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2315
2316 // Earlier versions of the attestation extension schema included a slot:
2317 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2318 // This should never have been included, and should never be filled in.
2319 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2320 // to confirm that this field never makes it into the attestation extension.
2321 vector<uint8_t> key_blob;
2322 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002323 auto builder = AuthorizationSetBuilder()
2324 .Authorization(TAG_NO_AUTH_REQUIRED)
2325 .EcdsaSigningKey(EcCurve::P_256)
2326 .Digest(Digest::NONE)
2327 .AttestationChallenge(challenge)
2328 .AttestationApplicationId(attest_app_id)
2329 .Authorization(TAG_APPLICATION_ID, "client_id")
2330 .Authorization(TAG_APPLICATION_DATA, "appdata")
2331 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2332 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2333 .SetDefaultValidity();
2334
2335 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002336 // Strongbox may not support factory provisioned attestation key.
2337 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002338 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2339 result = GenerateKeyWithSelfSignedAttestKey(
2340 AuthorizationSetBuilder()
2341 .EcdsaKey(EcCurve::P_256)
2342 .AttestKey()
2343 .SetDefaultValidity(), /* attest key params */
2344 builder, &key_blob, &key_characteristics);
2345 }
subrahmanyaman05642492022-02-05 07:10:56 +00002346 }
David Drysdale37af4b32021-05-14 16:46:59 +01002347 ASSERT_EQ(result, ErrorCode::OK);
2348 ASSERT_GT(key_blob.size(), 0U);
2349
2350 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2351 ASSERT_GT(cert_chain_.size(), 0);
2352 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2353
2354 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2355 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002356 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2357 hw_enforced, SecLevel(),
2358 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002359
2360 // Check that the app id is not in the cert.
2361 string app_id = "clientid";
2362 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2363 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2364 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2365 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2366 cert_chain_[0].encodedCertificate.end());
2367
2368 CheckedDeleteKey(&key_blob);
2369}
2370
2371/*
Selene Huang4f64c222021-04-13 19:54:36 -07002372 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2373 *
2374 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2375 * the key will generate a self signed attestation.
2376 */
2377TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002378 auto subject = "cert subj 2";
2379 vector<uint8_t> subject_der(make_name_from_str(subject));
2380
2381 uint64_t serial_int = 0x123456FFF1234;
2382 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2383
David Drysdaledf09e542021-06-08 15:46:11 +01002384 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002385 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002386 vector<uint8_t> key_blob;
2387 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002388 ASSERT_EQ(ErrorCode::OK,
2389 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002390 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002391 .Digest(Digest::NONE)
2392 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2393 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2394 .SetDefaultValidity(),
2395 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002396 ASSERT_GT(key_blob.size(), 0U);
2397 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002398 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002399
2400 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2401
2402 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002403 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002404
2405 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2406 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002407 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002408
2409 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2410 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2411
2412 CheckedDeleteKey(&key_blob);
2413 }
2414}
2415
2416/*
2417 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2418 *
2419 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2420 * app id must also be provided or else it will fail.
2421 */
2422TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2423 auto challenge = "hello";
2424 vector<uint8_t> key_blob;
2425 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002426 auto builder = AuthorizationSetBuilder()
2427 .EcdsaSigningKey(EcCurve::P_256)
2428 .Digest(Digest::NONE)
2429 .AttestationChallenge(challenge)
2430 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002431
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002432 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002433 // Strongbox may not support factory provisioned attestation key.
2434 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002435 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2436 result = GenerateKeyWithSelfSignedAttestKey(
2437 AuthorizationSetBuilder()
2438 .EcdsaKey(EcCurve::P_256)
2439 .AttestKey()
2440 .SetDefaultValidity(), /* attest key params */
2441 builder, &key_blob, &key_characteristics);
2442 }
subrahmanyaman05642492022-02-05 07:10:56 +00002443 }
2444 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002445}
2446
2447/*
2448 * NewKeyGenerationTest.EcdsaIgnoreAppId
2449 *
2450 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2451 * any appid will be ignored, and keymint will generate a self sign certificate.
2452 */
2453TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2454 auto app_id = "foo";
2455
David Drysdaledf09e542021-06-08 15:46:11 +01002456 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002457 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002458 vector<uint8_t> key_blob;
2459 vector<KeyCharacteristics> key_characteristics;
2460 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002461 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002462 .Digest(Digest::NONE)
2463 .AttestationApplicationId(app_id)
2464 .SetDefaultValidity(),
2465 &key_blob, &key_characteristics));
2466
2467 ASSERT_GT(key_blob.size(), 0U);
2468 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002469 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002470
2471 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2472
2473 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002474 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002475
2476 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2477 ASSERT_EQ(cert_chain_.size(), 1);
2478
2479 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2480 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2481
2482 CheckedDeleteKey(&key_blob);
2483 }
2484}
2485
2486/*
2487 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2488 *
2489 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2490 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2491 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2492 * to specify how many following bytes will be used to encode the length.
2493 */
2494TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2495 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002496 std::vector<uint32_t> app_id_lengths{143, 258};
2497
2498 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002499 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002500 const string app_id(length, 'a');
2501 vector<uint8_t> key_blob;
2502 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002503 auto builder = AuthorizationSetBuilder()
2504 .Authorization(TAG_NO_AUTH_REQUIRED)
2505 .EcdsaSigningKey(EcCurve::P_256)
2506 .Digest(Digest::NONE)
2507 .AttestationChallenge(challenge)
2508 .AttestationApplicationId(app_id)
2509 .SetDefaultValidity();
2510
2511 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002512 // Strongbox may not support factory provisioned attestation key.
2513 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002514 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2515 result = GenerateKeyWithSelfSignedAttestKey(
2516 AuthorizationSetBuilder()
2517 .EcdsaKey(EcCurve::P_256)
2518 .AttestKey()
2519 .SetDefaultValidity(), /* attest key params */
2520 builder, &key_blob, &key_characteristics);
2521 }
subrahmanyaman05642492022-02-05 07:10:56 +00002522 }
2523 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002524 ASSERT_GT(key_blob.size(), 0U);
2525 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002526 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002527
2528 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2529
2530 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002531 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002532
2533 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2534 ASSERT_GT(cert_chain_.size(), 0);
2535
2536 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2537 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002538 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002539 sw_enforced, hw_enforced, SecLevel(),
2540 cert_chain_[0].encodedCertificate));
2541
2542 CheckedDeleteKey(&key_blob);
2543 }
2544}
2545
2546/*
Qi Wud22ec842020-11-26 13:27:53 +08002547 * NewKeyGenerationTest.LimitedUsageEcdsa
2548 *
2549 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2550 * resulting keys have correct characteristics.
2551 */
2552TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002553 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002554 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002555 vector<uint8_t> key_blob;
2556 vector<KeyCharacteristics> key_characteristics;
2557 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002558 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002559 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002560 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2561 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002562 &key_blob, &key_characteristics));
2563
2564 ASSERT_GT(key_blob.size(), 0U);
2565 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002566 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002567
2568 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2569
2570 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002571 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002572
2573 // Check the usage count limit tag appears in the authorizations.
2574 AuthorizationSet auths;
2575 for (auto& entry : key_characteristics) {
2576 auths.push_back(AuthorizationSet(entry.authorizations));
2577 }
2578 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2579 << "key usage count limit " << 1U << " missing";
2580
2581 CheckedDeleteKey(&key_blob);
2582 }
2583}
2584
2585/*
Selene Huang31ab4042020-04-29 04:22:39 -07002586 * NewKeyGenerationTest.EcdsaDefaultSize
2587 *
David Drysdaledf09e542021-06-08 15:46:11 +01002588 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002589 * UNSUPPORTED_KEY_SIZE.
2590 */
2591TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2592 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2593 GenerateKey(AuthorizationSetBuilder()
2594 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2595 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002596 .Digest(Digest::NONE)
2597 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002598}
2599
2600/*
David Drysdale42fe1892021-10-14 14:43:46 +01002601 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002602 *
David Drysdale42fe1892021-10-14 14:43:46 +01002603 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002604 * UNSUPPORTED_KEY_SIZE.
2605 */
David Drysdale42fe1892021-10-14 14:43:46 +01002606TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002607 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002608 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002609 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002610 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002611 auto result = GenerateKey(AuthorizationSetBuilder()
2612 .EcdsaSigningKey(curve)
2613 .Digest(Digest::NONE)
2614 .SetDefaultValidity(),
2615 &key_blob, &key_characteristics);
2616 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2617 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002618 }
2619
David Drysdaledf09e542021-06-08 15:46:11 +01002620 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2621 GenerateKey(AuthorizationSetBuilder()
2622 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2623 .Authorization(TAG_KEY_SIZE, 190)
2624 .SigningKey()
2625 .Digest(Digest::NONE)
2626 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002627}
2628
2629/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002630 * NewKeyGenerationTest.EcdsaMissingCurve
2631 *
2632 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2633 */
2634TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2635 if (AidlVersion() < 2) {
2636 /*
2637 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2638 * However, this was not checked at the time so we can only be strict about checking this
2639 * for implementations of KeyMint version 2 and above.
2640 */
2641 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2642 }
2643 /* If EC_CURVE not provided, generateKey
2644 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2645 */
2646 auto result = GenerateKey(
2647 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2648 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2649 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2650}
2651
2652/*
Selene Huang31ab4042020-04-29 04:22:39 -07002653 * NewKeyGenerationTest.EcdsaMismatchKeySize
2654 *
2655 * Verifies that specifying mismatched key size and curve for EC key generation returns
2656 * INVALID_ARGUMENT.
2657 */
2658TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002659 if (SecLevel() == SecurityLevel::STRONGBOX) {
2660 GTEST_SKIP() << "Test not applicable to StrongBox device";
2661 }
Selene Huang31ab4042020-04-29 04:22:39 -07002662
David Drysdaledf09e542021-06-08 15:46:11 +01002663 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002664 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002665 .Authorization(TAG_KEY_SIZE, 224)
2666 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002667 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002668 .Digest(Digest::NONE)
2669 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002670 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002671}
2672
2673/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002674 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002675 *
2676 * Verifies that keymint does not support any curve designated as unsupported.
2677 */
2678TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2679 Digest digest;
2680 if (SecLevel() == SecurityLevel::STRONGBOX) {
2681 digest = Digest::SHA_2_256;
2682 } else {
2683 digest = Digest::SHA_2_512;
2684 }
2685 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002686 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002687 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2688 .EcdsaSigningKey(curve)
2689 .Digest(digest)
2690 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002691 << "Failed to generate key on curve: " << curve;
2692 CheckedDeleteKey();
2693 }
2694}
2695
2696/*
2697 * NewKeyGenerationTest.Hmac
2698 *
2699 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2700 * characteristics.
2701 */
2702TEST_P(NewKeyGenerationTest, Hmac) {
2703 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002704 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002705 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002706 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002707 constexpr size_t key_size = 128;
2708 ASSERT_EQ(ErrorCode::OK,
2709 GenerateKey(
2710 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2711 TAG_MIN_MAC_LENGTH, 128),
2712 &key_blob, &key_characteristics));
2713
2714 ASSERT_GT(key_blob.size(), 0U);
2715 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002716 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002717
Shawn Willden7f424372021-01-10 18:06:50 -07002718 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2719 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2720 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2721 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002722
2723 CheckedDeleteKey(&key_blob);
2724 }
2725}
2726
2727/*
Selene Huang4f64c222021-04-13 19:54:36 -07002728 * NewKeyGenerationTest.HmacNoAttestation
2729 *
2730 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2731 * and app id are provided.
2732 */
2733TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2734 auto challenge = "hello";
2735 auto app_id = "foo";
2736
2737 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002738 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002739 vector<uint8_t> key_blob;
2740 vector<KeyCharacteristics> key_characteristics;
2741 constexpr size_t key_size = 128;
2742 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2743 .HmacKey(key_size)
2744 .Digest(digest)
2745 .AttestationChallenge(challenge)
2746 .AttestationApplicationId(app_id)
2747 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2748 &key_blob, &key_characteristics));
2749
2750 ASSERT_GT(key_blob.size(), 0U);
2751 ASSERT_EQ(cert_chain_.size(), 0);
2752 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002753 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002754
2755 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2756 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2757 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2758 << "Key size " << key_size << "missing";
2759
2760 CheckedDeleteKey(&key_blob);
2761 }
2762}
2763
2764/*
Qi Wud22ec842020-11-26 13:27:53 +08002765 * NewKeyGenerationTest.LimitedUsageHmac
2766 *
2767 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2768 * resulting keys have correct characteristics.
2769 */
2770TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2771 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002772 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002773 vector<uint8_t> key_blob;
2774 vector<KeyCharacteristics> key_characteristics;
2775 constexpr size_t key_size = 128;
2776 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2777 .HmacKey(key_size)
2778 .Digest(digest)
2779 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2780 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2781 &key_blob, &key_characteristics));
2782
2783 ASSERT_GT(key_blob.size(), 0U);
2784 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002785 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002786
2787 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2788 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2789 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2790 << "Key size " << key_size << "missing";
2791
2792 // Check the usage count limit tag appears in the authorizations.
2793 AuthorizationSet auths;
2794 for (auto& entry : key_characteristics) {
2795 auths.push_back(AuthorizationSet(entry.authorizations));
2796 }
2797 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2798 << "key usage count limit " << 1U << " missing";
2799
2800 CheckedDeleteKey(&key_blob);
2801 }
2802}
2803
2804/*
Selene Huang31ab4042020-04-29 04:22:39 -07002805 * NewKeyGenerationTest.HmacCheckKeySizes
2806 *
2807 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2808 */
2809TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2810 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002811 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002812 if (key_size < 64 || key_size % 8 != 0) {
2813 // To keep this test from being very slow, we only test a random fraction of
2814 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2815 // them, we expect to run ~40 of them in each run.
2816 if (key_size % 8 == 0 || random() % 10 == 0) {
2817 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2818 GenerateKey(AuthorizationSetBuilder()
2819 .HmacKey(key_size)
2820 .Digest(Digest::SHA_2_256)
2821 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2822 << "HMAC key size " << key_size << " invalid";
2823 }
2824 } else {
2825 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2826 .HmacKey(key_size)
2827 .Digest(Digest::SHA_2_256)
2828 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2829 << "Failed to generate HMAC key of size " << key_size;
2830 CheckedDeleteKey();
2831 }
2832 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002833 if (SecLevel() == SecurityLevel::STRONGBOX) {
2834 // STRONGBOX devices must not support keys larger than 512 bits.
2835 size_t key_size = 520;
2836 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2837 GenerateKey(AuthorizationSetBuilder()
2838 .HmacKey(key_size)
2839 .Digest(Digest::SHA_2_256)
2840 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2841 << "HMAC key size " << key_size << " unexpectedly valid";
2842 }
Selene Huang31ab4042020-04-29 04:22:39 -07002843}
2844
2845/*
2846 * NewKeyGenerationTest.HmacCheckMinMacLengths
2847 *
2848 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2849 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2850 * specific MAC length that failed, so reproducing a failed run will be easy.
2851 */
2852TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2853 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002854 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002855 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2856 // To keep this test from being very long, we only test a random fraction of
2857 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2858 // we expect to run ~17 of them in each run.
2859 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2860 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2861 GenerateKey(AuthorizationSetBuilder()
2862 .HmacKey(128)
2863 .Digest(Digest::SHA_2_256)
2864 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2865 << "HMAC min mac length " << min_mac_length << " invalid.";
2866 }
2867 } else {
2868 EXPECT_EQ(ErrorCode::OK,
2869 GenerateKey(AuthorizationSetBuilder()
2870 .HmacKey(128)
2871 .Digest(Digest::SHA_2_256)
2872 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2873 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2874 CheckedDeleteKey();
2875 }
2876 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002877
2878 // Minimum MAC length must be no more than 512 bits.
2879 size_t min_mac_length = 520;
2880 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2881 GenerateKey(AuthorizationSetBuilder()
2882 .HmacKey(128)
2883 .Digest(Digest::SHA_2_256)
2884 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2885 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002886}
2887
2888/*
2889 * NewKeyGenerationTest.HmacMultipleDigests
2890 *
2891 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2892 */
2893TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002894 if (SecLevel() == SecurityLevel::STRONGBOX) {
2895 GTEST_SKIP() << "Test not applicable to StrongBox device";
2896 }
Selene Huang31ab4042020-04-29 04:22:39 -07002897
2898 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2899 GenerateKey(AuthorizationSetBuilder()
2900 .HmacKey(128)
2901 .Digest(Digest::SHA1)
2902 .Digest(Digest::SHA_2_256)
2903 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2904}
2905
2906/*
2907 * NewKeyGenerationTest.HmacDigestNone
2908 *
2909 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2910 */
2911TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2912 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2913 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2914 128)));
2915
2916 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2917 GenerateKey(AuthorizationSetBuilder()
2918 .HmacKey(128)
2919 .Digest(Digest::NONE)
2920 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2921}
2922
Selene Huang4f64c222021-04-13 19:54:36 -07002923/*
2924 * NewKeyGenerationTest.AesNoAttestation
2925 *
2926 * Verifies that attestation parameters to AES keys are ignored and generateKey
2927 * will succeed.
2928 */
2929TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2930 auto challenge = "hello";
2931 auto app_id = "foo";
2932
2933 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2934 .Authorization(TAG_NO_AUTH_REQUIRED)
2935 .AesEncryptionKey(128)
2936 .EcbMode()
2937 .Padding(PaddingMode::PKCS7)
2938 .AttestationChallenge(challenge)
2939 .AttestationApplicationId(app_id)));
2940
2941 ASSERT_EQ(cert_chain_.size(), 0);
2942}
2943
2944/*
2945 * NewKeyGenerationTest.TripleDesNoAttestation
2946 *
2947 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2948 * will be successful. No attestation should be generated.
2949 */
2950TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2951 auto challenge = "hello";
2952 auto app_id = "foo";
2953
2954 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2955 .TripleDesEncryptionKey(168)
2956 .BlockMode(BlockMode::ECB)
2957 .Authorization(TAG_NO_AUTH_REQUIRED)
2958 .Padding(PaddingMode::NONE)
2959 .AttestationChallenge(challenge)
2960 .AttestationApplicationId(app_id)));
2961 ASSERT_EQ(cert_chain_.size(), 0);
2962}
2963
Selene Huang31ab4042020-04-29 04:22:39 -07002964INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2965
2966typedef KeyMintAidlTestBase SigningOperationsTest;
2967
2968/*
2969 * SigningOperationsTest.RsaSuccess
2970 *
2971 * Verifies that raw RSA signature operations succeed.
2972 */
2973TEST_P(SigningOperationsTest, RsaSuccess) {
2974 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2975 .RsaSigningKey(2048, 65537)
2976 .Digest(Digest::NONE)
2977 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002978 .Authorization(TAG_NO_AUTH_REQUIRED)
2979 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002980 string message = "12345678901234567890123456789012";
2981 string signature = SignMessage(
2982 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002983 LocalVerifyMessage(message, signature,
2984 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2985}
2986
2987/*
2988 * SigningOperationsTest.RsaAllPaddingsAndDigests
2989 *
2990 * Verifies RSA signature/verification for all padding modes and digests.
2991 */
2992TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2993 auto authorizations = AuthorizationSetBuilder()
2994 .Authorization(TAG_NO_AUTH_REQUIRED)
2995 .RsaSigningKey(2048, 65537)
2996 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2997 .Padding(PaddingMode::NONE)
2998 .Padding(PaddingMode::RSA_PSS)
2999 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3000 .SetDefaultValidity();
3001
3002 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
3003
3004 string message(128, 'a');
3005 string corrupt_message(message);
3006 ++corrupt_message[corrupt_message.size() / 2];
3007
3008 for (auto padding :
3009 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
3010 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003011 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003012 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
3013 // Digesting only makes sense with padding.
3014 continue;
3015 }
3016
3017 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
3018 // PSS requires digesting.
3019 continue;
3020 }
3021
3022 string signature =
3023 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
3024 LocalVerifyMessage(message, signature,
3025 AuthorizationSetBuilder().Digest(digest).Padding(padding));
3026 }
3027 }
Selene Huang31ab4042020-04-29 04:22:39 -07003028}
3029
3030/*
3031 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
3032 *
Shawn Willden7f424372021-01-10 18:06:50 -07003033 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07003034 */
3035TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
3036 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3037 .Authorization(TAG_NO_AUTH_REQUIRED)
3038 .RsaSigningKey(2048, 65537)
3039 .Digest(Digest::NONE)
3040 .Padding(PaddingMode::NONE)
3041 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003042 .Authorization(TAG_APPLICATION_DATA, "appdata")
3043 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003044
3045 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3046
Selene Huang31ab4042020-04-29 04:22:39 -07003047 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3048 Begin(KeyPurpose::SIGN,
3049 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3050 AbortIfNeeded();
3051 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3052 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3053 .Digest(Digest::NONE)
3054 .Padding(PaddingMode::NONE)
3055 .Authorization(TAG_APPLICATION_ID, "clientid")));
3056 AbortIfNeeded();
3057 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3058 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3059 .Digest(Digest::NONE)
3060 .Padding(PaddingMode::NONE)
3061 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3062 AbortIfNeeded();
3063 EXPECT_EQ(ErrorCode::OK,
3064 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3065 .Digest(Digest::NONE)
3066 .Padding(PaddingMode::NONE)
3067 .Authorization(TAG_APPLICATION_DATA, "appdata")
3068 .Authorization(TAG_APPLICATION_ID, "clientid")));
3069 AbortIfNeeded();
3070}
3071
3072/*
3073 * SigningOperationsTest.RsaPssSha256Success
3074 *
3075 * Verifies that RSA-PSS signature operations succeed.
3076 */
3077TEST_P(SigningOperationsTest, RsaPssSha256Success) {
3078 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3079 .RsaSigningKey(2048, 65537)
3080 .Digest(Digest::SHA_2_256)
3081 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003082 .Authorization(TAG_NO_AUTH_REQUIRED)
3083 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003084 // Use large message, which won't work without digesting.
3085 string message(1024, 'a');
3086 string signature = SignMessage(
3087 message,
3088 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
3089}
3090
3091/*
3092 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
3093 *
3094 * Verifies that keymint rejects signature operations that specify a padding mode when the key
3095 * supports only unpadded operations.
3096 */
3097TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
3098 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3099 .RsaSigningKey(2048, 65537)
3100 .Digest(Digest::NONE)
3101 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003102 .Padding(PaddingMode::NONE)
3103 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003104 string message = "12345678901234567890123456789012";
3105 string signature;
3106
3107 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3108 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3109 .Digest(Digest::NONE)
3110 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3111}
3112
3113/*
3114 * SigningOperationsTest.NoUserConfirmation
3115 *
3116 * Verifies that keymint rejects signing operations for keys with
3117 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
3118 * presented.
3119 */
3120TEST_P(SigningOperationsTest, NoUserConfirmation) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08003121 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3122 .RsaSigningKey(1024, 65537)
3123 .Digest(Digest::NONE)
3124 .Padding(PaddingMode::NONE)
3125 .Authorization(TAG_NO_AUTH_REQUIRED)
3126 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3127 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003128
3129 const string message = "12345678901234567890123456789012";
3130 EXPECT_EQ(ErrorCode::OK,
3131 Begin(KeyPurpose::SIGN,
3132 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3133 string signature;
3134 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3135}
3136
3137/*
3138 * SigningOperationsTest.RsaPkcs1Sha256Success
3139 *
3140 * Verifies that digested RSA-PKCS1 signature operations succeed.
3141 */
3142TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3143 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3144 .RsaSigningKey(2048, 65537)
3145 .Digest(Digest::SHA_2_256)
3146 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003147 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3148 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003149 string message(1024, 'a');
3150 string signature = SignMessage(message, AuthorizationSetBuilder()
3151 .Digest(Digest::SHA_2_256)
3152 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3153}
3154
3155/*
3156 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3157 *
3158 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3159 */
3160TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3161 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3162 .RsaSigningKey(2048, 65537)
3163 .Digest(Digest::NONE)
3164 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003165 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3166 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003167 string message(53, 'a');
3168 string signature = SignMessage(message, AuthorizationSetBuilder()
3169 .Digest(Digest::NONE)
3170 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3171}
3172
3173/*
3174 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3175 *
3176 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3177 * given a too-long message.
3178 */
3179TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3180 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3181 .RsaSigningKey(2048, 65537)
3182 .Digest(Digest::NONE)
3183 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003184 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3185 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003186 string message(257, 'a');
3187
3188 EXPECT_EQ(ErrorCode::OK,
3189 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3190 .Digest(Digest::NONE)
3191 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3192 string signature;
3193 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3194}
3195
3196/*
3197 * SigningOperationsTest.RsaPssSha512TooSmallKey
3198 *
3199 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3200 * used with a key that is too small for the message.
3201 *
3202 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3203 * keymint specification requires that salt_size == digest_size, so the message will be
3204 * digest_size * 2 +
3205 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3206 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3207 * for a 1024-bit key.
3208 */
3209TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003210 if (SecLevel() == SecurityLevel::STRONGBOX) {
3211 GTEST_SKIP() << "Test not applicable to StrongBox device";
3212 }
Selene Huang31ab4042020-04-29 04:22:39 -07003213 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3214 .RsaSigningKey(1024, 65537)
3215 .Digest(Digest::SHA_2_512)
3216 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003217 .Padding(PaddingMode::RSA_PSS)
3218 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003219 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3220 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3221 .Digest(Digest::SHA_2_512)
3222 .Padding(PaddingMode::RSA_PSS)));
3223}
3224
3225/*
3226 * SigningOperationsTest.RsaNoPaddingTooLong
3227 *
3228 * Verifies that raw RSA signature operations fail with the correct error code when
3229 * given a too-long message.
3230 */
3231TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3232 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3233 .RsaSigningKey(2048, 65537)
3234 .Digest(Digest::NONE)
3235 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003236 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3237 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003238 // One byte too long
3239 string message(2048 / 8 + 1, 'a');
3240 ASSERT_EQ(ErrorCode::OK,
3241 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3242 .Digest(Digest::NONE)
3243 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3244 string result;
3245 ErrorCode finish_error_code = Finish(message, &result);
3246 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3247 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3248
3249 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3250 message = string(128 * 1024, 'a');
3251 ASSERT_EQ(ErrorCode::OK,
3252 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3253 .Digest(Digest::NONE)
3254 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3255 finish_error_code = Finish(message, &result);
3256 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3257 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3258}
3259
3260/*
3261 * SigningOperationsTest.RsaAbort
3262 *
3263 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3264 * test, but the behavior should be algorithm and purpose-independent.
3265 */
3266TEST_P(SigningOperationsTest, RsaAbort) {
3267 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3268 .RsaSigningKey(2048, 65537)
3269 .Digest(Digest::NONE)
3270 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003271 .Padding(PaddingMode::NONE)
3272 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003273
3274 ASSERT_EQ(ErrorCode::OK,
3275 Begin(KeyPurpose::SIGN,
3276 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3277 EXPECT_EQ(ErrorCode::OK, Abort());
3278
3279 // Another abort should fail
3280 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3281
3282 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003283 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003284}
3285
3286/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003287 * SigningOperationsTest.RsaNonUniqueParams
3288 *
3289 * Verifies that an operation with multiple padding modes is rejected.
3290 */
3291TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3292 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3293 .RsaSigningKey(2048, 65537)
3294 .Digest(Digest::NONE)
3295 .Digest(Digest::SHA1)
3296 .Authorization(TAG_NO_AUTH_REQUIRED)
3297 .Padding(PaddingMode::NONE)
3298 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3299 .SetDefaultValidity()));
3300
3301 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3302 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3303 .Digest(Digest::NONE)
3304 .Padding(PaddingMode::NONE)
3305 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3306
Tommy Chiuc93c4392021-05-11 18:36:50 +08003307 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3308 .Digest(Digest::NONE)
3309 .Digest(Digest::SHA1)
3310 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3311 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003312
3313 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3314 Begin(KeyPurpose::SIGN,
3315 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3316}
3317
3318/*
Selene Huang31ab4042020-04-29 04:22:39 -07003319 * SigningOperationsTest.RsaUnsupportedPadding
3320 *
3321 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3322 * with a padding mode inappropriate for RSA.
3323 */
3324TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3325 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3326 .RsaSigningKey(2048, 65537)
3327 .Authorization(TAG_NO_AUTH_REQUIRED)
3328 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003329 .Padding(PaddingMode::PKCS7)
3330 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003331 ASSERT_EQ(
3332 ErrorCode::UNSUPPORTED_PADDING_MODE,
3333 Begin(KeyPurpose::SIGN,
3334 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003335 CheckedDeleteKey();
3336
3337 ASSERT_EQ(ErrorCode::OK,
3338 GenerateKey(
3339 AuthorizationSetBuilder()
3340 .RsaSigningKey(2048, 65537)
3341 .Authorization(TAG_NO_AUTH_REQUIRED)
3342 .Digest(Digest::SHA_2_256 /* supported digest */)
3343 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3344 .SetDefaultValidity()));
3345 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3346 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3347 .Digest(Digest::SHA_2_256)
3348 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003349}
3350
3351/*
3352 * SigningOperationsTest.RsaPssNoDigest
3353 *
3354 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3355 */
3356TEST_P(SigningOperationsTest, RsaNoDigest) {
3357 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3358 .RsaSigningKey(2048, 65537)
3359 .Authorization(TAG_NO_AUTH_REQUIRED)
3360 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003361 .Padding(PaddingMode::RSA_PSS)
3362 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003363 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3364 Begin(KeyPurpose::SIGN,
3365 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3366
3367 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3368 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3369}
3370
3371/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003372 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003373 *
3374 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3375 * supported in some cases (as validated in other tests), but a mode must be specified.
3376 */
3377TEST_P(SigningOperationsTest, RsaNoPadding) {
3378 // Padding must be specified
3379 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3380 .RsaKey(2048, 65537)
3381 .Authorization(TAG_NO_AUTH_REQUIRED)
3382 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003383 .Digest(Digest::NONE)
3384 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003385 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3386 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3387}
3388
3389/*
3390 * SigningOperationsTest.RsaShortMessage
3391 *
3392 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3393 */
3394TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3395 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3396 .Authorization(TAG_NO_AUTH_REQUIRED)
3397 .RsaSigningKey(2048, 65537)
3398 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003399 .Padding(PaddingMode::NONE)
3400 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003401
3402 // Barely shorter
3403 string message(2048 / 8 - 1, 'a');
3404 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3405
3406 // Much shorter
3407 message = "a";
3408 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3409}
3410
3411/*
3412 * SigningOperationsTest.RsaSignWithEncryptionKey
3413 *
3414 * Verifies that RSA encryption keys cannot be used to sign.
3415 */
3416TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3417 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3418 .Authorization(TAG_NO_AUTH_REQUIRED)
3419 .RsaEncryptionKey(2048, 65537)
3420 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003421 .Padding(PaddingMode::NONE)
3422 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003423 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3424 Begin(KeyPurpose::SIGN,
3425 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3426}
3427
3428/*
3429 * SigningOperationsTest.RsaSignTooLargeMessage
3430 *
3431 * Verifies that attempting a raw signature of a message which is the same length as the key,
3432 * but numerically larger than the public modulus, fails with the correct error.
3433 */
3434TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3435 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3436 .Authorization(TAG_NO_AUTH_REQUIRED)
3437 .RsaSigningKey(2048, 65537)
3438 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003439 .Padding(PaddingMode::NONE)
3440 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003441
3442 // Largest possible message will always be larger than the public modulus.
3443 string message(2048 / 8, static_cast<char>(0xff));
3444 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3445 .Authorization(TAG_NO_AUTH_REQUIRED)
3446 .Digest(Digest::NONE)
3447 .Padding(PaddingMode::NONE)));
3448 string signature;
3449 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3450}
3451
3452/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003453 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3454 *
David Drysdale42fe1892021-10-14 14:43:46 +01003455 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003456 */
3457TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003458
3459 string message = "1234567890";
3460 string corrupt_message = "2234567890";
3461 for (auto curve : ValidCurves()) {
3462 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003463 // Ed25519 only allows Digest::NONE.
3464 auto digests = (curve == EcCurve::CURVE_25519)
3465 ? std::vector<Digest>(1, Digest::NONE)
3466 : ValidDigests(true /* withNone */, false /* withMD5 */);
3467
David Drysdaledf8f52e2021-05-06 08:10:58 +01003468 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3469 .Authorization(TAG_NO_AUTH_REQUIRED)
3470 .EcdsaSigningKey(curve)
3471 .Digest(digests)
3472 .SetDefaultValidity());
3473 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3474 if (error != ErrorCode::OK) {
3475 continue;
3476 }
3477
3478 for (auto digest : digests) {
3479 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3480 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3481 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3482 }
3483
3484 auto rc = DeleteKey();
3485 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3486 }
3487}
3488
3489/*
Selene Huang31ab4042020-04-29 04:22:39 -07003490 * SigningOperationsTest.EcdsaAllCurves
3491 *
David Drysdale42fe1892021-10-14 14:43:46 +01003492 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003493 */
3494TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3495 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003496 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3497 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003498 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3499 .Authorization(TAG_NO_AUTH_REQUIRED)
3500 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003501 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003502 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003503 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3504 if (error != ErrorCode::OK) continue;
3505
3506 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003507 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003508 CheckedDeleteKey();
3509 }
3510}
3511
3512/*
David Drysdale42fe1892021-10-14 14:43:46 +01003513 * SigningOperationsTest.EcdsaCurve25519
3514 *
3515 * Verifies that ECDSA operations succeed with curve25519.
3516 */
3517TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3518 if (!Curve25519Supported()) {
3519 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3520 }
3521
3522 EcCurve curve = EcCurve::CURVE_25519;
3523 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3524 .Authorization(TAG_NO_AUTH_REQUIRED)
3525 .EcdsaSigningKey(curve)
3526 .Digest(Digest::NONE)
3527 .SetDefaultValidity());
3528 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3529
3530 string message(1024, 'a');
3531 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3532 CheckedDeleteKey();
3533}
3534
3535/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003536 * SigningOperationsTest.EcdsaCurve25519MaxSize
3537 *
3538 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3539 */
3540TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3541 if (!Curve25519Supported()) {
3542 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3543 }
3544
3545 EcCurve curve = EcCurve::CURVE_25519;
3546 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3547 .Authorization(TAG_NO_AUTH_REQUIRED)
3548 .EcdsaSigningKey(curve)
3549 .Digest(Digest::NONE)
3550 .SetDefaultValidity());
3551 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3552
3553 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3554
3555 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3556 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3557 string message(msg_size, 'a');
3558
3559 // Attempt to sign via Begin+Finish.
3560 AuthorizationSet out_params;
3561 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3562 EXPECT_TRUE(out_params.empty());
3563 string signature;
3564 auto result = Finish(message, &signature);
3565 EXPECT_EQ(result, ErrorCode::OK);
3566 LocalVerifyMessage(message, signature, params);
3567
3568 // Attempt to sign via Begin+Update+Finish
3569 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3570 EXPECT_TRUE(out_params.empty());
3571 string output;
3572 result = Update(message, &output);
3573 EXPECT_EQ(result, ErrorCode::OK);
3574 EXPECT_EQ(output.size(), 0);
3575 string signature2;
3576 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3577 LocalVerifyMessage(message, signature2, params);
3578 }
3579
3580 CheckedDeleteKey();
3581}
3582
3583/*
3584 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3585 *
3586 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3587 */
3588TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3589 if (!Curve25519Supported()) {
3590 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3591 }
3592
3593 EcCurve curve = EcCurve::CURVE_25519;
3594 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3595 .Authorization(TAG_NO_AUTH_REQUIRED)
3596 .EcdsaSigningKey(curve)
3597 .Digest(Digest::NONE)
3598 .SetDefaultValidity());
3599 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3600
3601 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3602
3603 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3604 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3605 string message(msg_size, 'a');
3606
3607 // Attempt to sign via Begin+Finish.
3608 AuthorizationSet out_params;
3609 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3610 EXPECT_TRUE(out_params.empty());
3611 string signature;
3612 auto result = Finish(message, &signature);
3613 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3614
3615 // Attempt to sign via Begin+Update (but never get to Finish)
3616 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3617 EXPECT_TRUE(out_params.empty());
3618 string output;
3619 result = Update(message, &output);
3620 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3621 }
3622
3623 CheckedDeleteKey();
3624}
3625
3626/*
Selene Huang31ab4042020-04-29 04:22:39 -07003627 * SigningOperationsTest.EcdsaNoDigestHugeData
3628 *
3629 * Verifies that ECDSA operations support very large messages, even without digesting. This
3630 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3631 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3632 * the framework.
3633 */
3634TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3635 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3636 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003637 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003638 .Digest(Digest::NONE)
3639 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003640 string message(1 * 1024, 'a');
3641 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3642}
3643
3644/*
3645 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3646 *
3647 * Verifies that using an EC key requires the correct app ID/data.
3648 */
3649TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3650 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3651 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003652 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003653 .Digest(Digest::NONE)
3654 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003655 .Authorization(TAG_APPLICATION_DATA, "appdata")
3656 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003657
3658 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3659
Selene Huang31ab4042020-04-29 04:22:39 -07003660 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3661 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3662 AbortIfNeeded();
3663 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3664 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3665 .Digest(Digest::NONE)
3666 .Authorization(TAG_APPLICATION_ID, "clientid")));
3667 AbortIfNeeded();
3668 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3669 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3670 .Digest(Digest::NONE)
3671 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3672 AbortIfNeeded();
3673 EXPECT_EQ(ErrorCode::OK,
3674 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3675 .Digest(Digest::NONE)
3676 .Authorization(TAG_APPLICATION_DATA, "appdata")
3677 .Authorization(TAG_APPLICATION_ID, "clientid")));
3678 AbortIfNeeded();
3679}
3680
3681/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003682 * SigningOperationsTest.EcdsaIncompatibleDigest
3683 *
3684 * Verifies that using an EC key requires compatible digest.
3685 */
3686TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3687 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3688 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003689 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003690 .Digest(Digest::NONE)
3691 .Digest(Digest::SHA1)
3692 .SetDefaultValidity()));
3693 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3694 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3695 AbortIfNeeded();
3696}
3697
3698/*
Selene Huang31ab4042020-04-29 04:22:39 -07003699 * SigningOperationsTest.AesEcbSign
3700 *
3701 * Verifies that attempts to use AES keys to sign fail in the correct way.
3702 */
3703TEST_P(SigningOperationsTest, AesEcbSign) {
3704 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3705 .Authorization(TAG_NO_AUTH_REQUIRED)
3706 .SigningKey()
3707 .AesEncryptionKey(128)
3708 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3709
3710 AuthorizationSet out_params;
3711 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3712 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3713 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3714 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3715}
3716
3717/*
3718 * SigningOperationsTest.HmacAllDigests
3719 *
3720 * Verifies that HMAC works with all digests.
3721 */
3722TEST_P(SigningOperationsTest, HmacAllDigests) {
3723 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003724 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003725 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3726 .Authorization(TAG_NO_AUTH_REQUIRED)
3727 .HmacKey(128)
3728 .Digest(digest)
3729 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3730 << "Failed to create HMAC key with digest " << digest;
3731 string message = "12345678901234567890123456789012";
3732 string signature = MacMessage(message, digest, 160);
3733 EXPECT_EQ(160U / 8U, signature.size())
3734 << "Failed to sign with HMAC key with digest " << digest;
3735 CheckedDeleteKey();
3736 }
3737}
3738
3739/*
3740 * SigningOperationsTest.HmacSha256TooLargeMacLength
3741 *
3742 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3743 * digest size.
3744 */
3745TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3746 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3747 .Authorization(TAG_NO_AUTH_REQUIRED)
3748 .HmacKey(128)
3749 .Digest(Digest::SHA_2_256)
3750 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3751 AuthorizationSet output_params;
3752 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3753 AuthorizationSetBuilder()
3754 .Digest(Digest::SHA_2_256)
3755 .Authorization(TAG_MAC_LENGTH, 264),
3756 &output_params));
3757}
3758
3759/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003760 * SigningOperationsTest.HmacSha256InvalidMacLength
3761 *
3762 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3763 * not a multiple of 8.
3764 */
3765TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3766 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3767 .Authorization(TAG_NO_AUTH_REQUIRED)
3768 .HmacKey(128)
3769 .Digest(Digest::SHA_2_256)
3770 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3771 AuthorizationSet output_params;
3772 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3773 AuthorizationSetBuilder()
3774 .Digest(Digest::SHA_2_256)
3775 .Authorization(TAG_MAC_LENGTH, 161),
3776 &output_params));
3777}
3778
3779/*
Selene Huang31ab4042020-04-29 04:22:39 -07003780 * SigningOperationsTest.HmacSha256TooSmallMacLength
3781 *
3782 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3783 * specified minimum MAC length.
3784 */
3785TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3786 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3787 .Authorization(TAG_NO_AUTH_REQUIRED)
3788 .HmacKey(128)
3789 .Digest(Digest::SHA_2_256)
3790 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3791 AuthorizationSet output_params;
3792 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3793 AuthorizationSetBuilder()
3794 .Digest(Digest::SHA_2_256)
3795 .Authorization(TAG_MAC_LENGTH, 120),
3796 &output_params));
3797}
3798
3799/*
3800 * SigningOperationsTest.HmacRfc4231TestCase3
3801 *
3802 * Validates against the test vectors from RFC 4231 test case 3.
3803 */
3804TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3805 string key(20, 0xaa);
3806 string message(50, 0xdd);
3807 uint8_t sha_224_expected[] = {
3808 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3809 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3810 };
3811 uint8_t sha_256_expected[] = {
3812 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3813 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3814 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3815 };
3816 uint8_t sha_384_expected[] = {
3817 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3818 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3819 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3820 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3821 };
3822 uint8_t sha_512_expected[] = {
3823 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3824 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3825 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3826 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3827 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3828 };
3829
3830 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3831 if (SecLevel() != SecurityLevel::STRONGBOX) {
3832 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3833 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3834 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3835 }
3836}
3837
3838/*
3839 * SigningOperationsTest.HmacRfc4231TestCase5
3840 *
3841 * Validates against the test vectors from RFC 4231 test case 5.
3842 */
3843TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3844 string key(20, 0x0c);
3845 string message = "Test With Truncation";
3846
3847 uint8_t sha_224_expected[] = {
3848 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3849 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3850 };
3851 uint8_t sha_256_expected[] = {
3852 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3853 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3854 };
3855 uint8_t sha_384_expected[] = {
3856 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3857 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3858 };
3859 uint8_t sha_512_expected[] = {
3860 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3861 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3862 };
3863
3864 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3865 if (SecLevel() != SecurityLevel::STRONGBOX) {
3866 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3867 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3868 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3869 }
3870}
3871
3872INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3873
3874typedef KeyMintAidlTestBase VerificationOperationsTest;
3875
3876/*
Selene Huang31ab4042020-04-29 04:22:39 -07003877 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3878 *
3879 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3880 */
3881TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3882 string key_material = "HelloThisIsAKey";
3883
3884 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003885 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003886 EXPECT_EQ(ErrorCode::OK,
3887 ImportKey(AuthorizationSetBuilder()
3888 .Authorization(TAG_NO_AUTH_REQUIRED)
3889 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3890 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3891 .Digest(Digest::SHA_2_256)
3892 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3893 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3894 EXPECT_EQ(ErrorCode::OK,
3895 ImportKey(AuthorizationSetBuilder()
3896 .Authorization(TAG_NO_AUTH_REQUIRED)
3897 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3898 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3899 .Digest(Digest::SHA_2_256)
3900 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3901 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3902
3903 string message = "This is a message.";
3904 string signature = SignMessage(
3905 signing_key, message,
3906 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3907
3908 // Signing key should not work.
3909 AuthorizationSet out_params;
3910 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3911 Begin(KeyPurpose::VERIFY, signing_key,
3912 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3913
3914 // Verification key should work.
3915 VerifyMessage(verification_key, message, signature,
3916 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3917
3918 CheckedDeleteKey(&signing_key);
3919 CheckedDeleteKey(&verification_key);
3920}
3921
Prashant Patildec9fdc2021-12-08 15:25:47 +00003922/*
3923 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3924 *
3925 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3926 */
3927TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3928 string key_material = "HelloThisIsAKey";
3929
3930 vector<uint8_t> signing_key, verification_key;
3931 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3932 EXPECT_EQ(ErrorCode::OK,
3933 ImportKey(AuthorizationSetBuilder()
3934 .Authorization(TAG_NO_AUTH_REQUIRED)
3935 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3936 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3937 .Digest(Digest::SHA_2_256)
3938 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3939 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3940 EXPECT_EQ(ErrorCode::OK,
3941 ImportKey(AuthorizationSetBuilder()
3942 .Authorization(TAG_NO_AUTH_REQUIRED)
3943 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3944 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3945 .Digest(Digest::SHA_2_256)
3946 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3947 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3948
3949 string message = "This is a message.";
3950 string signature = SignMessage(
3951 signing_key, message,
3952 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3953
3954 AuthorizationSet begin_out_params;
3955 ASSERT_EQ(ErrorCode::OK,
3956 Begin(KeyPurpose::VERIFY, verification_key,
3957 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3958
3959 string corruptMessage = "This is b message."; // Corrupted message
3960 string output;
3961 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3962
3963 ASSERT_EQ(ErrorCode::OK,
3964 Begin(KeyPurpose::VERIFY, verification_key,
3965 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3966
3967 signature[0] += 1; // Corrupt a signature
3968 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3969
3970 CheckedDeleteKey(&signing_key);
3971 CheckedDeleteKey(&verification_key);
3972}
3973
Selene Huang31ab4042020-04-29 04:22:39 -07003974INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3975
3976typedef KeyMintAidlTestBase ExportKeyTest;
3977
3978/*
3979 * ExportKeyTest.RsaUnsupportedKeyFormat
3980 *
3981 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3982 */
3983// TODO(seleneh) add ExportKey to GenerateKey
3984// check result
3985
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003986class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003987 public:
3988 template <TagType tag_type, Tag tag, typename ValueT>
3989 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3990 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003991 for (auto& entry : key_characteristics_) {
3992 if (entry.securityLevel == SecLevel()) {
3993 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3994 << "Tag " << tag << " with value " << expected
3995 << " not found at security level" << entry.securityLevel;
3996 } else {
3997 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3998 << "Tag " << tag << " found at security level " << entry.securityLevel;
3999 }
Selene Huang31ab4042020-04-29 04:22:39 -07004000 }
4001 }
4002
4003 void CheckOrigin() {
4004 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07004005 // Origin isn't a crypto param, but it always lives with them.
4006 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07004007 }
4008};
4009
4010/*
4011 * ImportKeyTest.RsaSuccess
4012 *
4013 * Verifies that importing and using an RSA key pair works correctly.
4014 */
4015TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07004016 uint32_t key_size;
4017 string key;
4018
4019 if (SecLevel() == SecurityLevel::STRONGBOX) {
4020 key_size = 2048;
4021 key = rsa_2048_key;
4022 } else {
4023 key_size = 1024;
4024 key = rsa_key;
4025 }
4026
Selene Huang31ab4042020-04-29 04:22:39 -07004027 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4028 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07004029 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07004030 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004031 .Padding(PaddingMode::RSA_PSS)
4032 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07004033 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07004034
4035 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07004036 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07004037 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4038 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4039 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4040 CheckOrigin();
4041
4042 string message(1024 / 8, 'a');
4043 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4044 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004045 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004046}
4047
4048/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004049 * ImportKeyTest.RsaSuccessWithoutParams
4050 *
4051 * Verifies that importing and using an RSA key pair without specifying parameters
4052 * works correctly.
4053 */
4054TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
4055 uint32_t key_size;
4056 string key;
4057
4058 if (SecLevel() == SecurityLevel::STRONGBOX) {
4059 key_size = 2048;
4060 key = rsa_2048_key;
4061 } else {
4062 key_size = 1024;
4063 key = rsa_key;
4064 }
4065
4066 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4067 .Authorization(TAG_NO_AUTH_REQUIRED)
4068 .SigningKey()
4069 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4070 .Digest(Digest::SHA_2_256)
4071 .Padding(PaddingMode::RSA_PSS)
4072 .SetDefaultValidity(),
4073 KeyFormat::PKCS8, key));
4074
4075 // Key size and public exponent are determined from the imported key material.
4076 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4077 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4078
4079 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4080 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4081 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4082 CheckOrigin();
4083
4084 string message(1024 / 8, 'a');
4085 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4086 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004087 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004088}
4089
4090/*
Selene Huang31ab4042020-04-29 04:22:39 -07004091 * ImportKeyTest.RsaKeySizeMismatch
4092 *
4093 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4094 * correct way.
4095 */
4096TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4097 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4098 ImportKey(AuthorizationSetBuilder()
4099 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4100 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004101 .Padding(PaddingMode::NONE)
4102 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004103 KeyFormat::PKCS8, rsa_key));
4104}
4105
4106/*
4107 * ImportKeyTest.RsaPublicExponentMismatch
4108 *
4109 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4110 * fails in the correct way.
4111 */
4112TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4113 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4114 ImportKey(AuthorizationSetBuilder()
4115 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4116 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004117 .Padding(PaddingMode::NONE)
4118 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004119 KeyFormat::PKCS8, rsa_key));
4120}
4121
4122/*
David Drysdalee60248c2021-10-04 12:54:13 +01004123 * ImportKeyTest.RsaAttestMultiPurposeFail
4124 *
4125 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4126 */
4127TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004128 if (AidlVersion() < 2) {
4129 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4130 // with other key purposes. However, this was not checked at the time
4131 // so we can only be strict about checking this for implementations of KeyMint
4132 // version 2 and above.
4133 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4134 }
David Drysdalee60248c2021-10-04 12:54:13 +01004135 uint32_t key_size = 2048;
4136 string key = rsa_2048_key;
4137
4138 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4139 ImportKey(AuthorizationSetBuilder()
4140 .Authorization(TAG_NO_AUTH_REQUIRED)
4141 .RsaSigningKey(key_size, 65537)
4142 .AttestKey()
4143 .Digest(Digest::SHA_2_256)
4144 .Padding(PaddingMode::RSA_PSS)
4145 .SetDefaultValidity(),
4146 KeyFormat::PKCS8, key));
4147}
4148
4149/*
Selene Huang31ab4042020-04-29 04:22:39 -07004150 * ImportKeyTest.EcdsaSuccess
4151 *
4152 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4153 */
4154TEST_P(ImportKeyTest, EcdsaSuccess) {
4155 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4156 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004157 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004158 .Digest(Digest::SHA_2_256)
4159 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004160 KeyFormat::PKCS8, ec_256_key));
4161
4162 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004163 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4164 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4165
4166 CheckOrigin();
4167
4168 string message(32, 'a');
4169 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4170 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004171 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004172}
4173
4174/*
4175 * ImportKeyTest.EcdsaP256RFC5915Success
4176 *
4177 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4178 * correctly.
4179 */
4180TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4181 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4182 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004183 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004184 .Digest(Digest::SHA_2_256)
4185 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004186 KeyFormat::PKCS8, ec_256_key_rfc5915));
4187
4188 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004189 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4190 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4191
4192 CheckOrigin();
4193
4194 string message(32, 'a');
4195 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4196 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004197 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004198}
4199
4200/*
4201 * ImportKeyTest.EcdsaP256SEC1Success
4202 *
4203 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4204 */
4205TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4206 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4207 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004208 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004209 .Digest(Digest::SHA_2_256)
4210 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004211 KeyFormat::PKCS8, ec_256_key_sec1));
4212
4213 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004214 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4215 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4216
4217 CheckOrigin();
4218
4219 string message(32, 'a');
4220 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4221 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004222 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004223}
4224
4225/*
4226 * ImportKeyTest.Ecdsa521Success
4227 *
4228 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4229 */
4230TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004231 if (SecLevel() == SecurityLevel::STRONGBOX) {
4232 GTEST_SKIP() << "Test not applicable to StrongBox device";
4233 }
Selene Huang31ab4042020-04-29 04:22:39 -07004234 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4235 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004236 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004237 .Digest(Digest::SHA_2_256)
4238 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004239 KeyFormat::PKCS8, ec_521_key));
4240
4241 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004242 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4243 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4244 CheckOrigin();
4245
4246 string message(32, 'a');
4247 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4248 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004249 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004250}
4251
4252/*
Selene Huang31ab4042020-04-29 04:22:39 -07004253 * ImportKeyTest.EcdsaCurveMismatch
4254 *
4255 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4256 * the correct way.
4257 */
4258TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4259 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4260 ImportKey(AuthorizationSetBuilder()
4261 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004262 .Digest(Digest::NONE)
4263 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004264 KeyFormat::PKCS8, ec_256_key));
4265}
4266
4267/*
David Drysdalee60248c2021-10-04 12:54:13 +01004268 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4269 *
4270 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4271 */
4272TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004273 if (AidlVersion() < 2) {
4274 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4275 // with other key purposes. However, this was not checked at the time
4276 // so we can only be strict about checking this for implementations of KeyMint
4277 // version 2 and above.
4278 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4279 }
David Drysdalee60248c2021-10-04 12:54:13 +01004280 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4281 ImportKey(AuthorizationSetBuilder()
4282 .Authorization(TAG_NO_AUTH_REQUIRED)
4283 .EcdsaSigningKey(EcCurve::P_256)
4284 .AttestKey()
4285 .Digest(Digest::SHA_2_256)
4286 .SetDefaultValidity(),
4287 KeyFormat::PKCS8, ec_256_key));
4288}
4289
4290/*
David Drysdale42fe1892021-10-14 14:43:46 +01004291 * ImportKeyTest.Ed25519RawSuccess
4292 *
4293 * Verifies that importing and using a raw Ed25519 private key works correctly.
4294 */
4295TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4296 if (!Curve25519Supported()) {
4297 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4298 }
4299
4300 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4301 .Authorization(TAG_NO_AUTH_REQUIRED)
4302 .EcdsaSigningKey(EcCurve::CURVE_25519)
4303 .Digest(Digest::NONE)
4304 .SetDefaultValidity(),
4305 KeyFormat::RAW, ed25519_key));
4306 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4307 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4308 CheckOrigin();
4309
4310 // The returned cert should hold the correct public key.
4311 ASSERT_GT(cert_chain_.size(), 0);
4312 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4313 ASSERT_NE(kmKeyCert, nullptr);
4314 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4315 ASSERT_NE(kmPubKey.get(), nullptr);
4316 size_t kmPubKeySize = 32;
4317 uint8_t kmPubKeyData[32];
4318 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4319 ASSERT_EQ(kmPubKeySize, 32);
4320 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4321
4322 string message(32, 'a');
4323 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4324 string signature = SignMessage(message, params);
4325 LocalVerifyMessage(message, signature, params);
4326}
4327
4328/*
4329 * ImportKeyTest.Ed25519Pkcs8Success
4330 *
4331 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4332 */
4333TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4334 if (!Curve25519Supported()) {
4335 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4336 }
4337
4338 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4339 .Authorization(TAG_NO_AUTH_REQUIRED)
4340 .EcdsaSigningKey(EcCurve::CURVE_25519)
4341 .Digest(Digest::NONE)
4342 .SetDefaultValidity(),
4343 KeyFormat::PKCS8, ed25519_pkcs8_key));
4344 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4345 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4346 CheckOrigin();
4347
4348 // The returned cert should hold the correct public key.
4349 ASSERT_GT(cert_chain_.size(), 0);
4350 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4351 ASSERT_NE(kmKeyCert, nullptr);
4352 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4353 ASSERT_NE(kmPubKey.get(), nullptr);
4354 size_t kmPubKeySize = 32;
4355 uint8_t kmPubKeyData[32];
4356 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4357 ASSERT_EQ(kmPubKeySize, 32);
4358 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4359
4360 string message(32, 'a');
4361 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4362 string signature = SignMessage(message, params);
4363 LocalVerifyMessage(message, signature, params);
4364}
4365
4366/*
4367 * ImportKeyTest.Ed25519CurveMismatch
4368 *
4369 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4370 * the correct way.
4371 */
4372TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4373 if (!Curve25519Supported()) {
4374 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4375 }
4376
4377 ASSERT_NE(ErrorCode::OK,
4378 ImportKey(AuthorizationSetBuilder()
4379 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4380 .Digest(Digest::NONE)
4381 .SetDefaultValidity(),
4382 KeyFormat::RAW, ed25519_key));
4383}
4384
4385/*
4386 * ImportKeyTest.Ed25519FormatMismatch
4387 *
4388 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4389 */
4390TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4391 if (!Curve25519Supported()) {
4392 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4393 }
4394
4395 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4396 .EcdsaSigningKey(EcCurve::CURVE_25519)
4397 .Digest(Digest::NONE)
4398 .SetDefaultValidity(),
4399 KeyFormat::PKCS8, ed25519_key));
4400 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4401 .EcdsaSigningKey(EcCurve::CURVE_25519)
4402 .Digest(Digest::NONE)
4403 .SetDefaultValidity(),
4404 KeyFormat::RAW, ed25519_pkcs8_key));
4405}
4406
4407/*
4408 * ImportKeyTest.Ed25519PurposeMismatch
4409 *
4410 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4411 */
4412TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4413 if (!Curve25519Supported()) {
4414 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4415 }
4416
4417 // Can't have both SIGN and ATTEST_KEY
4418 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4419 .EcdsaSigningKey(EcCurve::CURVE_25519)
4420 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4421 .Digest(Digest::NONE)
4422 .SetDefaultValidity(),
4423 KeyFormat::RAW, ed25519_key));
4424 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4425 // PKCS#8 format and so includes an OID).
4426 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4427 .EcdsaKey(EcCurve::CURVE_25519)
4428 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4429 .Digest(Digest::NONE)
4430 .SetDefaultValidity(),
4431 KeyFormat::PKCS8, ed25519_pkcs8_key));
4432}
4433
4434/*
4435 * ImportKeyTest.X25519RawSuccess
4436 *
4437 * Verifies that importing and using a raw X25519 private key works correctly.
4438 */
4439TEST_P(ImportKeyTest, X25519RawSuccess) {
4440 if (!Curve25519Supported()) {
4441 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4442 }
4443
4444 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4445 .Authorization(TAG_NO_AUTH_REQUIRED)
4446 .EcdsaKey(EcCurve::CURVE_25519)
4447 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4448 .SetDefaultValidity(),
4449 KeyFormat::RAW, x25519_key));
4450
4451 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4452 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4453 CheckOrigin();
4454}
4455
4456/*
4457 * ImportKeyTest.X25519Pkcs8Success
4458 *
4459 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4460 */
4461TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4462 if (!Curve25519Supported()) {
4463 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4464 }
4465
4466 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4467 .Authorization(TAG_NO_AUTH_REQUIRED)
4468 .EcdsaKey(EcCurve::CURVE_25519)
4469 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4470 .SetDefaultValidity(),
4471 KeyFormat::PKCS8, x25519_pkcs8_key));
4472
4473 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4474 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4475 CheckOrigin();
4476}
4477
4478/*
4479 * ImportKeyTest.X25519CurveMismatch
4480 *
4481 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4482 * the correct way.
4483 */
4484TEST_P(ImportKeyTest, X25519CurveMismatch) {
4485 if (!Curve25519Supported()) {
4486 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4487 }
4488
4489 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4490 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4491 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4492 .SetDefaultValidity(),
4493 KeyFormat::RAW, x25519_key));
4494}
4495
4496/*
4497 * ImportKeyTest.X25519FormatMismatch
4498 *
4499 * Verifies that importing an X25519 key with an invalid format fails.
4500 */
4501TEST_P(ImportKeyTest, X25519FormatMismatch) {
4502 if (!Curve25519Supported()) {
4503 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4504 }
4505
4506 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4507 .EcdsaKey(EcCurve::CURVE_25519)
4508 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4509 .SetDefaultValidity(),
4510 KeyFormat::PKCS8, x25519_key));
4511 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4512 .EcdsaKey(EcCurve::CURVE_25519)
4513 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4514 .SetDefaultValidity(),
4515 KeyFormat::RAW, x25519_pkcs8_key));
4516}
4517
4518/*
4519 * ImportKeyTest.X25519PurposeMismatch
4520 *
4521 * Verifies that importing an X25519 key pair with an invalid format fails.
4522 */
4523TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4524 if (!Curve25519Supported()) {
4525 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4526 }
4527
4528 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4529 .EcdsaKey(EcCurve::CURVE_25519)
4530 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4531 .SetDefaultValidity(),
4532 KeyFormat::PKCS8, x25519_pkcs8_key));
4533 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4534 .EcdsaSigningKey(EcCurve::CURVE_25519)
4535 .SetDefaultValidity(),
4536 KeyFormat::PKCS8, x25519_pkcs8_key));
4537}
4538
4539/*
Selene Huang31ab4042020-04-29 04:22:39 -07004540 * ImportKeyTest.AesSuccess
4541 *
4542 * Verifies that importing and using an AES key works.
4543 */
4544TEST_P(ImportKeyTest, AesSuccess) {
4545 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4546 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4547 .Authorization(TAG_NO_AUTH_REQUIRED)
4548 .AesEncryptionKey(key.size() * 8)
4549 .EcbMode()
4550 .Padding(PaddingMode::PKCS7),
4551 KeyFormat::RAW, key));
4552
4553 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4554 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4555 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4556 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4557 CheckOrigin();
4558
4559 string message = "Hello World!";
4560 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4561 string ciphertext = EncryptMessage(message, params);
4562 string plaintext = DecryptMessage(ciphertext, params);
4563 EXPECT_EQ(message, plaintext);
4564}
4565
4566/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004567 * ImportKeyTest.AesFailure
4568 *
4569 * Verifies that importing an invalid AES key fails.
4570 */
4571TEST_P(ImportKeyTest, AesFailure) {
4572 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4573 uint32_t bitlen = key.size() * 8;
4574 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004575 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004576 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004577 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004578 .Authorization(TAG_NO_AUTH_REQUIRED)
4579 .AesEncryptionKey(key_size)
4580 .EcbMode()
4581 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004582 KeyFormat::RAW, key);
4583 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004584 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4585 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004586 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004587
4588 // Explicit key size matches that of the provided key, but it's not a valid size.
4589 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4590 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4591 ImportKey(AuthorizationSetBuilder()
4592 .Authorization(TAG_NO_AUTH_REQUIRED)
4593 .AesEncryptionKey(long_key.size() * 8)
4594 .EcbMode()
4595 .Padding(PaddingMode::PKCS7),
4596 KeyFormat::RAW, long_key));
4597 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4598 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4599 ImportKey(AuthorizationSetBuilder()
4600 .Authorization(TAG_NO_AUTH_REQUIRED)
4601 .AesEncryptionKey(short_key.size() * 8)
4602 .EcbMode()
4603 .Padding(PaddingMode::PKCS7),
4604 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004605}
4606
4607/*
4608 * ImportKeyTest.TripleDesSuccess
4609 *
4610 * Verifies that importing and using a 3DES key works.
4611 */
4612TEST_P(ImportKeyTest, TripleDesSuccess) {
4613 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4614 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4615 .Authorization(TAG_NO_AUTH_REQUIRED)
4616 .TripleDesEncryptionKey(168)
4617 .EcbMode()
4618 .Padding(PaddingMode::PKCS7),
4619 KeyFormat::RAW, key));
4620
4621 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4622 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4623 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4624 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4625 CheckOrigin();
4626
4627 string message = "Hello World!";
4628 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4629 string ciphertext = EncryptMessage(message, params);
4630 string plaintext = DecryptMessage(ciphertext, params);
4631 EXPECT_EQ(message, plaintext);
4632}
4633
4634/*
4635 * ImportKeyTest.TripleDesFailure
4636 *
4637 * Verifies that importing an invalid 3DES key fails.
4638 */
4639TEST_P(ImportKeyTest, TripleDesFailure) {
4640 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004641 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004642 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004643 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004644 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004645 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004646 .Authorization(TAG_NO_AUTH_REQUIRED)
4647 .TripleDesEncryptionKey(key_size)
4648 .EcbMode()
4649 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004650 KeyFormat::RAW, key);
4651 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004652 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4653 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004654 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004655 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004656 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004657 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4658 ImportKey(AuthorizationSetBuilder()
4659 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004660 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004661 .EcbMode()
4662 .Padding(PaddingMode::PKCS7),
4663 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004664 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004665 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4666 ImportKey(AuthorizationSetBuilder()
4667 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004668 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004669 .EcbMode()
4670 .Padding(PaddingMode::PKCS7),
4671 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004672}
4673
4674/*
4675 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004676 *
4677 * Verifies that importing and using an HMAC key works.
4678 */
4679TEST_P(ImportKeyTest, HmacKeySuccess) {
4680 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4681 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4682 .Authorization(TAG_NO_AUTH_REQUIRED)
4683 .HmacKey(key.size() * 8)
4684 .Digest(Digest::SHA_2_256)
4685 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4686 KeyFormat::RAW, key));
4687
4688 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4689 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4690 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4691 CheckOrigin();
4692
4693 string message = "Hello World!";
4694 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4695 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4696}
4697
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004698/*
4699 * ImportKeyTest.GetKeyCharacteristics
4700 *
4701 * Verifies that imported keys have the correct characteristics.
4702 */
4703TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4704 vector<uint8_t> key_blob;
4705 vector<KeyCharacteristics> key_characteristics;
4706 auto base_builder = AuthorizationSetBuilder()
4707 .Padding(PaddingMode::NONE)
4708 .Authorization(TAG_NO_AUTH_REQUIRED)
4709 .SetDefaultValidity();
4710 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4711 Algorithm::TRIPLE_DES};
4712 ErrorCode result;
4713 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4714 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4715 for (auto alg : algorithms) {
4716 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4717 AuthorizationSetBuilder builder(base_builder);
4718 switch (alg) {
4719 case Algorithm::RSA:
4720 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4721
4722 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4723 &key_characteristics);
4724 break;
4725 case Algorithm::EC:
4726 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4727 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4728 &key_characteristics);
4729 break;
4730 case Algorithm::HMAC:
4731 builder.HmacKey(128)
4732 .Digest(Digest::SHA_2_256)
4733 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4734 result =
4735 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4736 break;
4737 case Algorithm::AES:
4738 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4739 result =
4740 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4741 break;
4742 case Algorithm::TRIPLE_DES:
4743 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4744 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4745 &key_characteristics);
4746 break;
4747 default:
4748 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4749 continue;
4750 }
4751 ASSERT_EQ(ErrorCode::OK, result);
4752 CheckCharacteristics(key_blob, key_characteristics);
4753 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4754 }
4755}
4756
Selene Huang31ab4042020-04-29 04:22:39 -07004757INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4758
4759auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004760 // IKeyMintDevice.aidl
4761 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4762 "020100" // INTEGER length 1 value 0x00 (version)
4763 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4764 "934bf94e2aa28a3f83c9f79297250262"
4765 "fbe3276b5a1c91159bbfa3ef8957aac8"
4766 "4b59b30b455a79c2973480823d8b3863"
4767 "c3deef4a8e243590268d80e18751a0e1"
4768 "30f67ce6a1ace9f79b95e097474febc9"
4769 "81195b1d13a69086c0863f66a7b7fdb4"
4770 "8792227b1ac5e2489febdf087ab54864"
4771 "83033a6f001ca5d1ec1e27f5c30f4cec"
4772 "2642074a39ae68aee552e196627a8e3d"
4773 "867e67a8c01b11e75f13cca0a97ab668"
4774 "b50cda07a8ecb7cd8e3dd7009c963653"
4775 "4f6f239cffe1fc8daa466f78b676c711"
4776 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4777 "99b801597d5220e307eaa5bee507fb94"
4778 "d1fa69f9e519b2de315bac92c36f2ea1"
4779 "fa1df4478c0ddedeae8c70e0233cd098"
4780 "040c" // OCTET STRING length 0x0c (initializationVector)
4781 "d796b02c370f1fa4cc0124f1"
4782 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4783 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4784 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4785 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4786 "3106" // SET length 0x06
4787 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4788 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4789 // } end SET
4790 // } end [1]
4791 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4792 "020120" // INTEGER length 1 value 0x20 (AES)
4793 // } end [2]
4794 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4795 "02020100" // INTEGER length 2 value 0x100
4796 // } end [3]
4797 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4798 "3103" // SET length 0x03 {
4799 "020101" // INTEGER length 1 value 0x01 (ECB)
4800 // } end SET
4801 // } end [4]
4802 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4803 "3103" // SET length 0x03 {
4804 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4805 // } end SET
4806 // } end [5]
4807 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4808 // (noAuthRequired)
4809 "0500" // NULL
4810 // } end [503]
4811 // } end SEQUENCE (AuthorizationList)
4812 // } end SEQUENCE (KeyDescription)
4813 "0420" // OCTET STRING length 0x20 (encryptedKey)
4814 "ccd540855f833a5e1480bfd2d36faf3a"
4815 "eee15df5beabe2691bc82dde2a7aa910"
4816 "0410" // OCTET STRING length 0x10 (tag)
4817 "64c9f689c60ff6223ab6e6999e0eb6e5"
4818 // } SEQUENCE (SecureKeyWrapper)
4819);
Selene Huang31ab4042020-04-29 04:22:39 -07004820
4821auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004822 // IKeyMintDevice.aidl
4823 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4824 "020100" // INTEGER length 1 value 0x00 (version)
4825 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4826 "aad93ed5924f283b4bb5526fbe7a1412"
4827 "f9d9749ec30db9062b29e574a8546f33"
4828 "c88732452f5b8e6a391ee76c39ed1712"
4829 "c61d8df6213dec1cffbc17a8c6d04c7b"
4830 "30893d8daa9b2015213e219468215532"
4831 "07f8f9931c4caba23ed3bee28b36947e"
4832 "47f10e0a5c3dc51c988a628daad3e5e1"
4833 "f4005e79c2d5a96c284b4b8d7e4948f3"
4834 "31e5b85dd5a236f85579f3ea1d1b8484"
4835 "87470bdb0ab4f81a12bee42c99fe0df4"
4836 "bee3759453e69ad1d68a809ce06b949f"
4837 "7694a990429b2fe81e066ff43e56a216"
4838 "02db70757922a4bcc23ab89f1e35da77"
4839 "586775f423e519c2ea394caf48a28d0c"
4840 "8020f1dcf6b3a68ec246f615ae96dae9"
4841 "a079b1f6eb959033c1af5c125fd94168"
4842 "040c" // OCTET STRING length 0x0c (initializationVector)
4843 "6d9721d08589581ab49204a3"
4844 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4845 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4846 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4847 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4848 "3106" // SET length 0x06
4849 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4850 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4851 // } end SET
4852 // } end [1]
4853 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4854 "020120" // INTEGER length 1 value 0x20 (AES)
4855 // } end [2]
4856 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4857 "02020100" // INTEGER length 2 value 0x100
4858 // } end [3]
4859 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4860 "3103" // SET length 0x03 {
4861 "020101" // INTEGER length 1 value 0x01 (ECB)
4862 // } end SET
4863 // } end [4]
4864 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4865 "3103" // SET length 0x03 {
4866 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4867 // } end SET
4868 // } end [5]
4869 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4870 // (noAuthRequired)
4871 "0500" // NULL
4872 // } end [503]
4873 // } end SEQUENCE (AuthorizationList)
4874 // } end SEQUENCE (KeyDescription)
4875 "0420" // OCTET STRING length 0x20 (encryptedKey)
4876 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4877 "c20d1f99a9a024a76f35c8e2cab9b68d"
4878 "0410" // OCTET STRING length 0x10 (tag)
4879 "2560c70109ae67c030f00b98b512a670"
4880 // } SEQUENCE (SecureKeyWrapper)
4881);
Selene Huang31ab4042020-04-29 04:22:39 -07004882
4883auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004884 // RFC 5208 s5
4885 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4886 "020100" // INTEGER length 1 value 0x00 (version)
4887 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4888 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4889 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4890 "0500" // NULL (parameters)
4891 // } SEQUENCE (AlgorithmIdentifier)
4892 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4893 // RFC 8017 A.1.2
4894 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4895 "020100" // INTEGER length 1 value 0x00 (version)
4896 "02820101" // INTEGER length 0x0101 (modulus) value...
4897 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4898 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4899 "7b06e673a837313d56b1c725150a3fef" // 0x30
4900 "86acbddc41bb759c2854eae32d35841e" // 0x40
4901 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4902 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4903 "312d7bd5921ffaea1347c157406fef71" // 0x70
4904 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4905 "f4645c11f5c1374c3886427411c44979" // 0x90
4906 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4907 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4908 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4909 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4910 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4911 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4912 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4913 "55" // 0x101
4914 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4915 "02820100" // INTEGER length 0x100 (privateExponent) value...
4916 "431447b6251908112b1ee76f99f3711a" // 0x10
4917 "52b6630960046c2de70de188d833f8b8" // 0x20
4918 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4919 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4920 "e710b630a03adc683b5d2c43080e52be" // 0x50
4921 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4922 "822bccff087d63c940ba8a45f670feb2" // 0x70
4923 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4924 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4925 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4926 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4927 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4928 "52659d5a5ba05b663737a8696281865b" // 0xd0
4929 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4930 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4931 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4932 "028181" // INTEGER length 0x81 (prime1) value...
4933 "00de392e18d682c829266cc3454e1d61" // 0x10
4934 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4935 "ff841be5bac82a164c5970007047b8c5" // 0x30
4936 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4937 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4938 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4939 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4940 "9e91346130748a6e3c124f9149d71c74" // 0x80
4941 "35"
4942 "028181" // INTEGER length 0x81 (prime2) value...
4943 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4944 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4945 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4946 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4947 "9ed39a2d934c880440aed8832f984316" // 0x50
4948 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4949 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4950 "b880677c068e1be936e81288815252a8" // 0x80
4951 "a1"
4952 "028180" // INTEGER length 0x80 (exponent1) value...
4953 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4954 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4955 "5a063212a4f105a3764743e53281988a" // 0x30
4956 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4957 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4958 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4959 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4960 "4719d6e2b9439823719cd08bcd031781" // 0x80
4961 "028181" // INTEGER length 0x81 (exponent2) value...
4962 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4963 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4964 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4965 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4966 "1254186af30b22c10582a8a43e34fe94" // 0x50
4967 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4968 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4969 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4970 "61"
4971 "028181" // INTEGER length 0x81 (coefficient) value...
4972 "00c931617c77829dfb1270502be9195c" // 0x10
4973 "8f2830885f57dba869536811e6864236" // 0x20
4974 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4975 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4976 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4977 "959356210723287b0affcc9f727044d4" // 0x60
4978 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4979 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4980 "22"
4981 // } SEQUENCE
4982 // } SEQUENCE ()
4983);
Selene Huang31ab4042020-04-29 04:22:39 -07004984
4985string zero_masking_key =
4986 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4987string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4988
4989class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4990
4991TEST_P(ImportWrappedKeyTest, Success) {
4992 auto wrapping_key_desc = AuthorizationSetBuilder()
4993 .RsaEncryptionKey(2048, 65537)
4994 .Digest(Digest::SHA_2_256)
4995 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004996 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4997 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004998
4999 ASSERT_EQ(ErrorCode::OK,
5000 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5001 AuthorizationSetBuilder()
5002 .Digest(Digest::SHA_2_256)
5003 .Padding(PaddingMode::RSA_OAEP)));
5004
5005 string message = "Hello World!";
5006 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5007 string ciphertext = EncryptMessage(message, params);
5008 string plaintext = DecryptMessage(ciphertext, params);
5009 EXPECT_EQ(message, plaintext);
5010}
5011
David Drysdaled2cc8c22021-04-15 13:29:45 +01005012/*
5013 * ImportWrappedKeyTest.SuccessSidsIgnored
5014 *
5015 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
5016 * include Tag:USER_SECURE_ID.
5017 */
5018TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
5019 auto wrapping_key_desc = AuthorizationSetBuilder()
5020 .RsaEncryptionKey(2048, 65537)
5021 .Digest(Digest::SHA_2_256)
5022 .Padding(PaddingMode::RSA_OAEP)
5023 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5024 .SetDefaultValidity();
5025
5026 int64_t password_sid = 42;
5027 int64_t biometric_sid = 24;
5028 ASSERT_EQ(ErrorCode::OK,
5029 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5030 AuthorizationSetBuilder()
5031 .Digest(Digest::SHA_2_256)
5032 .Padding(PaddingMode::RSA_OAEP),
5033 password_sid, biometric_sid));
5034
5035 string message = "Hello World!";
5036 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5037 string ciphertext = EncryptMessage(message, params);
5038 string plaintext = DecryptMessage(ciphertext, params);
5039 EXPECT_EQ(message, plaintext);
5040}
5041
Selene Huang31ab4042020-04-29 04:22:39 -07005042TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5043 auto wrapping_key_desc = AuthorizationSetBuilder()
5044 .RsaEncryptionKey(2048, 65537)
5045 .Digest(Digest::SHA_2_256)
5046 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005047 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5048 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005049
5050 ASSERT_EQ(ErrorCode::OK,
5051 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5052 AuthorizationSetBuilder()
5053 .Digest(Digest::SHA_2_256)
5054 .Padding(PaddingMode::RSA_OAEP)));
5055}
5056
5057TEST_P(ImportWrappedKeyTest, WrongMask) {
5058 auto wrapping_key_desc = AuthorizationSetBuilder()
5059 .RsaEncryptionKey(2048, 65537)
5060 .Digest(Digest::SHA_2_256)
5061 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005062 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5063 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005064
5065 ASSERT_EQ(
5066 ErrorCode::VERIFICATION_FAILED,
5067 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5068 AuthorizationSetBuilder()
5069 .Digest(Digest::SHA_2_256)
5070 .Padding(PaddingMode::RSA_OAEP)));
5071}
5072
5073TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5074 auto wrapping_key_desc = AuthorizationSetBuilder()
5075 .RsaEncryptionKey(2048, 65537)
5076 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005077 .Padding(PaddingMode::RSA_OAEP)
5078 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005079
5080 ASSERT_EQ(
5081 ErrorCode::INCOMPATIBLE_PURPOSE,
5082 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5083 AuthorizationSetBuilder()
5084 .Digest(Digest::SHA_2_256)
5085 .Padding(PaddingMode::RSA_OAEP)));
5086}
5087
David Drysdaled2cc8c22021-04-15 13:29:45 +01005088TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5089 auto wrapping_key_desc = AuthorizationSetBuilder()
5090 .RsaEncryptionKey(2048, 65537)
5091 .Digest(Digest::SHA_2_256)
5092 .Padding(PaddingMode::RSA_PSS)
5093 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5094 .SetDefaultValidity();
5095
5096 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5097 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5098 AuthorizationSetBuilder()
5099 .Digest(Digest::SHA_2_256)
5100 .Padding(PaddingMode::RSA_OAEP)));
5101}
5102
5103TEST_P(ImportWrappedKeyTest, WrongDigest) {
5104 auto wrapping_key_desc = AuthorizationSetBuilder()
5105 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005106 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005107 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005108 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5109 .SetDefaultValidity();
5110
5111 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5112 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5113 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005114 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005115 .Padding(PaddingMode::RSA_OAEP)));
5116}
5117
Selene Huang31ab4042020-04-29 04:22:39 -07005118INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5119
5120typedef KeyMintAidlTestBase EncryptionOperationsTest;
5121
5122/*
5123 * EncryptionOperationsTest.RsaNoPaddingSuccess
5124 *
David Drysdale59cae642021-05-12 13:52:03 +01005125 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005126 */
5127TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005128 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005129 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005130 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5131 .Authorization(TAG_NO_AUTH_REQUIRED)
5132 .RsaEncryptionKey(2048, exponent)
5133 .Padding(PaddingMode::NONE)
5134 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005135
David Drysdaled2cc8c22021-04-15 13:29:45 +01005136 string message = string(2048 / 8, 'a');
5137 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005138 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005139 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005140
David Drysdale59cae642021-05-12 13:52:03 +01005141 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005142 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005143
David Drysdaled2cc8c22021-04-15 13:29:45 +01005144 // Unpadded RSA is deterministic
5145 EXPECT_EQ(ciphertext1, ciphertext2);
5146
5147 CheckedDeleteKey();
5148 }
Selene Huang31ab4042020-04-29 04:22:39 -07005149}
5150
5151/*
5152 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5153 *
David Drysdale59cae642021-05-12 13:52:03 +01005154 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005155 */
5156TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5157 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5158 .Authorization(TAG_NO_AUTH_REQUIRED)
5159 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005160 .Padding(PaddingMode::NONE)
5161 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005162
5163 string message = "1";
5164 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5165
David Drysdale59cae642021-05-12 13:52:03 +01005166 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005167 EXPECT_EQ(2048U / 8, ciphertext.size());
5168
5169 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5170 string plaintext = DecryptMessage(ciphertext, params);
5171
5172 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005173}
5174
5175/*
Selene Huang31ab4042020-04-29 04:22:39 -07005176 * EncryptionOperationsTest.RsaOaepSuccess
5177 *
David Drysdale59cae642021-05-12 13:52:03 +01005178 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005179 */
5180TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5181 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5182
5183 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01005184 ASSERT_EQ(ErrorCode::OK,
5185 GenerateKey(AuthorizationSetBuilder()
5186 .Authorization(TAG_NO_AUTH_REQUIRED)
5187 .RsaEncryptionKey(key_size, 65537)
5188 .Padding(PaddingMode::RSA_OAEP)
5189 .Digest(digests)
5190 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
5191 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005192
5193 string message = "Hello";
5194
5195 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005196 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5197
5198 auto params = AuthorizationSetBuilder()
5199 .Digest(digest)
5200 .Padding(PaddingMode::RSA_OAEP)
5201 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5202 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005203 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5204 EXPECT_EQ(key_size / 8, ciphertext1.size());
5205
David Drysdale59cae642021-05-12 13:52:03 +01005206 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005207 EXPECT_EQ(key_size / 8, ciphertext2.size());
5208
5209 // OAEP randomizes padding so every result should be different (with astronomically high
5210 // probability).
5211 EXPECT_NE(ciphertext1, ciphertext2);
5212
5213 string plaintext1 = DecryptMessage(ciphertext1, params);
5214 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5215 string plaintext2 = DecryptMessage(ciphertext2, params);
5216 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5217
5218 // Decrypting corrupted ciphertext should fail.
5219 size_t offset_to_corrupt = random() % ciphertext1.size();
5220 char corrupt_byte;
5221 do {
5222 corrupt_byte = static_cast<char>(random() % 256);
5223 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5224 ciphertext1[offset_to_corrupt] = corrupt_byte;
5225
5226 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5227 string result;
5228 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5229 EXPECT_EQ(0U, result.size());
5230 }
5231}
5232
5233/*
5234 * EncryptionOperationsTest.RsaOaepInvalidDigest
5235 *
David Drysdale59cae642021-05-12 13:52:03 +01005236 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005237 * without a digest.
5238 */
5239TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5240 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5241 .Authorization(TAG_NO_AUTH_REQUIRED)
5242 .RsaEncryptionKey(2048, 65537)
5243 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005244 .Digest(Digest::NONE)
5245 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005246
5247 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005248 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005249}
5250
5251/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005252 * EncryptionOperationsTest.RsaOaepInvalidPadding
5253 *
David Drysdale59cae642021-05-12 13:52:03 +01005254 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005255 * with a padding value that is only suitable for signing/verifying.
5256 */
5257TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5258 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5259 .Authorization(TAG_NO_AUTH_REQUIRED)
5260 .RsaEncryptionKey(2048, 65537)
5261 .Padding(PaddingMode::RSA_PSS)
5262 .Digest(Digest::NONE)
5263 .SetDefaultValidity()));
5264
5265 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005266 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005267}
5268
5269/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005270 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005271 *
David Drysdale59cae642021-05-12 13:52:03 +01005272 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005273 * with a different digest than was used to encrypt.
5274 */
5275TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005276 if (SecLevel() == SecurityLevel::STRONGBOX) {
5277 GTEST_SKIP() << "Test not applicable to StrongBox device";
5278 }
Selene Huang31ab4042020-04-29 04:22:39 -07005279
5280 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5281 .Authorization(TAG_NO_AUTH_REQUIRED)
5282 .RsaEncryptionKey(1024, 65537)
5283 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005284 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5285 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005286 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005287 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005288 message,
5289 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5290
5291 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5292 .Digest(Digest::SHA_2_256)
5293 .Padding(PaddingMode::RSA_OAEP)));
5294 string result;
5295 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5296 EXPECT_EQ(0U, result.size());
5297}
5298
5299/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005300 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5301 *
David Drysdale59cae642021-05-12 13:52:03 +01005302 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005303 * digests.
5304 */
5305TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5306 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5307
5308 size_t key_size = 2048; // Need largish key for SHA-512 test.
5309 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5310 .OaepMGFDigest(digests)
5311 .Authorization(TAG_NO_AUTH_REQUIRED)
5312 .RsaEncryptionKey(key_size, 65537)
5313 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005314 .Digest(Digest::SHA_2_256)
5315 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005316
Shawn Willden20732262023-04-21 16:36:00 -06005317 std::vector<Digest> mgf1DigestsInAuths;
5318 mgf1DigestsInAuths.reserve(digests.size());
5319 const auto& hw_auths = SecLevelAuthorizations(key_characteristics_);
5320 std::for_each(hw_auths.begin(), hw_auths.end(), [&](auto& param) {
5321 if (param.tag == Tag::RSA_OAEP_MGF_DIGEST) {
5322 KeyParameterValue value = param.value;
5323 mgf1DigestsInAuths.push_back(param.value.template get<KeyParameterValue::digest>());
5324 }
5325 });
5326
5327 std::sort(digests.begin(), digests.end());
5328 std::sort(mgf1DigestsInAuths.begin(), mgf1DigestsInAuths.end());
5329 EXPECT_EQ(digests, mgf1DigestsInAuths);
5330
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005331 string message = "Hello";
5332
5333 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005334 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005335 auto params = AuthorizationSetBuilder()
5336 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5337 .Digest(Digest::SHA_2_256)
5338 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005339 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005340 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5341 EXPECT_EQ(key_size / 8, ciphertext1.size());
5342
David Drysdale59cae642021-05-12 13:52:03 +01005343 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005344 EXPECT_EQ(key_size / 8, ciphertext2.size());
5345
5346 // OAEP randomizes padding so every result should be different (with astronomically high
5347 // probability).
5348 EXPECT_NE(ciphertext1, ciphertext2);
5349
5350 string plaintext1 = DecryptMessage(ciphertext1, params);
5351 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5352 string plaintext2 = DecryptMessage(ciphertext2, params);
5353 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5354
5355 // Decrypting corrupted ciphertext should fail.
5356 size_t offset_to_corrupt = random() % ciphertext1.size();
5357 char corrupt_byte;
5358 do {
5359 corrupt_byte = static_cast<char>(random() % 256);
5360 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5361 ciphertext1[offset_to_corrupt] = corrupt_byte;
5362
5363 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5364 string result;
5365 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5366 EXPECT_EQ(0U, result.size());
5367 }
5368}
5369
5370/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005371 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5372 *
5373 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5374 * specified, defaulting to SHA-1.
5375 */
5376TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5377 size_t key_size = 2048;
5378 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5379 .Authorization(TAG_NO_AUTH_REQUIRED)
5380 .RsaEncryptionKey(key_size, 65537)
5381 .Padding(PaddingMode::RSA_OAEP)
5382 .Digest(Digest::SHA_2_256)
5383 .SetDefaultValidity()));
5384
5385 // Do local RSA encryption using the default MGF digest of SHA-1.
5386 string message = "Hello";
5387 auto params =
5388 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5389 string ciphertext = LocalRsaEncryptMessage(message, params);
5390 EXPECT_EQ(key_size / 8, ciphertext.size());
5391
5392 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5393 string plaintext = DecryptMessage(ciphertext, params);
5394 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5395
5396 // Decrypting corrupted ciphertext should fail.
5397 size_t offset_to_corrupt = random() % ciphertext.size();
5398 char corrupt_byte;
5399 do {
5400 corrupt_byte = static_cast<char>(random() % 256);
5401 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5402 ciphertext[offset_to_corrupt] = corrupt_byte;
5403
5404 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5405 string result;
5406 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5407 EXPECT_EQ(0U, result.size());
5408}
5409
5410/*
5411 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5412 *
5413 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5414 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5415 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5416 */
5417TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5418 size_t key_size = 2048;
5419 ASSERT_EQ(ErrorCode::OK,
5420 GenerateKey(AuthorizationSetBuilder()
5421 .Authorization(TAG_NO_AUTH_REQUIRED)
5422 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5423 .RsaEncryptionKey(key_size, 65537)
5424 .Padding(PaddingMode::RSA_OAEP)
5425 .Digest(Digest::SHA_2_256)
5426 .SetDefaultValidity()));
5427
5428 // Do local RSA encryption using the default MGF digest of SHA-1.
5429 string message = "Hello";
5430 auto params =
5431 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5432 string ciphertext = LocalRsaEncryptMessage(message, params);
5433 EXPECT_EQ(key_size / 8, ciphertext.size());
5434
5435 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5436 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5437 // is checked against those values, and found absent.
5438 auto result = Begin(KeyPurpose::DECRYPT, params);
5439 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5440 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5441}
5442
5443/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005444 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5445 *
David Drysdale59cae642021-05-12 13:52:03 +01005446 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005447 * with incompatible MGF digest.
5448 */
5449TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5450 ASSERT_EQ(ErrorCode::OK,
5451 GenerateKey(AuthorizationSetBuilder()
5452 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5453 .Authorization(TAG_NO_AUTH_REQUIRED)
5454 .RsaEncryptionKey(2048, 65537)
5455 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005456 .Digest(Digest::SHA_2_256)
5457 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005458 string message = "Hello World!";
5459
5460 auto params = AuthorizationSetBuilder()
5461 .Padding(PaddingMode::RSA_OAEP)
5462 .Digest(Digest::SHA_2_256)
5463 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005464 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005465}
5466
5467/*
5468 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5469 *
5470 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5471 * with unsupported MGF digest.
5472 */
5473TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5474 ASSERT_EQ(ErrorCode::OK,
5475 GenerateKey(AuthorizationSetBuilder()
5476 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5477 .Authorization(TAG_NO_AUTH_REQUIRED)
5478 .RsaEncryptionKey(2048, 65537)
5479 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005480 .Digest(Digest::SHA_2_256)
5481 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005482 string message = "Hello World!";
5483
5484 auto params = AuthorizationSetBuilder()
5485 .Padding(PaddingMode::RSA_OAEP)
5486 .Digest(Digest::SHA_2_256)
5487 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005488 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005489}
5490
5491/*
Selene Huang31ab4042020-04-29 04:22:39 -07005492 * EncryptionOperationsTest.RsaPkcs1Success
5493 *
5494 * Verifies that RSA PKCS encryption/decrypts works.
5495 */
5496TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5497 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5498 .Authorization(TAG_NO_AUTH_REQUIRED)
5499 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005500 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5501 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005502
5503 string message = "Hello World!";
5504 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005505 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005506 EXPECT_EQ(2048U / 8, ciphertext1.size());
5507
David Drysdale59cae642021-05-12 13:52:03 +01005508 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005509 EXPECT_EQ(2048U / 8, ciphertext2.size());
5510
5511 // PKCS1 v1.5 randomizes padding so every result should be different.
5512 EXPECT_NE(ciphertext1, ciphertext2);
5513
5514 string plaintext = DecryptMessage(ciphertext1, params);
5515 EXPECT_EQ(message, plaintext);
5516
5517 // Decrypting corrupted ciphertext should fail.
5518 size_t offset_to_corrupt = random() % ciphertext1.size();
5519 char corrupt_byte;
5520 do {
5521 corrupt_byte = static_cast<char>(random() % 256);
5522 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5523 ciphertext1[offset_to_corrupt] = corrupt_byte;
5524
5525 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5526 string result;
5527 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5528 EXPECT_EQ(0U, result.size());
5529}
5530
5531/*
Selene Huang31ab4042020-04-29 04:22:39 -07005532 * EncryptionOperationsTest.EcdsaEncrypt
5533 *
5534 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5535 */
5536TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5537 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5538 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005539 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005540 .Digest(Digest::NONE)
5541 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005542 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5543 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5544 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5545}
5546
5547/*
5548 * EncryptionOperationsTest.HmacEncrypt
5549 *
5550 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5551 */
5552TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5553 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5554 .Authorization(TAG_NO_AUTH_REQUIRED)
5555 .HmacKey(128)
5556 .Digest(Digest::SHA_2_256)
5557 .Padding(PaddingMode::NONE)
5558 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5559 auto params = AuthorizationSetBuilder()
5560 .Digest(Digest::SHA_2_256)
5561 .Padding(PaddingMode::NONE)
5562 .Authorization(TAG_MAC_LENGTH, 128);
5563 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5564 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5565}
5566
5567/*
5568 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5569 *
5570 * Verifies that AES ECB mode works.
5571 */
5572TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5573 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5574 .Authorization(TAG_NO_AUTH_REQUIRED)
5575 .AesEncryptionKey(128)
5576 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5577 .Padding(PaddingMode::NONE)));
5578
5579 ASSERT_GT(key_blob_.size(), 0U);
5580 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5581
5582 // Two-block message.
5583 string message = "12345678901234567890123456789012";
5584 string ciphertext1 = EncryptMessage(message, params);
5585 EXPECT_EQ(message.size(), ciphertext1.size());
5586
5587 string ciphertext2 = EncryptMessage(string(message), params);
5588 EXPECT_EQ(message.size(), ciphertext2.size());
5589
5590 // ECB is deterministic.
5591 EXPECT_EQ(ciphertext1, ciphertext2);
5592
5593 string plaintext = DecryptMessage(ciphertext1, params);
5594 EXPECT_EQ(message, plaintext);
5595}
5596
5597/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005598 * EncryptionOperationsTest.AesEcbUnknownTag
5599 *
5600 * Verifies that AES ECB operations ignore unknown tags.
5601 */
5602TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5603 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5604 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5605 KeyParameter unknown_param;
5606 unknown_param.tag = unknown_tag;
5607
5608 vector<KeyCharacteristics> key_characteristics;
5609 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5610 .Authorization(TAG_NO_AUTH_REQUIRED)
5611 .AesEncryptionKey(128)
5612 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5613 .Padding(PaddingMode::NONE)
5614 .Authorization(unknown_param),
5615 &key_blob_, &key_characteristics));
5616 ASSERT_GT(key_blob_.size(), 0U);
5617
5618 // Unknown tags should not be returned in key characteristics.
5619 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5620 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5621 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5622 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5623
5624 // Encrypt without mentioning the unknown parameter.
5625 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5626 string message = "12345678901234567890123456789012";
5627 string ciphertext = EncryptMessage(message, params);
5628 EXPECT_EQ(message.size(), ciphertext.size());
5629
5630 // Decrypt including the unknown parameter.
5631 auto decrypt_params = AuthorizationSetBuilder()
5632 .BlockMode(BlockMode::ECB)
5633 .Padding(PaddingMode::NONE)
5634 .Authorization(unknown_param);
5635 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5636 EXPECT_EQ(message, plaintext);
5637}
5638
5639/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005640 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005641 *
5642 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5643 */
5644TEST_P(EncryptionOperationsTest, AesWrongMode) {
5645 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5646 .Authorization(TAG_NO_AUTH_REQUIRED)
5647 .AesEncryptionKey(128)
5648 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5649 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005650 ASSERT_GT(key_blob_.size(), 0U);
5651
Selene Huang31ab4042020-04-29 04:22:39 -07005652 EXPECT_EQ(
5653 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5654 Begin(KeyPurpose::ENCRYPT,
5655 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5656}
5657
5658/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005659 * EncryptionOperationsTest.AesWrongPadding
5660 *
5661 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5662 */
5663TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5664 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5665 .Authorization(TAG_NO_AUTH_REQUIRED)
5666 .AesEncryptionKey(128)
5667 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5668 .Padding(PaddingMode::NONE)));
5669 ASSERT_GT(key_blob_.size(), 0U);
5670
5671 EXPECT_EQ(
5672 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5673 Begin(KeyPurpose::ENCRYPT,
5674 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5675}
5676
5677/*
5678 * EncryptionOperationsTest.AesInvalidParams
5679 *
5680 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5681 */
5682TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5683 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5684 .Authorization(TAG_NO_AUTH_REQUIRED)
5685 .AesEncryptionKey(128)
5686 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5687 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5688 .Padding(PaddingMode::NONE)
5689 .Padding(PaddingMode::PKCS7)));
5690 ASSERT_GT(key_blob_.size(), 0U);
5691
5692 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5693 .BlockMode(BlockMode::CBC)
5694 .BlockMode(BlockMode::ECB)
5695 .Padding(PaddingMode::NONE));
5696 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5697 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5698
5699 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5700 .BlockMode(BlockMode::ECB)
5701 .Padding(PaddingMode::NONE)
5702 .Padding(PaddingMode::PKCS7));
5703 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5704 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5705}
5706
5707/*
Selene Huang31ab4042020-04-29 04:22:39 -07005708 * EncryptionOperationsTest.AesWrongPurpose
5709 *
5710 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5711 * specified.
5712 */
5713TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5714 auto err = GenerateKey(AuthorizationSetBuilder()
5715 .Authorization(TAG_NO_AUTH_REQUIRED)
5716 .AesKey(128)
5717 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5718 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5719 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5720 .Padding(PaddingMode::NONE));
5721 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5722 ASSERT_GT(key_blob_.size(), 0U);
5723
5724 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5725 .BlockMode(BlockMode::GCM)
5726 .Padding(PaddingMode::NONE)
5727 .Authorization(TAG_MAC_LENGTH, 128));
5728 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5729
5730 CheckedDeleteKey();
5731
5732 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5733 .Authorization(TAG_NO_AUTH_REQUIRED)
5734 .AesKey(128)
5735 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5736 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5737 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5738 .Padding(PaddingMode::NONE)));
5739
5740 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5741 .BlockMode(BlockMode::GCM)
5742 .Padding(PaddingMode::NONE)
5743 .Authorization(TAG_MAC_LENGTH, 128));
5744 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5745}
5746
5747/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005748 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005749 *
5750 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5751 * multiple of the block size and no padding is specified.
5752 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005753TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5754 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005755 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005756 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5757 .Authorization(TAG_NO_AUTH_REQUIRED)
5758 .AesEncryptionKey(128)
5759 .Authorization(TAG_BLOCK_MODE, blockMode)
5760 .Padding(PaddingMode::NONE)));
5761 // Message is slightly shorter than two blocks.
5762 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005763
David Drysdaled2cc8c22021-04-15 13:29:45 +01005764 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5765 AuthorizationSet out_params;
5766 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5767 string ciphertext;
5768 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5769 EXPECT_EQ(0U, ciphertext.size());
5770
5771 CheckedDeleteKey();
5772 }
Selene Huang31ab4042020-04-29 04:22:39 -07005773}
5774
5775/*
5776 * EncryptionOperationsTest.AesEcbPkcs7Padding
5777 *
5778 * Verifies that AES PKCS7 padding works for any message length.
5779 */
5780TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5781 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5782 .Authorization(TAG_NO_AUTH_REQUIRED)
5783 .AesEncryptionKey(128)
5784 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5785 .Padding(PaddingMode::PKCS7)));
5786
5787 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5788
5789 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005790 for (size_t i = 0; i <= 48; i++) {
5791 SCOPED_TRACE(testing::Message() << "i = " << i);
5792 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5793 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005794 string ciphertext = EncryptMessage(message, params);
5795 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5796 string plaintext = DecryptMessage(ciphertext, params);
5797 EXPECT_EQ(message, plaintext);
5798 }
5799}
5800
5801/*
5802 * EncryptionOperationsTest.AesEcbWrongPadding
5803 *
5804 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5805 * specified.
5806 */
5807TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5808 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5809 .Authorization(TAG_NO_AUTH_REQUIRED)
5810 .AesEncryptionKey(128)
5811 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5812 .Padding(PaddingMode::NONE)));
5813
5814 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5815
5816 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005817 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005818 string message(i, 'a');
5819 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5820 }
5821}
5822
5823/*
5824 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5825 *
5826 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5827 */
5828TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5829 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5830 .Authorization(TAG_NO_AUTH_REQUIRED)
5831 .AesEncryptionKey(128)
5832 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5833 .Padding(PaddingMode::PKCS7)));
5834
5835 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5836
5837 string message = "a";
5838 string ciphertext = EncryptMessage(message, params);
5839 EXPECT_EQ(16U, ciphertext.size());
5840 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005841
Seth Moore7a55ae32021-06-23 14:28:11 -07005842 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5843 ++ciphertext[ciphertext.size() / 2];
5844
5845 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5846 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005847 ErrorCode error = Finish(ciphertext, &plaintext);
5848 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005849 // This is the expected error, we can exit the test now.
5850 return;
5851 } else {
5852 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005853 ASSERT_EQ(error, ErrorCode::OK)
5854 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005855 }
5856 }
5857 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005858}
5859
David Drysdaleb8093292022-04-08 12:22:35 +01005860/*
5861 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5862 *
5863 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5864 */
5865TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5866 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5867 .Authorization(TAG_NO_AUTH_REQUIRED)
5868 .AesEncryptionKey(128)
5869 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5870 .Padding(PaddingMode::PKCS7)));
5871
5872 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5873
5874 string message = "a";
5875 string ciphertext = EncryptMessage(message, params);
5876 EXPECT_EQ(16U, ciphertext.size());
5877 EXPECT_NE(ciphertext, message);
5878
5879 // Shorten the ciphertext.
5880 ciphertext.resize(ciphertext.size() - 1);
5881 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5882 string plaintext;
5883 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5884}
5885
Selene Huang31ab4042020-04-29 04:22:39 -07005886vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5887 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005888 EXPECT_TRUE(iv);
5889 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005890}
5891
5892/*
5893 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5894 *
5895 * Verifies that AES CTR mode works.
5896 */
5897TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5898 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5899 .Authorization(TAG_NO_AUTH_REQUIRED)
5900 .AesEncryptionKey(128)
5901 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5902 .Padding(PaddingMode::NONE)));
5903
5904 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5905
5906 string message = "123";
5907 AuthorizationSet out_params;
5908 string ciphertext1 = EncryptMessage(message, params, &out_params);
5909 vector<uint8_t> iv1 = CopyIv(out_params);
5910 EXPECT_EQ(16U, iv1.size());
5911
5912 EXPECT_EQ(message.size(), ciphertext1.size());
5913
5914 out_params.Clear();
5915 string ciphertext2 = EncryptMessage(message, params, &out_params);
5916 vector<uint8_t> iv2 = CopyIv(out_params);
5917 EXPECT_EQ(16U, iv2.size());
5918
5919 // IVs should be random, so ciphertexts should differ.
5920 EXPECT_NE(ciphertext1, ciphertext2);
5921
5922 auto params_iv1 =
5923 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5924 auto params_iv2 =
5925 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5926
5927 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5928 EXPECT_EQ(message, plaintext);
5929 plaintext = DecryptMessage(ciphertext2, params_iv2);
5930 EXPECT_EQ(message, plaintext);
5931
5932 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5933 plaintext = DecryptMessage(ciphertext1, params_iv2);
5934 EXPECT_NE(message, plaintext);
5935 plaintext = DecryptMessage(ciphertext2, params_iv1);
5936 EXPECT_NE(message, plaintext);
5937}
5938
5939/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305940 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005941 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305942 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005943 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305944TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5945 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5946}
Selene Huang31ab4042020-04-29 04:22:39 -07005947
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305948/*
5949 * EncryptionOperationsTest.AesCbcIncremental
5950 *
5951 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5952 */
5953TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5954 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5955}
Selene Huang31ab4042020-04-29 04:22:39 -07005956
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305957/*
5958 * EncryptionOperationsTest.AesCtrIncremental
5959 *
5960 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5961 */
5962TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5963 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5964}
Selene Huang31ab4042020-04-29 04:22:39 -07005965
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305966/*
5967 * EncryptionOperationsTest.AesGcmIncremental
5968 *
5969 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5970 */
5971TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5972 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005973}
5974
Prashant Patildd5f7f02022-07-06 18:58:07 +00005975/*
5976 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
5977 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5978 */
5979TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
5980 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
5981 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
5982 string kat_plaintext =
5983 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
5984 "809FFF37081C22EF278F896AB213A2A631");
5985 string kat_ciphertext =
5986 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
5987 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
5988 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5989 kat_ciphertext);
5990}
5991
5992/*
5993 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
5994 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5995 */
5996TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
5997 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
5998 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
5999 string kat_plaintext =
6000 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
6001 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
6002 string kat_ciphertext =
6003 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
6004 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
6005 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6006 kat_plaintext, kat_ciphertext);
6007}
6008
6009/*
6010 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
6011 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6012 */
6013TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
6014 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
6015 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
6016 string kat_plaintext =
6017 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
6018 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
6019 string kat_ciphertext =
6020 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
6021 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
6022 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6023 kat_ciphertext);
6024}
6025
6026/*
6027 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
6028 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6029 */
6030TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
6031 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
6032 string kat_plaintext =
6033 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
6034 "7B6168A9A27BCE554BEA94EF26E6C742A0");
6035 string kat_ciphertext =
6036 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
6037 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
6038 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6039 kat_ciphertext);
6040}
6041
6042/*
6043 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
6044 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6045 */
6046TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
6047 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
6048 string kat_plaintext =
6049 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
6050 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
6051 string kat_ciphertext =
6052 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6053 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6054 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6055 kat_ciphertext);
6056}
6057
6058/*
6059 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6060 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6061 */
6062TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6063 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6064 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6065 string kat_plaintext =
6066 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6067 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6068 string kat_ciphertext =
6069 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6070 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6071 "bdfcc0cba0");
6072
6073 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6074 kat_ciphertext);
6075}
6076
6077/*
6078 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6079 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6080 */
6081TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6082 if (SecLevel() == SecurityLevel::STRONGBOX) {
6083 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6084 }
6085 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6086 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6087 string kat_plaintext =
6088 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6089 "167f2497c994bd496eb80bfb2ba2c9d5af");
6090 string kat_ciphertext =
6091 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6092 "72c134552f3a138e726fbe493b3a839598");
6093 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6094 kat_ciphertext);
6095}
6096
6097/*
6098 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6099 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6100 */
6101TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6102 if (SecLevel() == SecurityLevel::STRONGBOX) {
6103 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6104 }
6105 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6106 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6107 string kat_plaintext =
6108 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6109 "b170");
6110 string kat_ciphertext =
6111 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6112 "4e3884138ff403a41fd99818708ada301c");
6113 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6114 kat_plaintext, kat_ciphertext);
6115}
6116
6117/*
6118 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6119 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6120 */
6121TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6122 if (SecLevel() == SecurityLevel::STRONGBOX) {
6123 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6124 }
6125 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6126 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6127 string kat_plaintext =
6128 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6129 "28091e09cdbbd3b42b");
6130 string kat_ciphertext =
6131 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6132 "2ae0f90f0c19f42b4a");
6133 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6134 kat_ciphertext);
6135}
6136
6137/*
6138 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6139 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6140 */
6141TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6142 if (SecLevel() == SecurityLevel::STRONGBOX) {
6143 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6144 }
6145 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6146 string kat_plaintext =
6147 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6148 "44ab");
6149 string kat_ciphertext =
6150 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6151 "2453");
6152 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6153 kat_ciphertext);
6154}
6155
6156/*
6157 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6158 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6159 */
6160TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6161 if (SecLevel() == SecurityLevel::STRONGBOX) {
6162 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6163 }
6164 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6165 string kat_plaintext =
6166 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6167 "e2c7");
6168 string kat_ciphertext =
6169 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6170 "bb7e3a889dd4a9589098b44acf1056e7aa");
6171 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6172 kat_ciphertext);
6173}
6174
6175/*
6176 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6177 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6178 */
6179TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6180 if (SecLevel() == SecurityLevel::STRONGBOX) {
6181 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6182 }
6183 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6184 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6185 string kat_plaintext =
6186 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6187 "ff52");
6188 string kat_ciphertext =
6189 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6190 "1413ad70fb0e1970669095ad77ebb5974ae8");
6191
6192 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6193 kat_ciphertext);
6194}
6195
6196/*
6197 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6198 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6199 */
6200TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6201 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6202 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6203 string kat_plaintext =
6204 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6205 "494cb53caca353e4b637ba05687be20f8d");
6206 string kat_ciphertext =
6207 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6208 "6047da1e4fd7c4e1cf2656097f75ae8685");
6209 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6210 kat_ciphertext);
6211}
6212
6213/*
6214 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6215 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6216 */
6217TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6218 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6219 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6220 string kat_plaintext =
6221 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6222 "2545a82b73c48078b9dae62261c65909");
6223 string kat_ciphertext =
6224 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6225 "9403a71987b95124073d69f2a3cb95b0ab");
6226 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6227 kat_plaintext, kat_ciphertext);
6228}
6229
6230/*
6231 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6232 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6233 */
6234TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6235 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6236 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6237 string kat_plaintext =
6238 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6239 "1f6db3c884");
6240 string kat_ciphertext =
6241 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6242 "a7be30d4c3");
6243 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6244 kat_ciphertext);
6245}
6246
6247/*
6248 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6249 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6250 */
6251TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6252 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6253 string kat_plaintext =
6254 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6255 "31a476d6806b8116089c6ec50bb543200f");
6256 string kat_ciphertext =
6257 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6258 "c83e377faf246288931136bef2a07c0be4");
6259 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6260 kat_ciphertext);
6261}
6262
6263/*
6264 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6265 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6266 */
6267TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6268 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6269 string kat_plaintext =
6270 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6271 "6f");
6272 string kat_ciphertext =
6273 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6274 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6275 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6276 kat_ciphertext);
6277}
6278
6279/*
6280 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6281 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6282 */
6283TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6284 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6285 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6286 string kat_plaintext =
6287 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6288 "f0");
6289 string kat_ciphertext =
6290 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6291 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6292
6293 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6294 kat_ciphertext);
6295}
6296
Selene Huang31ab4042020-04-29 04:22:39 -07006297struct AesCtrSp80038aTestVector {
6298 const char* key;
6299 const char* nonce;
6300 const char* plaintext;
6301 const char* ciphertext;
6302};
6303
6304// These test vectors are taken from
6305// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6306static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6307 // AES-128
6308 {
6309 "2b7e151628aed2a6abf7158809cf4f3c",
6310 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6311 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6312 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6313 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6314 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6315 },
6316 // AES-192
6317 {
6318 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6319 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6320 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6321 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6322 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6323 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6324 },
6325 // AES-256
6326 {
6327 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6328 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6329 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6330 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6331 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6332 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6333 },
6334};
6335
6336/*
6337 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6338 *
6339 * Verifies AES CTR implementation against SP800-38A test vectors.
6340 */
6341TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6342 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6343 for (size_t i = 0; i < 3; i++) {
6344 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6345 const string key = hex2str(test.key);
6346 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6347 InvalidSizes.end())
6348 continue;
6349 const string nonce = hex2str(test.nonce);
6350 const string plaintext = hex2str(test.plaintext);
6351 const string ciphertext = hex2str(test.ciphertext);
6352 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6353 }
6354}
6355
6356/*
6357 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6358 *
6359 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6360 */
6361TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6362 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6363 .Authorization(TAG_NO_AUTH_REQUIRED)
6364 .AesEncryptionKey(128)
6365 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6366 .Padding(PaddingMode::PKCS7)));
6367 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6368 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6369}
6370
6371/*
6372 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6373 *
6374 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6375 */
6376TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6377 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6378 .Authorization(TAG_NO_AUTH_REQUIRED)
6379 .AesEncryptionKey(128)
6380 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6381 .Authorization(TAG_CALLER_NONCE)
6382 .Padding(PaddingMode::NONE)));
6383
6384 auto params = AuthorizationSetBuilder()
6385 .BlockMode(BlockMode::CTR)
6386 .Padding(PaddingMode::NONE)
6387 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6388 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6389
6390 params = AuthorizationSetBuilder()
6391 .BlockMode(BlockMode::CTR)
6392 .Padding(PaddingMode::NONE)
6393 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6394 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6395
6396 params = AuthorizationSetBuilder()
6397 .BlockMode(BlockMode::CTR)
6398 .Padding(PaddingMode::NONE)
6399 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6400 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6401}
6402
6403/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006404 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006405 *
6406 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6407 */
6408TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6409 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6410 .Authorization(TAG_NO_AUTH_REQUIRED)
6411 .AesEncryptionKey(128)
6412 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6413 .Padding(PaddingMode::NONE)));
6414 // Two-block message.
6415 string message = "12345678901234567890123456789012";
6416 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6417 AuthorizationSet out_params;
6418 string ciphertext1 = EncryptMessage(message, params, &out_params);
6419 vector<uint8_t> iv1 = CopyIv(out_params);
6420 EXPECT_EQ(message.size(), ciphertext1.size());
6421
6422 out_params.Clear();
6423
6424 string ciphertext2 = EncryptMessage(message, params, &out_params);
6425 vector<uint8_t> iv2 = CopyIv(out_params);
6426 EXPECT_EQ(message.size(), ciphertext2.size());
6427
6428 // IVs should be random, so ciphertexts should differ.
6429 EXPECT_NE(ciphertext1, ciphertext2);
6430
6431 params.push_back(TAG_NONCE, iv1);
6432 string plaintext = DecryptMessage(ciphertext1, params);
6433 EXPECT_EQ(message, plaintext);
6434}
6435
6436/*
Tommy Chiuee705692021-09-23 20:09:13 +08006437 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6438 *
6439 * Verifies that keymaster generates correct output on zero-input with
6440 * NonePadding mode
6441 */
6442TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6443 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6444 .Authorization(TAG_NO_AUTH_REQUIRED)
6445 .AesEncryptionKey(128)
6446 .BlockMode(BlockMode::CBC)
6447 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6448
6449 // Zero input message
6450 string message = "";
6451 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006452 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006453 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6454 AuthorizationSet out_params;
6455 string ciphertext1 = EncryptMessage(message, params, &out_params);
6456 vector<uint8_t> iv1 = CopyIv(out_params);
6457 if (padding == PaddingMode::NONE)
6458 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6459 else
6460 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6461
6462 out_params.Clear();
6463
6464 string ciphertext2 = EncryptMessage(message, params, &out_params);
6465 vector<uint8_t> iv2 = CopyIv(out_params);
6466 if (padding == PaddingMode::NONE)
6467 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6468 else
6469 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6470
6471 // IVs should be random
6472 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6473
6474 params.push_back(TAG_NONCE, iv1);
6475 string plaintext = DecryptMessage(ciphertext1, params);
6476 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6477 }
6478}
6479
6480/*
Selene Huang31ab4042020-04-29 04:22:39 -07006481 * EncryptionOperationsTest.AesCallerNonce
6482 *
6483 * Verifies that AES caller-provided nonces work correctly.
6484 */
6485TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6486 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6487 .Authorization(TAG_NO_AUTH_REQUIRED)
6488 .AesEncryptionKey(128)
6489 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6490 .Authorization(TAG_CALLER_NONCE)
6491 .Padding(PaddingMode::NONE)));
6492
6493 string message = "12345678901234567890123456789012";
6494
6495 // Don't specify nonce, should get a random one.
6496 AuthorizationSetBuilder params =
6497 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6498 AuthorizationSet out_params;
6499 string ciphertext = EncryptMessage(message, params, &out_params);
6500 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006501 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006502
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006503 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006504 string plaintext = DecryptMessage(ciphertext, params);
6505 EXPECT_EQ(message, plaintext);
6506
6507 // Now specify a nonce, should also work.
6508 params = AuthorizationSetBuilder()
6509 .BlockMode(BlockMode::CBC)
6510 .Padding(PaddingMode::NONE)
6511 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6512 out_params.Clear();
6513 ciphertext = EncryptMessage(message, params, &out_params);
6514
6515 // Decrypt with correct nonce.
6516 plaintext = DecryptMessage(ciphertext, params);
6517 EXPECT_EQ(message, plaintext);
6518
6519 // Try with wrong nonce.
6520 params = AuthorizationSetBuilder()
6521 .BlockMode(BlockMode::CBC)
6522 .Padding(PaddingMode::NONE)
6523 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6524 plaintext = DecryptMessage(ciphertext, params);
6525 EXPECT_NE(message, plaintext);
6526}
6527
6528/*
6529 * EncryptionOperationsTest.AesCallerNonceProhibited
6530 *
6531 * Verifies that caller-provided nonces are not permitted when not specified in the key
6532 * authorizations.
6533 */
6534TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6535 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6536 .Authorization(TAG_NO_AUTH_REQUIRED)
6537 .AesEncryptionKey(128)
6538 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6539 .Padding(PaddingMode::NONE)));
6540
6541 string message = "12345678901234567890123456789012";
6542
6543 // Don't specify nonce, should get a random one.
6544 AuthorizationSetBuilder params =
6545 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6546 AuthorizationSet out_params;
6547 string ciphertext = EncryptMessage(message, params, &out_params);
6548 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006549 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006550
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006551 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006552 string plaintext = DecryptMessage(ciphertext, params);
6553 EXPECT_EQ(message, plaintext);
6554
6555 // Now specify a nonce, should fail
6556 params = AuthorizationSetBuilder()
6557 .BlockMode(BlockMode::CBC)
6558 .Padding(PaddingMode::NONE)
6559 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6560 out_params.Clear();
6561 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6562}
6563
6564/*
6565 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6566 *
6567 * Verifies that AES GCM mode works.
6568 */
6569TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6570 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6571 .Authorization(TAG_NO_AUTH_REQUIRED)
6572 .AesEncryptionKey(128)
6573 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6574 .Padding(PaddingMode::NONE)
6575 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6576
6577 string aad = "foobar";
6578 string message = "123456789012345678901234567890123456";
6579
6580 auto begin_params = AuthorizationSetBuilder()
6581 .BlockMode(BlockMode::GCM)
6582 .Padding(PaddingMode::NONE)
6583 .Authorization(TAG_MAC_LENGTH, 128);
6584
Selene Huang31ab4042020-04-29 04:22:39 -07006585 // Encrypt
6586 AuthorizationSet begin_out_params;
6587 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6588 << "Begin encrypt";
6589 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006590 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6591 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006592 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6593
6594 // Grab nonce
6595 begin_params.push_back(begin_out_params);
6596
6597 // Decrypt.
6598 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006599 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006600 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006601 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006602 EXPECT_EQ(message.length(), plaintext.length());
6603 EXPECT_EQ(message, plaintext);
6604}
6605
6606/*
6607 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6608 *
6609 * Verifies that AES GCM mode works, even when there's a long delay
6610 * between operations.
6611 */
6612TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6613 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6614 .Authorization(TAG_NO_AUTH_REQUIRED)
6615 .AesEncryptionKey(128)
6616 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6617 .Padding(PaddingMode::NONE)
6618 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6619
6620 string aad = "foobar";
6621 string message = "123456789012345678901234567890123456";
6622
6623 auto begin_params = AuthorizationSetBuilder()
6624 .BlockMode(BlockMode::GCM)
6625 .Padding(PaddingMode::NONE)
6626 .Authorization(TAG_MAC_LENGTH, 128);
6627
Selene Huang31ab4042020-04-29 04:22:39 -07006628 // Encrypt
6629 AuthorizationSet begin_out_params;
6630 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6631 << "Begin encrypt";
6632 string ciphertext;
6633 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006634 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006635 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006636 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006637
6638 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6639
6640 // Grab nonce
6641 begin_params.push_back(begin_out_params);
6642
6643 // Decrypt.
6644 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6645 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006646 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006647 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006648 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006649 sleep(5);
6650 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6651 EXPECT_EQ(message.length(), plaintext.length());
6652 EXPECT_EQ(message, plaintext);
6653}
6654
6655/*
6656 * EncryptionOperationsTest.AesGcmDifferentNonces
6657 *
6658 * Verifies that encrypting the same data with different nonces produces different outputs.
6659 */
6660TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6661 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6662 .Authorization(TAG_NO_AUTH_REQUIRED)
6663 .AesEncryptionKey(128)
6664 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6665 .Padding(PaddingMode::NONE)
6666 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6667 .Authorization(TAG_CALLER_NONCE)));
6668
6669 string aad = "foobar";
6670 string message = "123456789012345678901234567890123456";
6671 string nonce1 = "000000000000";
6672 string nonce2 = "111111111111";
6673 string nonce3 = "222222222222";
6674
6675 string ciphertext1 =
6676 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6677 string ciphertext2 =
6678 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6679 string ciphertext3 =
6680 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6681
6682 ASSERT_NE(ciphertext1, ciphertext2);
6683 ASSERT_NE(ciphertext1, ciphertext3);
6684 ASSERT_NE(ciphertext2, ciphertext3);
6685}
6686
6687/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006688 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6689 *
6690 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6691 */
6692TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6693 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6694 .Authorization(TAG_NO_AUTH_REQUIRED)
6695 .AesEncryptionKey(128)
6696 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6697 .Padding(PaddingMode::NONE)
6698 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6699
6700 string aad = "foobar";
6701 string message = "123456789012345678901234567890123456";
6702
6703 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6704 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6705 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6706
6707 ASSERT_NE(ciphertext1, ciphertext2);
6708 ASSERT_NE(ciphertext1, ciphertext3);
6709 ASSERT_NE(ciphertext2, ciphertext3);
6710}
6711
6712/*
Selene Huang31ab4042020-04-29 04:22:39 -07006713 * EncryptionOperationsTest.AesGcmTooShortTag
6714 *
6715 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6716 */
6717TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6718 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6719 .Authorization(TAG_NO_AUTH_REQUIRED)
6720 .AesEncryptionKey(128)
6721 .BlockMode(BlockMode::GCM)
6722 .Padding(PaddingMode::NONE)
6723 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6724 string message = "123456789012345678901234567890123456";
6725 auto params = AuthorizationSetBuilder()
6726 .BlockMode(BlockMode::GCM)
6727 .Padding(PaddingMode::NONE)
6728 .Authorization(TAG_MAC_LENGTH, 96);
6729
6730 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6731}
6732
6733/*
6734 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6735 *
6736 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6737 */
6738TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6739 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6740 .Authorization(TAG_NO_AUTH_REQUIRED)
6741 .AesEncryptionKey(128)
6742 .BlockMode(BlockMode::GCM)
6743 .Padding(PaddingMode::NONE)
6744 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6745 string aad = "foobar";
6746 string message = "123456789012345678901234567890123456";
6747 auto params = AuthorizationSetBuilder()
6748 .BlockMode(BlockMode::GCM)
6749 .Padding(PaddingMode::NONE)
6750 .Authorization(TAG_MAC_LENGTH, 128);
6751
Selene Huang31ab4042020-04-29 04:22:39 -07006752 // Encrypt
6753 AuthorizationSet begin_out_params;
6754 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6755 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006756 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006757
6758 AuthorizationSet finish_out_params;
6759 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006760 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6761 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006762
6763 params = AuthorizationSetBuilder()
6764 .Authorizations(begin_out_params)
6765 .BlockMode(BlockMode::GCM)
6766 .Padding(PaddingMode::NONE)
6767 .Authorization(TAG_MAC_LENGTH, 96);
6768
6769 // Decrypt.
6770 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6771}
6772
6773/*
6774 * EncryptionOperationsTest.AesGcmCorruptKey
6775 *
6776 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6777 */
6778TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6779 const uint8_t nonce_bytes[] = {
6780 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6781 };
6782 string nonce = make_string(nonce_bytes);
6783 const uint8_t ciphertext_bytes[] = {
6784 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6785 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6786 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6787 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6788 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6789 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6790 };
6791 string ciphertext = make_string(ciphertext_bytes);
6792
6793 auto params = AuthorizationSetBuilder()
6794 .BlockMode(BlockMode::GCM)
6795 .Padding(PaddingMode::NONE)
6796 .Authorization(TAG_MAC_LENGTH, 128)
6797 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6798
6799 auto import_params = AuthorizationSetBuilder()
6800 .Authorization(TAG_NO_AUTH_REQUIRED)
6801 .AesEncryptionKey(128)
6802 .BlockMode(BlockMode::GCM)
6803 .Padding(PaddingMode::NONE)
6804 .Authorization(TAG_CALLER_NONCE)
6805 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6806
6807 // Import correct key and decrypt
6808 const uint8_t key_bytes[] = {
6809 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6810 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6811 };
6812 string key = make_string(key_bytes);
6813 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6814 string plaintext = DecryptMessage(ciphertext, params);
6815 CheckedDeleteKey();
6816
6817 // Corrupt key and attempt to decrypt
6818 key[0] = 0;
6819 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6820 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6821 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6822 CheckedDeleteKey();
6823}
6824
6825/*
6826 * EncryptionOperationsTest.AesGcmAadNoData
6827 *
6828 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6829 * encrypt.
6830 */
6831TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6832 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6833 .Authorization(TAG_NO_AUTH_REQUIRED)
6834 .AesEncryptionKey(128)
6835 .BlockMode(BlockMode::GCM)
6836 .Padding(PaddingMode::NONE)
6837 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6838
6839 string aad = "1234567890123456";
6840 auto params = AuthorizationSetBuilder()
6841 .BlockMode(BlockMode::GCM)
6842 .Padding(PaddingMode::NONE)
6843 .Authorization(TAG_MAC_LENGTH, 128);
6844
Selene Huang31ab4042020-04-29 04:22:39 -07006845 // Encrypt
6846 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006847 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006848 string ciphertext;
6849 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006850 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6851 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006852 EXPECT_TRUE(finish_out_params.empty());
6853
6854 // Grab nonce
6855 params.push_back(begin_out_params);
6856
6857 // Decrypt.
6858 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006859 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006860 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006861 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006862
6863 EXPECT_TRUE(finish_out_params.empty());
6864
6865 EXPECT_EQ("", plaintext);
6866}
6867
6868/*
6869 * EncryptionOperationsTest.AesGcmMultiPartAad
6870 *
6871 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6872 * chunks.
6873 */
6874TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6875 const size_t tag_bits = 128;
6876 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6877 .Authorization(TAG_NO_AUTH_REQUIRED)
6878 .AesEncryptionKey(128)
6879 .BlockMode(BlockMode::GCM)
6880 .Padding(PaddingMode::NONE)
6881 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6882
6883 string message = "123456789012345678901234567890123456";
6884 auto begin_params = AuthorizationSetBuilder()
6885 .BlockMode(BlockMode::GCM)
6886 .Padding(PaddingMode::NONE)
6887 .Authorization(TAG_MAC_LENGTH, tag_bits);
6888 AuthorizationSet begin_out_params;
6889
David Drysdale7fc26b92022-05-13 09:54:24 +01006890 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006891
6892 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006893 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6894 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006895 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006896 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6897 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006898
Selene Huang31ab4042020-04-29 04:22:39 -07006899 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006900 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006901
6902 // Grab nonce.
6903 begin_params.push_back(begin_out_params);
6904
6905 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006906 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006907 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006908 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006909 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006910 EXPECT_EQ(message, plaintext);
6911}
6912
6913/*
6914 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6915 *
6916 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6917 */
6918TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6919 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6920 .Authorization(TAG_NO_AUTH_REQUIRED)
6921 .AesEncryptionKey(128)
6922 .BlockMode(BlockMode::GCM)
6923 .Padding(PaddingMode::NONE)
6924 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6925
6926 string message = "123456789012345678901234567890123456";
6927 auto begin_params = AuthorizationSetBuilder()
6928 .BlockMode(BlockMode::GCM)
6929 .Padding(PaddingMode::NONE)
6930 .Authorization(TAG_MAC_LENGTH, 128);
6931 AuthorizationSet begin_out_params;
6932
David Drysdale7fc26b92022-05-13 09:54:24 +01006933 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006934
Shawn Willden92d79c02021-02-19 07:31:55 -07006935 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006936 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006937 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6938 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006939
David Drysdaled2cc8c22021-04-15 13:29:45 +01006940 // The failure should have already cancelled the operation.
6941 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6942
Shawn Willden92d79c02021-02-19 07:31:55 -07006943 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006944}
6945
6946/*
6947 * EncryptionOperationsTest.AesGcmBadAad
6948 *
6949 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6950 */
6951TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6952 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6953 .Authorization(TAG_NO_AUTH_REQUIRED)
6954 .AesEncryptionKey(128)
6955 .BlockMode(BlockMode::GCM)
6956 .Padding(PaddingMode::NONE)
6957 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6958
6959 string message = "12345678901234567890123456789012";
6960 auto begin_params = AuthorizationSetBuilder()
6961 .BlockMode(BlockMode::GCM)
6962 .Padding(PaddingMode::NONE)
6963 .Authorization(TAG_MAC_LENGTH, 128);
6964
Selene Huang31ab4042020-04-29 04:22:39 -07006965 // Encrypt
6966 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006967 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006968 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006969 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006970 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006971
6972 // Grab nonce
6973 begin_params.push_back(begin_out_params);
6974
Selene Huang31ab4042020-04-29 04:22:39 -07006975 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006976 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006977 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006978 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006979 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006980}
6981
6982/*
6983 * EncryptionOperationsTest.AesGcmWrongNonce
6984 *
6985 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6986 */
6987TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6988 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6989 .Authorization(TAG_NO_AUTH_REQUIRED)
6990 .AesEncryptionKey(128)
6991 .BlockMode(BlockMode::GCM)
6992 .Padding(PaddingMode::NONE)
6993 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6994
6995 string message = "12345678901234567890123456789012";
6996 auto begin_params = AuthorizationSetBuilder()
6997 .BlockMode(BlockMode::GCM)
6998 .Padding(PaddingMode::NONE)
6999 .Authorization(TAG_MAC_LENGTH, 128);
7000
Selene Huang31ab4042020-04-29 04:22:39 -07007001 // Encrypt
7002 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007003 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007004 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007005 string ciphertext;
7006 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07007007 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007008
7009 // Wrong nonce
7010 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
7011
7012 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007013 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007014 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007015 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007016 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007017
7018 // With wrong nonce, should have gotten garbage plaintext (or none).
7019 EXPECT_NE(message, plaintext);
7020}
7021
7022/*
7023 * EncryptionOperationsTest.AesGcmCorruptTag
7024 *
7025 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
7026 */
7027TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
7028 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7029 .Authorization(TAG_NO_AUTH_REQUIRED)
7030 .AesEncryptionKey(128)
7031 .BlockMode(BlockMode::GCM)
7032 .Padding(PaddingMode::NONE)
7033 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7034
7035 string aad = "1234567890123456";
7036 string message = "123456789012345678901234567890123456";
7037
7038 auto params = AuthorizationSetBuilder()
7039 .BlockMode(BlockMode::GCM)
7040 .Padding(PaddingMode::NONE)
7041 .Authorization(TAG_MAC_LENGTH, 128);
7042
Selene Huang31ab4042020-04-29 04:22:39 -07007043 // Encrypt
7044 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007045 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007046 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007047 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007048 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007049
7050 // Corrupt tag
7051 ++(*ciphertext.rbegin());
7052
7053 // Grab nonce
7054 params.push_back(begin_out_params);
7055
7056 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007057 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007058 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007059 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007060 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007061}
7062
7063/*
7064 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7065 *
7066 * Verifies that 3DES is basically functional.
7067 */
7068TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7069 auto auths = AuthorizationSetBuilder()
7070 .TripleDesEncryptionKey(168)
7071 .BlockMode(BlockMode::ECB)
7072 .Authorization(TAG_NO_AUTH_REQUIRED)
7073 .Padding(PaddingMode::NONE);
7074
7075 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7076 // Two-block message.
7077 string message = "1234567890123456";
7078 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7079 string ciphertext1 = EncryptMessage(message, inParams);
7080 EXPECT_EQ(message.size(), ciphertext1.size());
7081
7082 string ciphertext2 = EncryptMessage(string(message), inParams);
7083 EXPECT_EQ(message.size(), ciphertext2.size());
7084
7085 // ECB is deterministic.
7086 EXPECT_EQ(ciphertext1, ciphertext2);
7087
7088 string plaintext = DecryptMessage(ciphertext1, inParams);
7089 EXPECT_EQ(message, plaintext);
7090}
7091
7092/*
7093 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7094 *
7095 * Verifies that CBC keys reject ECB usage.
7096 */
7097TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7098 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7099 .TripleDesEncryptionKey(168)
7100 .BlockMode(BlockMode::CBC)
7101 .Authorization(TAG_NO_AUTH_REQUIRED)
7102 .Padding(PaddingMode::NONE)));
7103
7104 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7105 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7106}
7107
7108/*
7109 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7110 *
7111 * Tests ECB mode with PKCS#7 padding, various message sizes.
7112 */
7113TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7114 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7115 .TripleDesEncryptionKey(168)
7116 .BlockMode(BlockMode::ECB)
7117 .Authorization(TAG_NO_AUTH_REQUIRED)
7118 .Padding(PaddingMode::PKCS7)));
7119
7120 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007121 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007122 string message(i, 'a');
7123 auto inParams =
7124 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7125 string ciphertext = EncryptMessage(message, inParams);
7126 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7127 string plaintext = DecryptMessage(ciphertext, inParams);
7128 EXPECT_EQ(message, plaintext);
7129 }
7130}
7131
7132/*
7133 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7134 *
7135 * Verifies that keys configured for no padding reject PKCS7 padding
7136 */
7137TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7138 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7139 .TripleDesEncryptionKey(168)
7140 .BlockMode(BlockMode::ECB)
7141 .Authorization(TAG_NO_AUTH_REQUIRED)
7142 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007143 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7144 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007145}
7146
7147/*
7148 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7149 *
7150 * Verifies that corrupted padding is detected.
7151 */
7152TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7153 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7154 .TripleDesEncryptionKey(168)
7155 .BlockMode(BlockMode::ECB)
7156 .Authorization(TAG_NO_AUTH_REQUIRED)
7157 .Padding(PaddingMode::PKCS7)));
7158
7159 string message = "a";
7160 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7161 EXPECT_EQ(8U, ciphertext.size());
7162 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007163
7164 AuthorizationSetBuilder begin_params;
7165 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7166 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007167
7168 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7169 ++ciphertext[ciphertext.size() / 2];
7170
David Drysdale7fc26b92022-05-13 09:54:24 +01007171 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007172 string plaintext;
7173 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7174 ErrorCode error = Finish(&plaintext);
7175 if (error == ErrorCode::INVALID_ARGUMENT) {
7176 // This is the expected error, we can exit the test now.
7177 return;
7178 } else {
7179 // Very small chance we got valid decryption, so try again.
7180 ASSERT_EQ(error, ErrorCode::OK);
7181 }
7182 }
7183 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007184}
7185
7186struct TripleDesTestVector {
7187 const char* name;
7188 const KeyPurpose purpose;
7189 const BlockMode block_mode;
7190 const PaddingMode padding_mode;
7191 const char* key;
7192 const char* iv;
7193 const char* input;
7194 const char* output;
7195};
7196
7197// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7198// of the NIST vectors are multiples of the block size.
7199static const TripleDesTestVector kTripleDesTestVectors[] = {
7200 {
7201 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7202 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7203 "", // IV
7204 "329d86bdf1bc5af4", // input
7205 "d946c2756d78633f", // output
7206 },
7207 {
7208 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7209 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7210 "", // IV
7211 "6b1540781b01ce1997adae102dbf3c5b", // input
7212 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7213 },
7214 {
7215 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7216 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7217 "", // IV
7218 "6daad94ce08acfe7", // input
7219 "660e7d32dcc90e79", // output
7220 },
7221 {
7222 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7223 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7224 "", // IV
7225 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7226 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7227 },
7228 {
7229 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7230 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7231 "43f791134c5647ba", // IV
7232 "dcc153cef81d6f24", // input
7233 "92538bd8af18d3ba", // output
7234 },
7235 {
7236 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7237 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7238 "c2e999cb6249023c", // IV
7239 "c689aee38a301bb316da75db36f110b5", // input
7240 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7241 },
7242 {
7243 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7244 PaddingMode::PKCS7,
7245 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7246 "c2e999cb6249023c", // IV
7247 "c689aee38a301bb316da75db36f110b500", // input
7248 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7249 },
7250 {
7251 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7252 PaddingMode::PKCS7,
7253 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7254 "c2e999cb6249023c", // IV
7255 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7256 "c689aee38a301bb316da75db36f110b500", // output
7257 },
7258 {
7259 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7260 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7261 "41746c7e442d3681", // IV
7262 "c53a7b0ec40600fe", // input
7263 "d4f00eb455de1034", // output
7264 },
7265 {
7266 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7267 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7268 "3982bc02c3727d45", // IV
7269 "6006f10adef52991fcc777a1238bbb65", // input
7270 "edae09288e9e3bc05746d872b48e3b29", // output
7271 },
7272};
7273
7274/*
7275 * EncryptionOperationsTest.TripleDesTestVector
7276 *
7277 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7278 */
7279TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7280 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7281 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7282 SCOPED_TRACE(test->name);
7283 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7284 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7285 hex2str(test->output));
7286 }
7287}
7288
7289/*
7290 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7291 *
7292 * Validates CBC mode functionality.
7293 */
7294TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7295 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7296 .TripleDesEncryptionKey(168)
7297 .BlockMode(BlockMode::CBC)
7298 .Authorization(TAG_NO_AUTH_REQUIRED)
7299 .Padding(PaddingMode::NONE)));
7300
7301 ASSERT_GT(key_blob_.size(), 0U);
7302
Brian J Murray734c8412022-01-13 14:55:30 -08007303 // Four-block message.
7304 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007305 vector<uint8_t> iv1;
7306 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7307 EXPECT_EQ(message.size(), ciphertext1.size());
7308
7309 vector<uint8_t> iv2;
7310 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7311 EXPECT_EQ(message.size(), ciphertext2.size());
7312
7313 // IVs should be random, so ciphertexts should differ.
7314 EXPECT_NE(iv1, iv2);
7315 EXPECT_NE(ciphertext1, ciphertext2);
7316
7317 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7318 EXPECT_EQ(message, plaintext);
7319}
7320
7321/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007322 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7323 *
7324 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7325 */
7326TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7327 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7328 .TripleDesEncryptionKey(168)
7329 .BlockMode(BlockMode::CBC)
7330 .Authorization(TAG_NO_AUTH_REQUIRED)
7331 .Authorization(TAG_CALLER_NONCE)
7332 .Padding(PaddingMode::NONE)));
7333 auto params = AuthorizationSetBuilder()
7334 .BlockMode(BlockMode::CBC)
7335 .Padding(PaddingMode::NONE)
7336 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7337 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7338}
7339
7340/*
Selene Huang31ab4042020-04-29 04:22:39 -07007341 * EncryptionOperationsTest.TripleDesCallerIv
7342 *
7343 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7344 */
7345TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7346 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7347 .TripleDesEncryptionKey(168)
7348 .BlockMode(BlockMode::CBC)
7349 .Authorization(TAG_NO_AUTH_REQUIRED)
7350 .Authorization(TAG_CALLER_NONCE)
7351 .Padding(PaddingMode::NONE)));
7352 string message = "1234567890123456";
7353 vector<uint8_t> iv;
7354 // Don't specify IV, should get a random one.
7355 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7356 EXPECT_EQ(message.size(), ciphertext1.size());
7357 EXPECT_EQ(8U, iv.size());
7358
7359 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7360 EXPECT_EQ(message, plaintext);
7361
7362 // Now specify an IV, should also work.
7363 iv = AidlBuf("abcdefgh");
7364 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7365
7366 // Decrypt with correct IV.
7367 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7368 EXPECT_EQ(message, plaintext);
7369
7370 // Now try with wrong IV.
7371 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7372 EXPECT_NE(message, plaintext);
7373}
7374
7375/*
7376 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7377 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007378 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007379 */
7380TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7381 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7382 .TripleDesEncryptionKey(168)
7383 .BlockMode(BlockMode::CBC)
7384 .Authorization(TAG_NO_AUTH_REQUIRED)
7385 .Padding(PaddingMode::NONE)));
7386
7387 string message = "12345678901234567890123456789012";
7388 vector<uint8_t> iv;
7389 // Don't specify nonce, should get a random one.
7390 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7391 EXPECT_EQ(message.size(), ciphertext1.size());
7392 EXPECT_EQ(8U, iv.size());
7393
7394 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7395 EXPECT_EQ(message, plaintext);
7396
7397 // Now specify a nonce, should fail.
7398 auto input_params = AuthorizationSetBuilder()
7399 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7400 .BlockMode(BlockMode::CBC)
7401 .Padding(PaddingMode::NONE);
7402 AuthorizationSet output_params;
7403 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7404 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7405}
7406
7407/*
7408 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7409 *
7410 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7411 */
7412TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7413 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7414 .TripleDesEncryptionKey(168)
7415 .BlockMode(BlockMode::ECB)
7416 .Authorization(TAG_NO_AUTH_REQUIRED)
7417 .Padding(PaddingMode::NONE)));
7418 // Two-block message.
7419 string message = "1234567890123456";
7420 auto begin_params =
7421 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7422 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7423}
7424
7425/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007426 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007427 *
7428 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7429 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007430TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7431 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007432 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007433 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7434 .TripleDesEncryptionKey(168)
7435 .BlockMode(blockMode)
7436 .Authorization(TAG_NO_AUTH_REQUIRED)
7437 .Padding(PaddingMode::NONE)));
7438 // Message is slightly shorter than two blocks.
7439 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007440
David Drysdaled2cc8c22021-04-15 13:29:45 +01007441 auto begin_params =
7442 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7443 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007444 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007445 string ciphertext;
7446 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7447
7448 CheckedDeleteKey();
7449 }
Selene Huang31ab4042020-04-29 04:22:39 -07007450}
7451
7452/*
7453 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7454 *
7455 * Verifies that PKCS7 padding works correctly in CBC mode.
7456 */
7457TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7458 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7459 .TripleDesEncryptionKey(168)
7460 .BlockMode(BlockMode::CBC)
7461 .Authorization(TAG_NO_AUTH_REQUIRED)
7462 .Padding(PaddingMode::PKCS7)));
7463
7464 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007465 for (size_t i = 0; i <= 32; i++) {
7466 SCOPED_TRACE(testing::Message() << "i = " << i);
7467 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7468 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007469 vector<uint8_t> iv;
7470 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7471 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7472 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7473 EXPECT_EQ(message, plaintext);
7474 }
7475}
7476
7477/*
7478 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7479 *
7480 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7481 */
7482TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7483 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7484 .TripleDesEncryptionKey(168)
7485 .BlockMode(BlockMode::CBC)
7486 .Authorization(TAG_NO_AUTH_REQUIRED)
7487 .Padding(PaddingMode::NONE)));
7488
7489 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007490 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007491 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007492 auto begin_params =
7493 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7494 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7495 }
7496}
7497
7498/*
7499 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7500 *
7501 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7502 */
7503TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7504 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7505 .TripleDesEncryptionKey(168)
7506 .BlockMode(BlockMode::CBC)
7507 .Authorization(TAG_NO_AUTH_REQUIRED)
7508 .Padding(PaddingMode::PKCS7)));
7509
7510 string message = "a";
7511 vector<uint8_t> iv;
7512 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7513 EXPECT_EQ(8U, ciphertext.size());
7514 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007515
7516 auto begin_params = AuthorizationSetBuilder()
7517 .BlockMode(BlockMode::CBC)
7518 .Padding(PaddingMode::PKCS7)
7519 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007520
7521 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007522 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007523 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007524 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007525 string plaintext;
7526 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7527 ErrorCode error = Finish(&plaintext);
7528 if (error == ErrorCode::INVALID_ARGUMENT) {
7529 // This is the expected error, we can exit the test now.
7530 return;
7531 } else {
7532 // Very small chance we got valid decryption, so try again.
7533 ASSERT_EQ(error, ErrorCode::OK);
7534 }
7535 }
7536 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007537}
7538
7539/*
7540 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7541 *
7542 * Verifies that 3DES CBC works with many different input sizes.
7543 */
7544TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7545 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7546 .TripleDesEncryptionKey(168)
7547 .BlockMode(BlockMode::CBC)
7548 .Authorization(TAG_NO_AUTH_REQUIRED)
7549 .Padding(PaddingMode::NONE)));
7550
7551 int increment = 7;
7552 string message(240, 'a');
7553 AuthorizationSet input_params =
7554 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7555 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007556 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007557
7558 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007559 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007560 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007561 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7562 EXPECT_EQ(message.size(), ciphertext.size());
7563
7564 // Move TAG_NONCE into input_params
7565 input_params = output_params;
7566 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7567 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7568 output_params.Clear();
7569
David Drysdale7fc26b92022-05-13 09:54:24 +01007570 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007571 string plaintext;
7572 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007573 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007574 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7575 EXPECT_EQ(ciphertext.size(), plaintext.size());
7576 EXPECT_EQ(message, plaintext);
7577}
7578
7579INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7580
7581typedef KeyMintAidlTestBase MaxOperationsTest;
7582
7583/*
7584 * MaxOperationsTest.TestLimitAes
7585 *
7586 * Verifies that the max uses per boot tag works correctly with AES keys.
7587 */
7588TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007589 if (SecLevel() == SecurityLevel::STRONGBOX) {
7590 GTEST_SKIP() << "Test not applicable to StrongBox device";
7591 }
Selene Huang31ab4042020-04-29 04:22:39 -07007592
7593 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7594 .Authorization(TAG_NO_AUTH_REQUIRED)
7595 .AesEncryptionKey(128)
7596 .EcbMode()
7597 .Padding(PaddingMode::NONE)
7598 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7599
7600 string message = "1234567890123456";
7601
7602 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7603
7604 EncryptMessage(message, params);
7605 EncryptMessage(message, params);
7606 EncryptMessage(message, params);
7607
7608 // Fourth time should fail.
7609 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7610}
7611
7612/*
Qi Wud22ec842020-11-26 13:27:53 +08007613 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007614 *
7615 * Verifies that the max uses per boot tag works correctly with RSA keys.
7616 */
7617TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007618 if (SecLevel() == SecurityLevel::STRONGBOX) {
7619 GTEST_SKIP() << "Test not applicable to StrongBox device";
7620 }
Selene Huang31ab4042020-04-29 04:22:39 -07007621
7622 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7623 .Authorization(TAG_NO_AUTH_REQUIRED)
7624 .RsaSigningKey(1024, 65537)
7625 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007626 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7627 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007628
7629 string message = "1234567890123456";
7630
7631 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7632
7633 SignMessage(message, params);
7634 SignMessage(message, params);
7635 SignMessage(message, params);
7636
7637 // Fourth time should fail.
7638 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7639}
7640
7641INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7642
Qi Wud22ec842020-11-26 13:27:53 +08007643typedef KeyMintAidlTestBase UsageCountLimitTest;
7644
7645/*
Qi Wubeefae42021-01-28 23:16:37 +08007646 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007647 *
Qi Wubeefae42021-01-28 23:16:37 +08007648 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007649 */
Qi Wubeefae42021-01-28 23:16:37 +08007650TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007651 if (SecLevel() == SecurityLevel::STRONGBOX) {
7652 GTEST_SKIP() << "Test not applicable to StrongBox device";
7653 }
Qi Wud22ec842020-11-26 13:27:53 +08007654
7655 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7656 .Authorization(TAG_NO_AUTH_REQUIRED)
7657 .AesEncryptionKey(128)
7658 .EcbMode()
7659 .Padding(PaddingMode::NONE)
7660 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7661
7662 // Check the usage count limit tag appears in the authorizations.
7663 AuthorizationSet auths;
7664 for (auto& entry : key_characteristics_) {
7665 auths.push_back(AuthorizationSet(entry.authorizations));
7666 }
7667 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7668 << "key usage count limit " << 1U << " missing";
7669
7670 string message = "1234567890123456";
7671 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7672
Qi Wubeefae42021-01-28 23:16:37 +08007673 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7674 AuthorizationSet keystore_auths =
7675 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7676
Qi Wud22ec842020-11-26 13:27:53 +08007677 // First usage of AES key should work.
7678 EncryptMessage(message, params);
7679
Qi Wud22ec842020-11-26 13:27:53 +08007680 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7681 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7682 // must be invalidated from secure storage (such as RPMB partition).
7683 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7684 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007685 // Usage count limit tag is enforced by keystore, keymint does nothing.
7686 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007687 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007688 }
7689}
7690
7691/*
Qi Wubeefae42021-01-28 23:16:37 +08007692 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007693 *
Qi Wubeefae42021-01-28 23:16:37 +08007694 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007695 */
Qi Wubeefae42021-01-28 23:16:37 +08007696TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007697 if (SecLevel() == SecurityLevel::STRONGBOX) {
7698 GTEST_SKIP() << "Test not applicable to StrongBox device";
7699 }
Qi Wubeefae42021-01-28 23:16:37 +08007700
7701 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7702 .Authorization(TAG_NO_AUTH_REQUIRED)
7703 .AesEncryptionKey(128)
7704 .EcbMode()
7705 .Padding(PaddingMode::NONE)
7706 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7707
7708 // Check the usage count limit tag appears in the authorizations.
7709 AuthorizationSet auths;
7710 for (auto& entry : key_characteristics_) {
7711 auths.push_back(AuthorizationSet(entry.authorizations));
7712 }
7713 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7714 << "key usage count limit " << 3U << " missing";
7715
7716 string message = "1234567890123456";
7717 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7718
7719 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7720 AuthorizationSet keystore_auths =
7721 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7722
7723 EncryptMessage(message, params);
7724 EncryptMessage(message, params);
7725 EncryptMessage(message, params);
7726
7727 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7728 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7729 // must be invalidated from secure storage (such as RPMB partition).
7730 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7731 } else {
7732 // Usage count limit tag is enforced by keystore, keymint does nothing.
7733 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007734 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007735 }
7736}
7737
7738/*
7739 * UsageCountLimitTest.TestSingleUseRsa
7740 *
7741 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7742 */
7743TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007744 if (SecLevel() == SecurityLevel::STRONGBOX) {
7745 GTEST_SKIP() << "Test not applicable to StrongBox device";
7746 }
Qi Wud22ec842020-11-26 13:27:53 +08007747
7748 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7749 .Authorization(TAG_NO_AUTH_REQUIRED)
7750 .RsaSigningKey(1024, 65537)
7751 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007752 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7753 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007754
7755 // Check the usage count limit tag appears in the authorizations.
7756 AuthorizationSet auths;
7757 for (auto& entry : key_characteristics_) {
7758 auths.push_back(AuthorizationSet(entry.authorizations));
7759 }
7760 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7761 << "key usage count limit " << 1U << " missing";
7762
7763 string message = "1234567890123456";
7764 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7765
Qi Wubeefae42021-01-28 23:16:37 +08007766 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7767 AuthorizationSet keystore_auths =
7768 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7769
Qi Wud22ec842020-11-26 13:27:53 +08007770 // First usage of RSA key should work.
7771 SignMessage(message, params);
7772
Qi Wud22ec842020-11-26 13:27:53 +08007773 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7774 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7775 // must be invalidated from secure storage (such as RPMB partition).
7776 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7777 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007778 // Usage count limit tag is enforced by keystore, keymint does nothing.
7779 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007780 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007781 }
7782}
7783
7784/*
7785 * UsageCountLimitTest.TestLimitUseRsa
7786 *
7787 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7788 */
7789TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007790 if (SecLevel() == SecurityLevel::STRONGBOX) {
7791 GTEST_SKIP() << "Test not applicable to StrongBox device";
7792 }
Qi Wubeefae42021-01-28 23:16:37 +08007793
7794 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7795 .Authorization(TAG_NO_AUTH_REQUIRED)
7796 .RsaSigningKey(1024, 65537)
7797 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007798 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7799 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007800
7801 // Check the usage count limit tag appears in the authorizations.
7802 AuthorizationSet auths;
7803 for (auto& entry : key_characteristics_) {
7804 auths.push_back(AuthorizationSet(entry.authorizations));
7805 }
7806 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7807 << "key usage count limit " << 3U << " missing";
7808
7809 string message = "1234567890123456";
7810 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7811
7812 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7813 AuthorizationSet keystore_auths =
7814 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7815
7816 SignMessage(message, params);
7817 SignMessage(message, params);
7818 SignMessage(message, params);
7819
7820 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7821 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7822 // must be invalidated from secure storage (such as RPMB partition).
7823 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7824 } else {
7825 // Usage count limit tag is enforced by keystore, keymint does nothing.
7826 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007827 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007828 }
7829}
7830
Qi Wu8e727f72021-02-11 02:49:33 +08007831/*
7832 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7833 *
7834 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7835 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7836 * in hardware.
7837 */
7838TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
Qi Wu8e727f72021-02-11 02:49:33 +08007839 auto error = GenerateKey(AuthorizationSetBuilder()
7840 .RsaSigningKey(2048, 65537)
7841 .Digest(Digest::NONE)
7842 .Padding(PaddingMode::NONE)
7843 .Authorization(TAG_NO_AUTH_REQUIRED)
7844 .Authorization(TAG_ROLLBACK_RESISTANCE)
7845 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007846 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7847 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007848 }
David Drysdale513bf122021-10-06 11:53:13 +01007849
7850 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7851 ASSERT_EQ(ErrorCode::OK, error);
7852 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7853 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7854 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7855
7856 // The KeyMint should also enforce single use key in hardware when it supports rollback
7857 // resistance.
7858 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7859 .Authorization(TAG_NO_AUTH_REQUIRED)
7860 .RsaSigningKey(1024, 65537)
7861 .NoDigestOrPadding()
7862 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7863 .SetDefaultValidity()));
7864
7865 // Check the usage count limit tag appears in the hardware authorizations.
7866 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7867 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7868 << "key usage count limit " << 1U << " missing";
7869
7870 string message = "1234567890123456";
7871 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7872
7873 // First usage of RSA key should work.
7874 SignMessage(message, params);
7875
7876 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7877 // must be invalidated from secure storage (such as RPMB partition).
7878 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007879}
7880
Qi Wud22ec842020-11-26 13:27:53 +08007881INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7882
David Drysdale7de9feb2021-03-05 14:56:19 +00007883typedef KeyMintAidlTestBase GetHardwareInfoTest;
7884
7885TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7886 // Retrieving hardware info should give the same result each time.
7887 KeyMintHardwareInfo info;
7888 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7889 KeyMintHardwareInfo info2;
7890 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7891 EXPECT_EQ(info, info2);
7892}
7893
7894INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7895
Selene Huang31ab4042020-04-29 04:22:39 -07007896typedef KeyMintAidlTestBase AddEntropyTest;
7897
7898/*
7899 * AddEntropyTest.AddEntropy
7900 *
7901 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7902 * is actually added.
7903 */
7904TEST_P(AddEntropyTest, AddEntropy) {
7905 string data = "foo";
7906 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7907}
7908
7909/*
7910 * AddEntropyTest.AddEmptyEntropy
7911 *
7912 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7913 */
7914TEST_P(AddEntropyTest, AddEmptyEntropy) {
7915 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7916}
7917
7918/*
7919 * AddEntropyTest.AddLargeEntropy
7920 *
7921 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7922 */
7923TEST_P(AddEntropyTest, AddLargeEntropy) {
7924 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7925}
7926
David Drysdalebb3d85e2021-04-13 11:15:51 +01007927/*
7928 * AddEntropyTest.AddTooLargeEntropy
7929 *
7930 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7931 */
7932TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7933 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7934 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7935}
7936
Selene Huang31ab4042020-04-29 04:22:39 -07007937INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7938
Selene Huang31ab4042020-04-29 04:22:39 -07007939typedef KeyMintAidlTestBase KeyDeletionTest;
7940
7941/**
7942 * KeyDeletionTest.DeleteKey
7943 *
7944 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7945 * valid key blob.
7946 */
7947TEST_P(KeyDeletionTest, DeleteKey) {
7948 auto error = GenerateKey(AuthorizationSetBuilder()
7949 .RsaSigningKey(2048, 65537)
7950 .Digest(Digest::NONE)
7951 .Padding(PaddingMode::NONE)
7952 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007953 .Authorization(TAG_ROLLBACK_RESISTANCE)
7954 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007955 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7956 GTEST_SKIP() << "Rollback resistance not supported";
7957 }
Selene Huang31ab4042020-04-29 04:22:39 -07007958
7959 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007960 ASSERT_EQ(ErrorCode::OK, error);
7961 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7962 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007963
David Drysdale513bf122021-10-06 11:53:13 +01007964 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007965
David Drysdale513bf122021-10-06 11:53:13 +01007966 string message = "12345678901234567890123456789012";
7967 AuthorizationSet begin_out_params;
7968 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7969 Begin(KeyPurpose::SIGN, key_blob_,
7970 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7971 &begin_out_params));
7972 AbortIfNeeded();
7973 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007974}
7975
7976/**
7977 * KeyDeletionTest.DeleteInvalidKey
7978 *
7979 * This test checks that the HAL excepts invalid key blobs..
7980 */
7981TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7982 // Generate key just to check if rollback protection is implemented
7983 auto error = GenerateKey(AuthorizationSetBuilder()
7984 .RsaSigningKey(2048, 65537)
7985 .Digest(Digest::NONE)
7986 .Padding(PaddingMode::NONE)
7987 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007988 .Authorization(TAG_ROLLBACK_RESISTANCE)
7989 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007990 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7991 GTEST_SKIP() << "Rollback resistance not supported";
7992 }
Selene Huang31ab4042020-04-29 04:22:39 -07007993
7994 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007995 ASSERT_EQ(ErrorCode::OK, error);
7996 AuthorizationSet enforced(SecLevelAuthorizations());
7997 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007998
David Drysdale513bf122021-10-06 11:53:13 +01007999 // Delete the key we don't care about the result at this point.
8000 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07008001
David Drysdale513bf122021-10-06 11:53:13 +01008002 // Now create an invalid key blob and delete it.
8003 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07008004
David Drysdale513bf122021-10-06 11:53:13 +01008005 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07008006}
8007
8008/**
8009 * KeyDeletionTest.DeleteAllKeys
8010 *
8011 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
8012 *
8013 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
8014 * FBE/FDE encryption keys, which means that the device will not even boot until after the
8015 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
8016 * been provisioned. Use this test only on dedicated testing devices that have no valuable
8017 * credentials stored in Keystore/Keymint.
8018 */
8019TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01008020 if (!arm_deleteAllKeys) {
8021 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
8022 return;
8023 }
Selene Huang31ab4042020-04-29 04:22:39 -07008024 auto error = GenerateKey(AuthorizationSetBuilder()
8025 .RsaSigningKey(2048, 65537)
8026 .Digest(Digest::NONE)
8027 .Padding(PaddingMode::NONE)
8028 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06008029 .Authorization(TAG_ROLLBACK_RESISTANCE)
8030 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008031 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8032 GTEST_SKIP() << "Rollback resistance not supported";
8033 }
Selene Huang31ab4042020-04-29 04:22:39 -07008034
8035 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008036 ASSERT_EQ(ErrorCode::OK, error);
8037 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8038 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008039
David Drysdale513bf122021-10-06 11:53:13 +01008040 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07008041
David Drysdale513bf122021-10-06 11:53:13 +01008042 string message = "12345678901234567890123456789012";
8043 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07008044
David Drysdale513bf122021-10-06 11:53:13 +01008045 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8046 Begin(KeyPurpose::SIGN, key_blob_,
8047 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8048 &begin_out_params));
8049 AbortIfNeeded();
8050 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008051}
8052
8053INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8054
David Drysdaled2cc8c22021-04-15 13:29:45 +01008055typedef KeyMintAidlTestBase KeyUpgradeTest;
8056
8057/**
8058 * KeyUpgradeTest.UpgradeInvalidKey
8059 *
8060 * This test checks that the HAL excepts invalid key blobs..
8061 */
8062TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8063 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8064
8065 std::vector<uint8_t> new_blob;
8066 Status result = keymint_->upgradeKey(key_blob,
8067 AuthorizationSetBuilder()
8068 .Authorization(TAG_APPLICATION_ID, "clientid")
8069 .Authorization(TAG_APPLICATION_DATA, "appdata")
8070 .vector_data(),
8071 &new_blob);
8072 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8073}
8074
8075INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8076
Selene Huang31ab4042020-04-29 04:22:39 -07008077using UpgradeKeyTest = KeyMintAidlTestBase;
8078
8079/*
8080 * UpgradeKeyTest.UpgradeKey
8081 *
8082 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8083 */
8084TEST_P(UpgradeKeyTest, UpgradeKey) {
8085 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8086 .AesEncryptionKey(128)
8087 .Padding(PaddingMode::NONE)
8088 .Authorization(TAG_NO_AUTH_REQUIRED)));
8089
8090 auto result = UpgradeKey(key_blob_);
8091
8092 // Key doesn't need upgrading. Should get okay, but no new key blob.
8093 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8094}
8095
8096INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8097
8098using ClearOperationsTest = KeyMintAidlTestBase;
8099
8100/*
8101 * ClearSlotsTest.TooManyOperations
8102 *
8103 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8104 * operations are started without being finished or aborted. Also verifies
8105 * that aborting the operations clears the operations.
8106 *
8107 */
8108TEST_P(ClearOperationsTest, TooManyOperations) {
8109 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8110 .Authorization(TAG_NO_AUTH_REQUIRED)
8111 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008112 .Padding(PaddingMode::NONE)
8113 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008114
8115 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8116 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008117 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008118 AuthorizationSet out_params;
8119 ErrorCode result;
8120 size_t i;
8121
8122 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008123 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008124 if (ErrorCode::OK != result) {
8125 break;
8126 }
8127 }
8128 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8129 // Try again just in case there's a weird overflow bug
8130 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008131 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008132 for (size_t j = 0; j < i; j++) {
8133 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8134 << "Aboort failed for i = " << j << std::endl;
8135 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008136 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008137 AbortIfNeeded();
8138}
8139
8140INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8141
8142typedef KeyMintAidlTestBase TransportLimitTest;
8143
8144/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008145 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008146 *
8147 * Verifies that passing input data to finish succeeds as expected.
8148 */
8149TEST_P(TransportLimitTest, LargeFinishInput) {
8150 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8151 .Authorization(TAG_NO_AUTH_REQUIRED)
8152 .AesEncryptionKey(128)
8153 .BlockMode(BlockMode::ECB)
8154 .Padding(PaddingMode::NONE)));
8155
8156 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008157 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008158 auto cipher_params =
8159 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8160
8161 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008162 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008163
8164 string plain_message = std::string(1 << msg_size, 'x');
8165 string encrypted_message;
8166 auto rc = Finish(plain_message, &encrypted_message);
8167
8168 EXPECT_EQ(ErrorCode::OK, rc);
8169 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8170 << "Encrypt finish returned OK, but did not consume all of the given input";
8171 cipher_params.push_back(out_params);
8172
David Drysdale7fc26b92022-05-13 09:54:24 +01008173 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008174
8175 string decrypted_message;
8176 rc = Finish(encrypted_message, &decrypted_message);
8177 EXPECT_EQ(ErrorCode::OK, rc);
8178 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8179 << "Decrypt finish returned OK, did not consume all of the given input";
8180 }
8181}
8182
8183INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8184
Seth Moored79a0ec2021-12-13 20:03:33 +00008185static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008186 switch (curve) {
8187 case EcCurve::P_224:
8188 return NID_secp224r1;
8189 case EcCurve::P_256:
8190 return NID_X9_62_prime256v1;
8191 case EcCurve::P_384:
8192 return NID_secp384r1;
8193 case EcCurve::P_521:
8194 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008195 case EcCurve::CURVE_25519:
8196 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008197 }
8198}
8199
David Drysdale42fe1892021-10-14 14:43:46 +01008200class KeyAgreementTest : public KeyMintAidlTestBase {
8201 protected:
8202 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8203 std::vector<uint8_t>* localPublicKey) {
8204 // Generate EC key locally (with access to private key material)
8205 if (localCurve == EcCurve::CURVE_25519) {
8206 uint8_t privKeyData[32];
8207 uint8_t pubKeyData[32];
8208 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008209 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8210 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8211 } else {
8212 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8213 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8214 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8215 ASSERT_NE(group, nullptr);
8216 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8217 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8218 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8219 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008220 }
David Drysdalea410b772022-05-09 16:44:13 +01008221
8222 // Get encoded form of the public part of the locally generated key...
8223 unsigned char* p = nullptr;
8224 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8225 ASSERT_GT(localPublicKeySize, 0);
8226 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8227 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8228 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008229 }
8230
8231 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8232 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008233 auto builder = AuthorizationSetBuilder()
8234 .Authorization(TAG_NO_AUTH_REQUIRED)
8235 .Authorization(TAG_EC_CURVE, curve)
8236 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8237 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8238 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8239 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8240 .SetDefaultValidity();
8241 ErrorCode result = GenerateKey(builder);
8242
8243 if (SecLevel() == SecurityLevel::STRONGBOX) {
8244 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8245 result = GenerateKeyWithSelfSignedAttestKey(
8246 AuthorizationSetBuilder()
8247 .EcdsaKey(EcCurve::P_256)
8248 .AttestKey()
8249 .SetDefaultValidity(), /* attest key params */
8250 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8251 }
8252 }
David Drysdale42fe1892021-10-14 14:43:46 +01008253 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8254 ASSERT_GT(cert_chain_.size(), 0);
8255 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8256 ASSERT_NE(kmKeyCert, nullptr);
8257 // Check that keyAgreement (bit 4) is set in KeyUsage
8258 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8259 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8260 ASSERT_NE(*kmPubKey, nullptr);
8261 if (dump_Attestations) {
8262 for (size_t n = 0; n < cert_chain_.size(); n++) {
8263 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8264 }
8265 }
8266 }
8267
8268 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8269 const std::vector<uint8_t>& localPublicKey) {
8270 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8271 string ZabFromKeyMintStr;
8272 ASSERT_EQ(ErrorCode::OK,
8273 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8274 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8275 vector<uint8_t> ZabFromTest;
8276
8277 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8278 size_t kmPubKeySize = 32;
8279 uint8_t kmPubKeyData[32];
8280 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8281 ASSERT_EQ(kmPubKeySize, 32);
8282
8283 uint8_t localPrivKeyData[32];
8284 size_t localPrivKeySize = 32;
8285 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8286 &localPrivKeySize));
8287 ASSERT_EQ(localPrivKeySize, 32);
8288
8289 uint8_t sharedKey[32];
8290 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8291 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8292 } else {
8293 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8294 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8295 ASSERT_NE(ctx, nullptr);
8296 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8297 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8298 size_t ZabFromTestLen = 0;
8299 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8300 ZabFromTest.resize(ZabFromTestLen);
8301 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8302 }
8303 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8304 }
8305};
8306
David Zeuthene0c40892021-01-08 12:54:11 -05008307/*
8308 * KeyAgreementTest.Ecdh
8309 *
David Drysdale42fe1892021-10-14 14:43:46 +01008310 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008311 */
8312TEST_P(KeyAgreementTest, Ecdh) {
8313 // Because it's possible to use this API with keys on different curves, we
8314 // check all N^2 combinations where N is the number of supported
8315 // curves.
8316 //
8317 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8318 // lot more curves we can be smart about things and just pick |otherCurve| so
8319 // it's not |curve| and that way we end up with only 2*N runs
8320 //
8321 for (auto curve : ValidCurves()) {
8322 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008323 SCOPED_TRACE(testing::Message()
8324 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8325
David Zeuthene0c40892021-01-08 12:54:11 -05008326 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008327 EVP_PKEY_Ptr localPrivKey;
8328 vector<uint8_t> localPublicKey;
8329 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008330
8331 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008332 EVP_PKEY_Ptr kmPubKey;
8333 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008334
8335 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8336 if (curve != localCurve) {
8337 // If the keys are using different curves KeyMint should fail with
8338 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008339 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008340 string ZabFromKeyMintStr;
8341 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008342 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008343 &ZabFromKeyMintStr));
8344
8345 } else {
8346 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008347 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008348 }
8349
8350 CheckedDeleteKey();
8351 }
8352 }
8353}
8354
David Drysdale42fe1892021-10-14 14:43:46 +01008355/*
8356 * KeyAgreementTest.EcdhCurve25519
8357 *
8358 * Verifies that ECDH works for curve25519. This is also covered by the general
8359 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8360 * KeyMint 1.0.
8361 */
8362TEST_P(KeyAgreementTest, EcdhCurve25519) {
8363 if (!Curve25519Supported()) {
8364 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8365 }
8366
8367 // Generate EC key in KeyMint (only access to public key material)
8368 EcCurve curve = EcCurve::CURVE_25519;
8369 EVP_PKEY_Ptr kmPubKey = nullptr;
8370 GenerateKeyMintEcKey(curve, &kmPubKey);
8371
8372 // Generate EC key on same curve locally (with access to private key material).
8373 EVP_PKEY_Ptr privKey;
8374 vector<uint8_t> encodedPublicKey;
8375 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8376
8377 // Agree on a key between local and KeyMint and check it.
8378 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8379
8380 CheckedDeleteKey();
8381}
8382
8383/*
8384 * KeyAgreementTest.EcdhCurve25519Imported
8385 *
8386 * Verifies that ECDH works for an imported curve25519 key.
8387 */
8388TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8389 if (!Curve25519Supported()) {
8390 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8391 }
8392
8393 // Import x25519 key into KeyMint.
8394 EcCurve curve = EcCurve::CURVE_25519;
8395 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8396 .Authorization(TAG_NO_AUTH_REQUIRED)
8397 .EcdsaKey(EcCurve::CURVE_25519)
8398 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8399 .SetDefaultValidity(),
8400 KeyFormat::PKCS8, x25519_pkcs8_key));
8401 ASSERT_GT(cert_chain_.size(), 0);
8402 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8403 ASSERT_NE(kmKeyCert, nullptr);
8404 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8405 ASSERT_NE(kmPubKey.get(), nullptr);
8406
8407 // Expect the import to emit corresponding public key data.
8408 size_t kmPubKeySize = 32;
8409 uint8_t kmPubKeyData[32];
8410 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8411 ASSERT_EQ(kmPubKeySize, 32);
8412 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8413 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8414
8415 // Generate EC key on same curve locally (with access to private key material).
8416 EVP_PKEY_Ptr privKey;
8417 vector<uint8_t> encodedPublicKey;
8418 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8419
8420 // Agree on a key between local and KeyMint and check it.
8421 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8422
8423 CheckedDeleteKey();
8424}
8425
8426/*
8427 * KeyAgreementTest.EcdhCurve25519InvalidSize
8428 *
8429 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8430 */
8431TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8432 if (!Curve25519Supported()) {
8433 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8434 }
8435
8436 // Generate EC key in KeyMint (only access to public key material)
8437 EcCurve curve = EcCurve::CURVE_25519;
8438 EVP_PKEY_Ptr kmPubKey = nullptr;
8439 GenerateKeyMintEcKey(curve, &kmPubKey);
8440
8441 // Generate EC key on same curve locally (with access to private key material).
8442 EVP_PKEY_Ptr privKey;
8443 vector<uint8_t> encodedPublicKey;
8444 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8445
8446 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8447 string ZabFromKeyMintStr;
8448 // Send in an incomplete public key.
8449 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8450 &ZabFromKeyMintStr));
8451
8452 CheckedDeleteKey();
8453}
8454
8455/*
8456 * KeyAgreementTest.EcdhCurve25519Mismatch
8457 *
8458 * Verifies that ECDH fails between curve25519 and other curves.
8459 */
8460TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8461 if (!Curve25519Supported()) {
8462 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8463 }
8464
8465 // Generate EC key in KeyMint (only access to public key material)
8466 EcCurve curve = EcCurve::CURVE_25519;
8467 EVP_PKEY_Ptr kmPubKey = nullptr;
8468 GenerateKeyMintEcKey(curve, &kmPubKey);
8469
8470 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008471 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008472 if (localCurve == curve) {
8473 continue;
8474 }
8475 // Generate EC key on a different curve locally (with access to private key material).
8476 EVP_PKEY_Ptr privKey;
8477 vector<uint8_t> encodedPublicKey;
8478 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8479
David Drysdale7fc26b92022-05-13 09:54:24 +01008480 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008481 string ZabFromKeyMintStr;
8482 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8483 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8484 &ZabFromKeyMintStr));
8485 }
8486
8487 CheckedDeleteKey();
8488}
8489
David Zeuthene0c40892021-01-08 12:54:11 -05008490INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8491
David Drysdaled2cc8c22021-04-15 13:29:45 +01008492using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8493
8494// This is a problematic test, as it can render the device under test permanently unusable.
8495// Re-enable and run at your own risk.
8496TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8497 auto result = DestroyAttestationIds();
8498 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8499}
8500
8501INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8502
Shawn Willdend659c7c2021-02-19 14:51:51 -07008503using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008504
David Drysdaledb0dcf52021-05-18 11:43:31 +01008505/*
8506 * EarlyBootKeyTest.CreateEarlyBootKeys
8507 *
8508 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8509 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008510TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008511 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008512 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8513 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8514
David Drysdaleadfe6112021-05-27 12:00:53 +01008515 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8516 ASSERT_GT(keyData.blob.size(), 0U);
8517 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8518 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8519 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008520 CheckedDeleteKey(&aesKeyData.blob);
8521 CheckedDeleteKey(&hmacKeyData.blob);
8522 CheckedDeleteKey(&rsaKeyData.blob);
8523 CheckedDeleteKey(&ecdsaKeyData.blob);
8524}
8525
David Drysdaledb0dcf52021-05-18 11:43:31 +01008526/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008527 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8528 *
8529 * Verifies that creating an early boot key with attestation succeeds.
8530 */
8531TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8532 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8533 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8534 builder->AttestationChallenge("challenge");
8535 builder->AttestationApplicationId("app_id");
8536 });
8537
8538 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008539 // Strongbox may not support factory attestation. Key creation might fail with
8540 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8541 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8542 continue;
8543 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008544 ASSERT_GT(keyData.blob.size(), 0U);
8545 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8546 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8547 }
8548 CheckedDeleteKey(&aesKeyData.blob);
8549 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00008550 if (rsaKeyData.blob.size() != 0U) {
8551 CheckedDeleteKey(&rsaKeyData.blob);
8552 }
8553 if (ecdsaKeyData.blob.size() != 0U) {
8554 CheckedDeleteKey(&ecdsaKeyData.blob);
8555 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008556}
8557
8558/*
8559 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008560 *
8561 * Verifies that using early boot keys at a later stage fails.
8562 */
8563TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8564 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8565 .Authorization(TAG_NO_AUTH_REQUIRED)
8566 .Authorization(TAG_EARLY_BOOT_ONLY)
8567 .HmacKey(128)
8568 .Digest(Digest::SHA_2_256)
8569 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8570 AuthorizationSet output_params;
8571 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8572 AuthorizationSetBuilder()
8573 .Digest(Digest::SHA_2_256)
8574 .Authorization(TAG_MAC_LENGTH, 256),
8575 &output_params));
8576}
8577
8578/*
8579 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8580 *
8581 * Verifies that importing early boot keys fails.
8582 */
8583TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8584 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8585 .Authorization(TAG_NO_AUTH_REQUIRED)
8586 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008587 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008588 .Digest(Digest::SHA_2_256)
8589 .SetDefaultValidity(),
8590 KeyFormat::PKCS8, ec_256_key));
8591}
8592
David Drysdaled2cc8c22021-04-15 13:29:45 +01008593// 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 +00008594// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8595// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8596// early boot, so you'll have to reboot between runs.
8597TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8598 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8599 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8600 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8601 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8602 EXPECT_TRUE(
8603 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8604 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8605 EXPECT_TRUE(
8606 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8607
8608 // Should be able to use keys, since early boot has not ended
8609 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8610 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8611 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8612 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8613
8614 // End early boot
8615 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8616 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8617
8618 // Should not be able to use already-created keys.
8619 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8620 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8621 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8622 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8623
8624 CheckedDeleteKey(&aesKeyData.blob);
8625 CheckedDeleteKey(&hmacKeyData.blob);
8626 CheckedDeleteKey(&rsaKeyData.blob);
8627 CheckedDeleteKey(&ecdsaKeyData.blob);
8628
8629 // Should not be able to create new keys
8630 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
8631 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
8632
8633 CheckedDeleteKey(&aesKeyData.blob);
8634 CheckedDeleteKey(&hmacKeyData.blob);
8635 CheckedDeleteKey(&rsaKeyData.blob);
8636 CheckedDeleteKey(&ecdsaKeyData.blob);
8637}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008638
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008639INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8640
Shawn Willdend659c7c2021-02-19 14:51:51 -07008641using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008642
8643// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8644// between runs... and on most test devices there are no enrolled credentials so it can't be
8645// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8646// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8647// a manual test process, which includes unlocking between runs, which is why it's included here.
8648// Well, that and the fact that it's the only test we can do without also making calls into the
8649// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8650// implications might be, so that may or may not be a solution.
8651TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8652 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8653 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
8654
8655 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8656 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8657 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8658 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8659
8660 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008661 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008662 ASSERT_EQ(ErrorCode::OK, rc);
8663 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8664 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8665 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8666 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8667
8668 CheckedDeleteKey(&aesKeyData.blob);
8669 CheckedDeleteKey(&hmacKeyData.blob);
8670 CheckedDeleteKey(&rsaKeyData.blob);
8671 CheckedDeleteKey(&ecdsaKeyData.blob);
8672}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008673
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008674INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8675
Shawn Willden22fb9c12022-06-02 14:04:33 -06008676using VsrRequirementTest = KeyMintAidlTestBase;
8677
8678TEST_P(VsrRequirementTest, Vsr13Test) {
8679 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008680 if (vsr_api_level < __ANDROID_API_T__) {
Shawn Willden22fb9c12022-06-02 14:04:33 -06008681 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8682 }
8683 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8684}
8685
Eran Messerib9346f52022-12-15 14:58:34 +00008686TEST_P(VsrRequirementTest, Vsr14Test) {
8687 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008688 if (vsr_api_level < __ANDROID_API_U__) {
Eran Messerib9346f52022-12-15 14:58:34 +00008689 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8690 }
8691 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8692}
8693
Shawn Willden22fb9c12022-06-02 14:04:33 -06008694INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8695
Janis Danisevskis24c04702020-12-16 18:28:39 -08008696} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008697
8698int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008699 std::cout << "Testing ";
8700 auto halInstances =
8701 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8702 std::cout << "HAL instances:\n";
8703 for (auto& entry : halInstances) {
8704 std::cout << " " << entry << '\n';
8705 }
8706
Selene Huang31ab4042020-04-29 04:22:39 -07008707 ::testing::InitGoogleTest(&argc, argv);
8708 for (int i = 1; i < argc; ++i) {
8709 if (argv[i][0] == '-') {
8710 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008711 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8712 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008713 }
8714 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008715 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8716 dump_Attestations = true;
8717 } else {
8718 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008719 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008720 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8721 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8722 // be run in emulated environments that don't have the normal bootloader
8723 // interactions.
8724 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8725 }
David Drysdale9f5c0c52022-11-03 15:10:16 +00008726 if (std::string(argv[i]) == "--keyblob_dir") {
8727 if (i + 1 >= argc) {
8728 std::cerr << "Missing argument for --keyblob_dir\n";
8729 return 1;
8730 }
8731 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::keyblob_dir =
8732 std::string(argv[i + 1]);
8733 ++i;
8734 }
Selene Huang31ab4042020-04-29 04:22:39 -07008735 }
8736 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008737 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008738}