blob: 3bcdd8f7dc87c61140dd4f4b56af6c09442635af [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>
David Drysdale6c9bdb82024-01-23 09:32:04 +000024#include <map>
Selene Huang31ab4042020-04-29 04:22:39 -070025
David Drysdale42fe1892021-10-14 14:43:46 +010026#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050027#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070028#include <openssl/evp.h>
29#include <openssl/mem.h>
David Drysdalead785f52023-03-27 19:53:01 +010030#include <openssl/x509.h>
David Zeuthene0c40892021-01-08 12:54:11 -050031#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070032
33#include <cutils/properties.h>
34
David Drysdale4dc01072021-04-01 12:17:35 +010035#include <android/binder_manager.h>
36
37#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080038#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070039
Shawn Willden08a7e432020-12-11 13:05:27 +000040#include <keymint_support/key_param_output.h>
41#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070042
43#include "KeyMintAidlTestBase.h"
44
Janis Danisevskis24c04702020-12-16 18:28:39 -080045using aidl::android::hardware::security::keymint::AuthorizationSet;
46using aidl::android::hardware::security::keymint::KeyCharacteristics;
47using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070048
Selene Huang31ab4042020-04-29 04:22:39 -070049namespace std {
50
Janis Danisevskis24c04702020-12-16 18:28:39 -080051using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070052
53template <>
54struct std::equal_to<KeyCharacteristics> {
55 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070056 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070057
Shawn Willden7f424372021-01-10 18:06:50 -070058 // this isn't very efficient. Oh, well.
59 AuthorizationSet a_auths(a.authorizations);
60 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070061
Shawn Willden7f424372021-01-10 18:06:50 -070062 a_auths.Sort();
63 b_auths.Sort();
64
65 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070066 }
67};
68
69} // namespace std
70
Janis Danisevskis24c04702020-12-16 18:28:39 -080071namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000072
Selene Huang31ab4042020-04-29 04:22:39 -070073namespace {
74
David Drysdalefeab5d92022-01-06 15:46:23 +000075// Maximum supported Ed25519 message size.
76const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
77
David Drysdaledbbbe2e2021-12-02 07:44:23 +000078// Whether to check that BOOT_PATCHLEVEL is populated.
79bool check_boot_pl = true;
80
Seth Moore7a55ae32021-06-23 14:28:11 -070081// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000082// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070083// is a small (roughly 1/256) chance that corrupting ciphertext still results
84// in valid PKCS7 padding.
85constexpr size_t kMaxPaddingCorruptionRetries = 8;
86
Selene Huang31ab4042020-04-29 04:22:39 -070087template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000088bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
89 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070090 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080091 if (auto p = authorizationValue(ttag, param)) {
92 return *p == expected_value;
93 }
94 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070095 });
96 return (it != set.end());
97}
98
99template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000100bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -0700101 auto it = std::find_if(set.begin(), set.end(),
102 [&](const KeyParameter& param) { return param.tag == tag; });
103 return (it != set.end());
104}
105
106constexpr char hex_value[256] = {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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
109 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
110 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
112 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
122
123string hex2str(string a) {
124 string b;
125 size_t num = a.size() / 2;
126 b.resize(num);
127 for (size_t i = 0; i < num; i++) {
128 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
129 }
130 return b;
131}
132
David Drysdaled2cc8c22021-04-15 13:29:45 +0100133string rsa_key = hex2str(
134 // RFC 5208 s5
135 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
136 "020100" // INTEGER length 1 value 0x00 (version)
137 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
138 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
139 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
140 "0500" // NULL (parameters)
141 // } end SEQUENCE (AlgorithmIdentifier)
142 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
143 // RFC 8017 A.1.2
144 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
145 "020100" // INTEGER length 1 value 0x00 (version)
146 "028181" // INTEGER length 0x81 value (modulus) ...
147 "00c6095409047d8634812d5a218176e4"
148 "5c41d60a75b13901f234226cffe77652"
149 "1c5a77b9e389417b71c0b6a44d13afe4"
150 "e4a2805d46c9da2935adb1ff0c1f24ea"
151 "06e62b20d776430a4d435157233c6f91"
152 "6783c30e310fcbd89b85c2d567711697"
153 "85ac12bca244abda72bfb19fc44d27c8"
154 "1e1d92de284f4061edfd99280745ea6d"
155 "25"
156 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
157 "028180" // INTEGER length 0x80 (privateExponent) value...
158 "1be0f04d9cae3718691f035338308e91"
159 "564b55899ffb5084d2460e6630257e05"
160 "b3ceab02972dfabcd6ce5f6ee2589eb6"
161 "7911ed0fac16e43a444b8c861e544a05"
162 "93365772f8baf6b22fc9e3c5f1024b06"
163 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
164 "ace7240290bef16c0b3f7f3cdd64ce3a"
165 "b5912cf6e32f39ab188358afcccd8081"
166 "0241" // INTEGER length 0x41 (prime1)
167 "00e4b49ef50f765d3b24dde01aceaaf1"
168 "30f2c76670a91a61ae08af497b4a82be"
169 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
170 "8c92bfab137fba2285227b83c342ff7c"
171 "55"
172 "0241" // INTEGER length 0x41 (prime2)
173 "00ddabb5839c4c7f6bf3d4183231f005"
174 "b31aa58affdda5c79e4cce217f6bc930"
175 "dbe563d480706c24e9ebfcab28a6cdef"
176 "d324b77e1bf7251b709092c24ff501fd"
177 "91"
178 "0240" // INTEGER length 0x40 (exponent1)
179 "23d4340eda3445d8cd26c14411da6fdc"
180 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
181 "842c1d280405bc2f6c1bea214a1d742a"
182 "b996b35b63a82a5e470fa88dbf823cdd"
183 "0240" // INTEGER length 0x40 (exponent2)
184 "1b7b57449ad30d1518249a5f56bb9829"
185 "4d4b6ac12ffc86940497a5a5837a6cf9"
186 "46262b494526d328c11e1126380fde04"
187 "c24f916dec250892db09a6d77cdba351"
188 "0240" // INTEGER length 0x40 (coefficient)
189 "7762cd8f4d050da56bd591adb515d24d"
190 "7ccd32cca0d05f866d583514bd7324d5"
191 "f33645e8ed8b4a1cb3cc4a1d67987399"
192 "f2a09f5b3fb68c88d5e5d90ac33492d6"
193 // } end SEQUENCE (PrivateKey)
194 // } end SEQUENCE (PrivateKeyInfo)
195);
Selene Huang31ab4042020-04-29 04:22:39 -0700196
Selene Huange5727e62021-04-13 22:41:20 -0700197/*
198 * DER-encoded PKCS#8 format RSA key. Generated using:
199 *
200 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
201 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100202string rsa_2048_key = hex2str(
203 // RFC 5208 s5
204 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
205 "020100" // INTEGER length 1 value 0x00 (version)
206 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
207 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
208 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
209 "0500" // NULL (parameters)
210 // } end SEQUENCE (AlgorithmIdentifier)
211 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
212 // RFC 8017 A.1.2
213 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
214 "020100" // INTEGER length 1 value 0x00 (version)
215 "02820101" // INTEGER length 0x101 value (modulus) ...
216 "00BEBC342B56D443B1299F9A6A7056E8"
217 "0A897E318476A5A18029E63B2ED739A6"
218 "1791D339F58DC763D9D14911F2EDEC38"
219 "3DEE11F6319B44510E7A3ECD9B79B973"
220 "82E49500ACF8117DC89CAF0E621F7775"
221 "6554A2FD4664BFE7AB8B59AB48340DBF"
222 "A27B93B5A81F6ECDEB02D0759307128D"
223 "F3E3BAD4055C8B840216DFAA5700670E"
224 "6C5126F0962FCB70FF308F25049164CC"
225 "F76CC2DA66A7DD9A81A714C2809D6918"
226 "6133D29D84568E892B6FFBF3199BDB14"
227 "383EE224407F190358F111A949552ABA"
228 "6714227D1BD7F6B20DD0CB88F9467B71"
229 "9339F33BFF35B3870B3F62204E4286B0"
230 "948EA348B524544B5F9838F29EE643B0"
231 "79EEF8A713B220D7806924CDF7295070"
232 "C5"
233 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
234 "02820100" // INTEGER length 0x100 (privateExponent) value...
235 "69F377F35F2F584EF075353CCD1CA997"
236 "38DB3DBC7C7FF35F9366CE176DFD1B13"
237 "5AB10030344ABF5FBECF1D4659FDEF1C"
238 "0FC430834BE1BE3911951377BB3D563A"
239 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
240 "2686C7B4B3C09A7B8354133E6F93F790"
241 "D59EAEB92E84C9A4339302CCE28FDF04"
242 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
243 "6AB706645BF074A4E4090D06FB163124"
244 "365FD5EE7A20D350E9958CC30D91326E"
245 "1B292E9EF5DB408EC42DAF737D201497"
246 "04D0A678A0FB5B5446863B099228A352"
247 "D604BA8091A164D01D5AB05397C71EAD"
248 "20BE2A08FC528FE442817809C787FEE4"
249 "AB97F97B9130D022153EDC6EB6CBE7B0"
250 "F8E3473F2E901209B5DB10F93604DB01"
251 "028181" // INTEGER length 0x81 (prime1)
252 "00E83C0998214941EA4F9293F1B77E2E"
253 "99E6CF305FAF358238E126124FEAF2EB"
254 "9724B2EA7B78E6032343821A80E55D1D"
255 "88FB12D220C3F41A56142FEC85796D19"
256 "17F1E8C774F142B67D3D6E7B7E6B4383"
257 "E94DB5929089DBB346D5BDAB40CC2D96"
258 "EE0409475E175C63BF78CFD744136740"
259 "838127EA723FF3FE7FA368C1311B4A4E"
260 "05"
261 "028181" // INTEGER length 0x81 (prime2)
262 "00D240FCC0F5D7715CDE21CB2DC86EA1"
263 "46132EA3B06F61FF2AF54BF38473F59D"
264 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
265 "B1B58C39F95E4798CCBB43E83D0119AC"
266 "F532F359CA743C85199F0286610E2009"
267 "97D7312917179AC9B67558773212EC96"
268 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
269 "94D94E066A0900B7B70E82A44FB30053"
270 "C1"
271 "028181" // INTEGER length 0x81 (exponent1)
272 "00AD15DA1CBD6A492B66851BA8C316D3"
273 "8AB700E2CFDDD926A658003513C54BAA"
274 "152B30021D667D20078F500F8AD3E7F3"
275 "945D74A891ED1A28EAD0FEEAEC8C14A8"
276 "E834CF46A13D1378C99D18940823CFDD"
277 "27EC5810D59339E0C34198AC638E09C8"
278 "7CBB1B634A9864AE9F4D5EB2D53514F6"
279 "7B4CAEC048C8AB849A02E397618F3271"
280 "35"
281 "028180" // INTEGER length 0x80 (exponent2)
282 "1FA2C1A5331880A92D8F3E281C617108"
283 "BF38244F16E352E69ED417C7153F9EC3"
284 "18F211839C643DCF8B4DD67CE2AC312E"
285 "95178D5D952F06B1BF779F4916924B70"
286 "F582A23F11304E02A5E7565AE22A35E7"
287 "4FECC8B6FDC93F92A1A37703E4CF0E63"
288 "783BD02EB716A7ECBBFA606B10B74D01"
289 "579522E7EF84D91FC522292108D902C1"
290 "028180" // INTEGER length 0x80 (coefficient)
291 "796FE3825F9DCC85DF22D58690065D93"
292 "898ACD65C087BEA8DA3A63BF4549B795"
293 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
294 "0D74F40DED8E1102C52152A31B6165F8"
295 "3A6722AECFCC35A493D7634664B888A0"
296 "8D3EB034F12EA28BFEE346E205D33482"
297 "7F778B16ED40872BD29FCB36536B6E93"
298 "FFB06778696B4A9D81BB0A9423E63DE5"
299 // } end SEQUENCE (PrivateKey)
300 // } end SEQUENCE (PrivateKeyInfo)
301);
Selene Huange5727e62021-04-13 22:41:20 -0700302
David Drysdaled2cc8c22021-04-15 13:29:45 +0100303string ec_256_key = hex2str(
304 // RFC 5208 s5
305 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
306 "020100" // INTEGER length 1 value 0 (version)
307 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
308 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
309 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
310 "0608" // OBJECT IDENTIFIER length 8 (param)
311 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
312 // } end SEQUENCE (AlgorithmIdentifier)
313 "046d" // OCTET STRING length 0x6d (privateKey) holding...
314 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
315 "020101" // INTEGER length 1 value 1 (version)
316 "0420" // OCTET STRING length 0x20 (privateKey)
317 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
318 "941eed09366bc03299986481f3a4d859"
319 "a144" // TAG [1] len 0x44 (publicKey) {
320 "03420004bf85d7720d07c25461683bc6"
321 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
322 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
323 "bcc41c6eb00083cf3376d11fd44949e0"
324 "b2183bfe"
325 // } end SEQUENCE (ECPrivateKey)
326 // } end SEQUENCE (PrivateKeyInfo)
327);
Selene Huang31ab4042020-04-29 04:22:39 -0700328
David Drysdaled2cc8c22021-04-15 13:29:45 +0100329string ec_521_key = hex2str(
330 // RFC 5208 s5
331 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
332 "020100" // INTEGER length 1 value 0 (version)
333 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
334 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
335 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
336 "0605" // OBJECT IDENTIFIER length 5 (param)
337 "2B81040023" // 1.3.132.0.35 (secp521r1)
338 // } end SEQUENCE (AlgorithmIdentifier)
339 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
340 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
341 "020101" // INTEGER length 1 value 1 (version)
342 "0442" // OCTET STRING length 0x42 (privateKey)
343 "0011458C586DB5DAA92AFAB03F4FE46A"
344 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
345 "9D18D7D08B5BCFA0E53C75B064AD51C4"
346 "49BAE0258D54B94B1E885DED08ED4FB2"
347 "5CE9"
348 "A18189" // TAG [1] len 0x89 (publicKey) {
349 "03818600040149EC11C6DF0FA122C6A9"
350 "AFD9754A4FA9513A627CA329E349535A"
351 "5629875A8ADFBE27DCB932C051986377"
352 "108D054C28C6F39B6F2C9AF81802F9F3"
353 "26B842FF2E5F3C00AB7635CFB36157FC"
354 "0882D574A10D839C1A0C049DC5E0D775"
355 "E2EE50671A208431BB45E78E70BEFE93"
356 "0DB34818EE4D5C26259F5C6B8E28A652"
357 "950F9F88D7B4B2C9D9"
358 // } end SEQUENCE (ECPrivateKey)
359 // } end SEQUENCE (PrivateKeyInfo)
360);
Selene Huang31ab4042020-04-29 04:22:39 -0700361
David Drysdaled2cc8c22021-04-15 13:29:45 +0100362string ec_256_key_rfc5915 = hex2str(
363 // RFC 5208 s5
364 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
365 "020100" // INTEGER length 1 value 0 (version)
366 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
367 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
368 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
369 "0608" // OBJECT IDENTIFIER length 8 (param)
370 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
371 // } end SEQUENCE (AlgorithmIdentifier)
372 "0479" // OCTET STRING length 0x79 (privateKey) holding...
373 // RFC 5915 s3
374 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
375 "020101" // INTEGER length 1 value 1 (version)
376 "0420" // OCTET STRING length 0x42 (privateKey)
377 "782370a8c8ce5537baadd04dcff079c8"
378 "158cfa9c67b818b38e8d21c9fa750c1d"
379 "a00a" // TAG [0] length 0xa (parameters)
380 "0608" // OBJECT IDENTIFIER length 8
381 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
382 // } end TAG [0]
383 "a144" // TAG [1] length 0x44 (publicKey) {
384 "0342" // BIT STRING length 0x42
385 "00" // no pad bits
386 "04e2cc561ee701da0ad0ef0d176bb0c9"
387 "19d42e79c393fdc1bd6c4010d85cf2cf"
388 "8e68c905464666f98dad4f01573ba810"
389 "78b3428570a439ba3229fbc026c55068"
390 "2f"
391 // } end SEQUENCE (ECPrivateKey)
392 // } end SEQUENCE (PrivateKeyInfo)
393);
Selene Huang31ab4042020-04-29 04:22:39 -0700394
David Drysdaled2cc8c22021-04-15 13:29:45 +0100395string ec_256_key_sec1 = hex2str(
396 // RFC 5208 s5
397 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
398 "020100" // INTEGER length 1 value 0 (version)
399 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
400 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
401 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
402 "0608" // OBJECT IDENTIFIER length 8 (param)
403 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
404 // } end SEQUENCE (AlgorithmIdentifier)
405 "046d" // OCTET STRING length 0x6d (privateKey) holding...
406 // SEC1-v2 C.4
407 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
408 "020101" // INTEGER length 1 value 0x01 (version)
409 "0420" // OCTET STRING length 0x20 (privateKey)
410 "782370a8c8ce5537baadd04dcff079c8"
411 "158cfa9c67b818b38e8d21c9fa750c1d"
412 "a144" // TAG [1] length 0x44 (publicKey) {
413 "0342" // BIT STRING length 0x42
414 "00" // no pad bits
415 "04e2cc561ee701da0ad0ef0d176bb0c9"
416 "19d42e79c393fdc1bd6c4010d85cf2cf"
417 "8e68c905464666f98dad4f01573ba810"
418 "78b3428570a439ba3229fbc026c55068"
419 "2f"
420 // } end TAG [1] (publicKey)
421 // } end SEQUENCE (PrivateKeyInfo)
422);
Selene Huang31ab4042020-04-29 04:22:39 -0700423
David Drysdale42fe1892021-10-14 14:43:46 +0100424/**
425 * Ed25519 key pair generated as follows:
426 * ```
427 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
428 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
429 * Generating a ED25519 private key writing new private key to
430 * 'ed25519_priv.key'
431 * -----
432 * % cat ed25519_priv.key
433 * -----BEGIN PRIVATE KEY-----
434 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
435 * -----END PRIVATE KEY-----
436 * % der2ascii -pem -i ed25519_priv.key
437 * SEQUENCE {
438 * INTEGER { 0 }
439 * SEQUENCE {
440 * # ed25519
441 * OBJECT_IDENTIFIER { 1.3.101.112 }
442 * }
443 * OCTET_STRING {
444 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
445 * }
446 * }
447 * % cat ed25519.pem
448 * -----BEGIN CERTIFICATE-----
449 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
450 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
451 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
452 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
453 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
454 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
455 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
456 * -----END CERTIFICATE-----
457 * % openssl x509 -in ed25519.pem -text -noout
458 * Certificate:
459 * Data:
460 * Version: 3 (0x2)
461 * Serial Number:
462 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
463 * Signature Algorithm: ED25519
464 * Issuer: CN = fake.ed25519.com
465 * Validity
466 * Not Before: Oct 20 08:27:42 2021 GMT
467 * Not After : Sep 20 08:27:42 2023 GMT
468 * Subject: CN = fake.ed25519.com
469 * Subject Public Key Info:
470 * Public Key Algorithm: ED25519
471 * ED25519 Public-Key:
472 * pub:
473 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
474 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
475 * 56:91
476 * X509v3 extensions:
477 * X509v3 Subject Key Identifier:
478 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
479 * X509v3 Authority Key Identifier:
480 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
481 *
482 * X509v3 Basic Constraints: critical
483 * CA:TRUE
484 * Signature Algorithm: ED25519
485 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
486 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
487 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
488 * e7:07:32:60:32:8d:bb:eb:f6:0f
489 * ```
490 */
491string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
492string ed25519_pkcs8_key = hex2str(
493 // RFC 5208 s5
494 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
495 "0201" // INTEGER length 1 (Version)
496 "00" // version 0
497 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
498 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
499 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
500 // } end SEQUENCE (AlgorithmIdentifier)
501 "0422" // OCTET STRING length 0x22 (PrivateKey)
502 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
503 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
504 // } end SEQUENCE (PrivateKeyInfo)
505);
506string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
507
508/**
509 * X25519 key pair generated as follows:
510 * ```
511 * % openssl genpkey -algorithm X25519 > x25519_priv.key
512 * % cat x25519_priv.key
513 * -----BEGIN PRIVATE KEY-----
514 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
515 * -----END PRIVATE KEY-----
516 * % der2ascii -pem -i x25519_priv.key
517 * SEQUENCE {
518 * INTEGER { 0 }
519 * SEQUENCE {
520 * # x25519
521 * OBJECT_IDENTIFIER { 1.3.101.110 }
522 * }
523 * OCTET_STRING {
524 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
525 * }
526 * }
527 * ```
528 */
529
530string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
531string x25519_pkcs8_key = hex2str(
532 // RFC 5208 s5
533 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
534 "0201" // INTEGER length 1 (Version)
535 "00" // version 0
536 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
537 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
538 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
539 "0422" // OCTET STRING length 0x22 (PrivateKey)
540 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
541 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
542string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
543
Selene Huang31ab4042020-04-29 04:22:39 -0700544struct RSA_Delete {
545 void operator()(RSA* p) { RSA_free(p); }
546};
547
Selene Huang31ab4042020-04-29 04:22:39 -0700548std::string make_string(const uint8_t* data, size_t length) {
549 return std::string(reinterpret_cast<const char*>(data), length);
550}
551
552template <size_t N>
553std::string make_string(const uint8_t (&a)[N]) {
554 return make_string(a, N);
555}
556
557class AidlBuf : public vector<uint8_t> {
558 typedef vector<uint8_t> super;
559
560 public:
561 AidlBuf() {}
562 AidlBuf(const super& other) : super(other) {}
563 AidlBuf(super&& other) : super(std::move(other)) {}
564 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
565
566 AidlBuf& operator=(const super& other) {
567 super::operator=(other);
568 return *this;
569 }
570
571 AidlBuf& operator=(super&& other) {
572 super::operator=(std::move(other));
573 return *this;
574 }
575
576 AidlBuf& operator=(const string& other) {
577 resize(other.size());
578 for (size_t i = 0; i < other.size(); ++i) {
579 (*this)[i] = static_cast<uint8_t>(other[i]);
580 }
581 return *this;
582 }
583
584 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
585};
586
David Drysdale4dc01072021-04-01 12:17:35 +0100587string device_suffix(const string& name) {
588 size_t pos = name.find('/');
589 if (pos == string::npos) {
590 return name;
591 }
592 return name.substr(pos + 1);
593}
594
Seth Moore5a0320f2023-03-24 12:29:08 -0700595std::shared_ptr<IRemotelyProvisionedComponent> matching_rp_instance(const std::string& km_name) {
David Drysdale4dc01072021-04-01 12:17:35 +0100596 string km_suffix = device_suffix(km_name);
597
598 vector<string> rp_names =
599 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
600 for (const string& rp_name : rp_names) {
601 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
602 // KeyMint instance, assume they match.
603 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
604 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
Seth Moore5a0320f2023-03-24 12:29:08 -0700605 return IRemotelyProvisionedComponent::fromBinder(binder);
David Drysdale4dc01072021-04-01 12:17:35 +0100606 }
607 }
Seth Moore5a0320f2023-03-24 12:29:08 -0700608 return nullptr;
David Drysdale4dc01072021-04-01 12:17:35 +0100609}
610
Selene Huang31ab4042020-04-29 04:22:39 -0700611} // namespace
612
613class NewKeyGenerationTest : public KeyMintAidlTestBase {
614 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700615 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000616 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
Selene Huang31ab4042020-04-29 04:22:39 -0700617 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700618
Selene Huang31ab4042020-04-29 04:22:39 -0700619 // Check that some unexpected tags/values are NOT present.
620 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
621 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000622 }
623
624 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000625 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
David Drysdale7de9feb2021-03-05 14:56:19 +0000626 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
627 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
628
629 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000630 }
631
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000632 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics,
633 const KeyOrigin expectedKeyOrigin) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000634 // TODO(swillden): Distinguish which params should be in which auth list.
635 AuthorizationSet auths;
636 for (auto& entry : keyCharacteristics) {
637 auths.push_back(AuthorizationSet(entry.authorizations));
638 }
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000639 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, expectedKeyOrigin));
David Drysdale7de9feb2021-03-05 14:56:19 +0000640
641 // Verify that App data, ROT and auth timeout are NOT included.
642 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
643 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700644 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
645
David Drysdaled2cc8c22021-04-15 13:29:45 +0100646 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
647 // never adds it.
648 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
649
David Drysdale7de9feb2021-03-05 14:56:19 +0000650 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700651 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000652 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700653 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700654 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000655 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700656 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000657
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000658 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100659 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
660 EXPECT_TRUE(vendor_pl);
661 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000662
663 // Should include boot patchlevel (but there are some test scenarios where this is not
664 // possible).
665 if (check_boot_pl) {
666 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
667 EXPECT_TRUE(boot_pl);
668 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100669
David Drysdale7de9feb2021-03-05 14:56:19 +0000670 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700671 }
672};
673
674/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000675 * NewKeyGenerationTest.Aes
676 *
677 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
678 * have correct characteristics.
679 */
680TEST_P(NewKeyGenerationTest, Aes) {
681 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
682 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
683 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
684 SCOPED_TRACE(testing::Message()
685 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
686 vector<uint8_t> key_blob;
687 vector<KeyCharacteristics> key_characteristics;
688 auto builder = AuthorizationSetBuilder()
689 .AesEncryptionKey(key_size)
690 .BlockMode(block_mode)
691 .Padding(padding_mode)
692 .SetDefaultValidity();
693 if (block_mode == BlockMode::GCM) {
694 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
695 }
696 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100697 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000698
699 EXPECT_GT(key_blob.size(), 0U);
700 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100701 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000702
703 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
704
705 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
706 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
707 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000708 }
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));
David Drysdale1b9febc2023-06-07 13:43:24 +0100880 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000881
882 EXPECT_GT(key_blob.size(), 0U);
883 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100884 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000885
886 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
887
888 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
889 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
890 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000891 }
892 }
893 }
894}
895
896/*
897 * NewKeyGenerationTest.TripleDesWithAttestation
898 *
899 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
900 * have correct characteristics.
901 *
902 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
903 * put in a certificate) but which isn't an error.
904 */
905TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
906 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
907 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
908 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
909 SCOPED_TRACE(testing::Message()
910 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
911
912 auto challenge = "hello";
913 auto app_id = "foo";
914
915 vector<uint8_t> key_blob;
916 vector<KeyCharacteristics> key_characteristics;
917 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
918 .TripleDesEncryptionKey(key_size)
919 .BlockMode(block_mode)
920 .Padding(padding_mode)
921 .Authorization(TAG_NO_AUTH_REQUIRED)
922 .AttestationChallenge(challenge)
923 .AttestationApplicationId(app_id)
924 .SetDefaultValidity(),
925 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100926 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000927
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";
David Drysdale7de9feb2021-03-05 14:56:19 +0000937 }
938 }
939 }
940}
941
942/*
943 * NewKeyGenerationTest.TripleDesInvalidSize
944 *
945 * Verifies that specifying an invalid key size for 3-DES key generation returns
946 * UNSUPPORTED_KEY_SIZE.
947 */
948TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
949 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
950 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
951 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
952 SCOPED_TRACE(testing::Message()
953 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
954 vector<uint8_t> key_blob;
955 vector<KeyCharacteristics> key_characteristics;
956 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
957 GenerateKey(AuthorizationSetBuilder()
958 .TripleDesEncryptionKey(key_size)
959 .BlockMode(block_mode)
960 .Padding(padding_mode)
961 .Authorization(TAG_NO_AUTH_REQUIRED)
962 .SetDefaultValidity(),
963 &key_blob, &key_characteristics));
964 }
965 }
966 }
967
968 // Omitting the key size fails.
969 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
970 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
971 SCOPED_TRACE(testing::Message()
972 << "3DES-default-" << block_mode << "-" << padding_mode);
973 vector<uint8_t> key_blob;
974 vector<KeyCharacteristics> key_characteristics;
975 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
976 GenerateKey(AuthorizationSetBuilder()
977 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
978 .BlockMode(block_mode)
979 .Padding(padding_mode)
980 .Authorization(TAG_NO_AUTH_REQUIRED)
981 .SetDefaultValidity(),
982 &key_blob, &key_characteristics));
983 }
984 }
985}
986
987/*
Selene Huang31ab4042020-04-29 04:22:39 -0700988 * NewKeyGenerationTest.Rsa
989 *
990 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
991 * have correct characteristics.
992 */
993TEST_P(NewKeyGenerationTest, Rsa) {
994 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100995 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -0700996 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700997 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700998 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
999 .RsaSigningKey(key_size, 65537)
1000 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001001 .Padding(PaddingMode::NONE)
1002 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001003 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001004 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07001005
1006 ASSERT_GT(key_blob.size(), 0U);
1007 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001008 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001009
Shawn Willden7f424372021-01-10 18:06:50 -07001010 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001011
1012 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1013 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1014 << "Key size " << key_size << "missing";
1015 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
Selene Huang31ab4042020-04-29 04:22:39 -07001016 }
1017}
1018
1019/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001020 * NewKeyGenerationTest.RsaWithMissingValidity
1021 *
1022 * Verifies that keymint returns an error while generating asymmetric key
1023 * without providing NOT_BEFORE and NOT_AFTER parameters.
1024 */
1025TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
Seth Moore7dc1fda2022-12-12 16:56:20 -08001026 if (AidlVersion() < 3) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001027 /*
1028 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1029 * specified for asymmetric key generation. However, this was not
1030 * checked at the time so we can only be strict about checking this for
Seth Mooreec10c482024-01-23 20:37:24 +00001031 * implementations of KeyMint version 3 and above.
Tommy Chiu7d22f602022-11-14 21:03:34 +08001032 */
Seth Mooreec10c482024-01-23 20:37:24 +00001033 GTEST_SKIP() << "Validity strict since KeyMint v3";
Tommy Chiu7d22f602022-11-14 21:03:34 +08001034 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001035 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1036 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1037 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1038
1039 vector<uint8_t> key_blob;
1040 vector<KeyCharacteristics> key_characteristics;
1041 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1042 GenerateKey(AuthorizationSetBuilder()
1043 .RsaSigningKey(2048, 65537)
1044 .Digest(Digest::NONE)
1045 .Padding(PaddingMode::NONE)
1046 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1047 kUndefinedExpirationDateTime),
1048 &key_blob, &key_characteristics));
1049
1050 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1051 GenerateKey(AuthorizationSetBuilder()
1052 .RsaSigningKey(2048, 65537)
1053 .Digest(Digest::NONE)
1054 .Padding(PaddingMode::NONE)
1055 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1056 &key_blob, &key_characteristics));
1057}
1058
1059/*
David Drysdalead785f52023-03-27 19:53:01 +01001060 * NewKeyGenerationTest.RsaWithSpecifiedValidity
1061 *
1062 * Verifies that KeyMint respects specified NOT_BEFORE and NOT_AFTER certificate dates.
1063 */
1064TEST_P(NewKeyGenerationTest, RsaWithSpecifiedValidity) {
1065 vector<uint8_t> key_blob;
1066 vector<KeyCharacteristics> key_characteristics;
Subrahmanyamane1560212023-05-09 04:40:33 +00001067 vector<uint64_t> test_vector_not_before_millis = {
1068 458046000000, /* 1984-07-07T11:00:00Z */
1069 1183806000000, /* 2007-07-07T11:00:00Z */
1070 1924991999000, /* 2030-12-31T23:59:59Z */
1071 3723753599000, /* 2087-12-31T23:59:59Z */
1072 26223868799000, /* 2800-12-31T23:59:59Z */
1073 45157996799000, /* 3400-12-31T23:59:59Z */
1074 60719587199000, /* 3894-02-15T23:59:59Z */
1075 95302051199000, /* 4989-12-31T23:59:59Z */
1076 86182012799000, /* 4700-12-31T23:59:59Z */
1077 111427574399000, /* 5500-12-31T23:59:59Z */
1078 136988668799000, /* 6310-12-31T23:59:59Z */
1079 139828895999000, /* 6400-12-31T23:59:59Z */
1080 169839503999000, /* 7351-12-31T23:59:59Z */
1081 171385804799000, /* 7400-12-31T23:59:59Z */
1082 190320019199000, /* 8000-12-31T23:59:59Z */
1083 193475692799000, /* 8100-12-31T23:59:59Z */
1084 242515209599000, /* 9654-12-31T23:59:59Z */
1085 250219065599000, /* 9899-02-15T23:59:59Z */
1086 };
1087 for (auto notBefore : test_vector_not_before_millis) {
1088 uint64_t notAfter = notBefore + 378691200000 /* 12 years milliseconds*/;
Subrahmanya Manikanta Venkateswarlu Bhamidipati Kameswara Srib66a37a2024-02-26 19:23:44 +00001089 SCOPED_TRACE(testing::Message() << "notBefore: " << notBefore << " notAfter: " << notAfter);
Subrahmanyamane1560212023-05-09 04:40:33 +00001090 ASSERT_EQ(ErrorCode::OK,
1091 GenerateKey(AuthorizationSetBuilder()
1092 .RsaSigningKey(2048, 65537)
1093 .Digest(Digest::NONE)
1094 .Padding(PaddingMode::NONE)
1095 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, notBefore)
1096 .Authorization(TAG_CERTIFICATE_NOT_AFTER, notAfter),
1097 &key_blob, &key_characteristics));
1098 ASSERT_GT(cert_chain_.size(), 0);
David Drysdalead785f52023-03-27 19:53:01 +01001099
Subrahmanyamane1560212023-05-09 04:40:33 +00001100 X509_Ptr cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1101 ASSERT_TRUE(!!cert.get());
David Drysdalead785f52023-03-27 19:53:01 +01001102
Subrahmanyamane1560212023-05-09 04:40:33 +00001103 const ASN1_TIME* not_before = X509_get0_notBefore(cert.get());
1104 ASSERT_NE(not_before, nullptr);
Subrahmanya Manikanta Venkateswarlu Bhamidipati Kameswara Srib66a37a2024-02-26 19:23:44 +00001105 int64_t not_before_time;
1106 ASSERT_EQ(ASN1_TIME_to_posix(not_before, &not_before_time), 1);
Subrahmanyamane1560212023-05-09 04:40:33 +00001107 EXPECT_EQ(not_before_time, (notBefore / 1000));
David Drysdalead785f52023-03-27 19:53:01 +01001108
Subrahmanyamane1560212023-05-09 04:40:33 +00001109 const ASN1_TIME* not_after = X509_get0_notAfter(cert.get());
1110 ASSERT_NE(not_after, nullptr);
Subrahmanya Manikanta Venkateswarlu Bhamidipati Kameswara Srib66a37a2024-02-26 19:23:44 +00001111 int64_t not_after_time;
1112 ASSERT_EQ(ASN1_TIME_to_posix(not_after, &not_after_time), 1);
Subrahmanyamane1560212023-05-09 04:40:33 +00001113 EXPECT_EQ(not_after_time, (notAfter / 1000));
1114 }
David Drysdalead785f52023-03-27 19:53:01 +01001115}
1116
1117/*
Qi Wud22ec842020-11-26 13:27:53 +08001118 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001119 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001120 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1121 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001122 */
1123TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001124 auto challenge = "hello";
1125 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001126
Selene Huang6e46f142021-04-20 19:20:11 -07001127 auto subject = "cert subj 2";
1128 vector<uint8_t> subject_der(make_name_from_str(subject));
1129
1130 uint64_t serial_int = 66;
1131 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1132
Selene Huang4f64c222021-04-13 19:54:36 -07001133 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001134 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001135 vector<uint8_t> key_blob;
1136 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001137 auto builder = AuthorizationSetBuilder()
1138 .RsaSigningKey(key_size, 65537)
1139 .Digest(Digest::NONE)
1140 .Padding(PaddingMode::NONE)
1141 .AttestationChallenge(challenge)
1142 .AttestationApplicationId(app_id)
1143 .Authorization(TAG_NO_AUTH_REQUIRED)
1144 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1145 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1146 .SetDefaultValidity();
1147
1148 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001149 // Strongbox may not support factory provisioned attestation key.
1150 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001151 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1152 result = GenerateKeyWithSelfSignedAttestKey(
1153 AuthorizationSetBuilder()
1154 .RsaKey(key_size, 65537)
1155 .AttestKey()
1156 .SetDefaultValidity(), /* attest key params */
1157 builder, &key_blob, &key_characteristics);
1158 }
subrahmanyaman05642492022-02-05 07:10:56 +00001159 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001160 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001161 KeyBlobDeleter deleter(keymint_, key_blob);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001162 ASSERT_GT(key_blob.size(), 0U);
1163 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001164 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001165
1166 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1167
1168 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1169 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1170 << "Key size " << key_size << "missing";
1171 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1172
David Drysdalea8a888e2022-06-08 12:43:56 +01001173 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001174 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001175 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001176
1177 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1178 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001179 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001180 sw_enforced, hw_enforced, SecLevel(),
1181 cert_chain_[0].encodedCertificate));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001182 }
1183}
1184
1185/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001186 * NewKeyGenerationTest.RsaWithRkpAttestation
David Drysdale4dc01072021-04-01 12:17:35 +01001187 *
Seth Moore7dc1fda2022-12-12 16:56:20 -08001188 * Verifies that keymint can generate all required RSA key sizes using an attestation key
David Drysdale4dc01072021-04-01 12:17:35 +01001189 * that has been generated using an associate IRemotelyProvisionedComponent.
1190 */
Seth Moore7dc1fda2022-12-12 16:56:20 -08001191TEST_P(NewKeyGenerationTest, RsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001192 if (!IsRkpSupportRequired()) {
1193 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001194 }
1195
Seth Moore5a0320f2023-03-24 12:29:08 -07001196 // Check for an IRemotelyProvisionedComponent instance associated with the
1197 // KeyMint instance.
1198 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1199 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1200 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1201 }
1202 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1203 << GetParam();
David Drysdale4dc01072021-04-01 12:17:35 +01001204
1205 // Generate a P-256 keypair to use as an attestation key.
1206 MacedPublicKey macedPubKey;
1207 std::vector<uint8_t> privateKeyBlob;
1208 auto status =
1209 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1210 ASSERT_TRUE(status.isOk());
1211 vector<uint8_t> coseKeyData;
1212 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1213
1214 AttestationKey attestation_key;
1215 attestation_key.keyBlob = std::move(privateKeyBlob);
1216 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1217
1218 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001219 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdale4dc01072021-04-01 12:17:35 +01001220 auto challenge = "hello";
1221 auto app_id = "foo";
1222
1223 vector<uint8_t> key_blob;
1224 vector<KeyCharacteristics> key_characteristics;
1225 ASSERT_EQ(ErrorCode::OK,
1226 GenerateKey(AuthorizationSetBuilder()
1227 .RsaSigningKey(key_size, 65537)
1228 .Digest(Digest::NONE)
1229 .Padding(PaddingMode::NONE)
1230 .AttestationChallenge(challenge)
1231 .AttestationApplicationId(app_id)
1232 .Authorization(TAG_NO_AUTH_REQUIRED)
1233 .SetDefaultValidity(),
1234 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
David Drysdale1b9febc2023-06-07 13:43:24 +01001235 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale4dc01072021-04-01 12:17:35 +01001236
1237 ASSERT_GT(key_blob.size(), 0U);
1238 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001239 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001240
1241 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1242
1243 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1244 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1245 << "Key size " << key_size << "missing";
1246 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1247
1248 // Attestation by itself is not valid (last entry is not self-signed).
1249 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1250
1251 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001252 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001253 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1254 ASSERT_TRUE(key_cert.get());
1255 EVP_PKEY_Ptr signing_pubkey;
1256 p256_pub_key(coseKeyData, &signing_pubkey);
1257 ASSERT_TRUE(signing_pubkey.get());
1258
1259 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1260 << "Verification of attested certificate failed "
1261 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
David Drysdale4dc01072021-04-01 12:17:35 +01001262 }
1263}
1264
1265/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001266 * NewKeyGenerationTest.EcdsaWithRkpAttestation
1267 *
1268 * Verifies that keymint can generate all required ECDSA key sizes using an attestation key
1269 * that has been generated using an associate IRemotelyProvisionedComponent.
1270 */
1271TEST_P(NewKeyGenerationTest, EcdsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001272 if (!IsRkpSupportRequired()) {
1273 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001274 }
1275
Seth Moore5a0320f2023-03-24 12:29:08 -07001276 // Check for an IRemotelyProvisionedComponent instance associated with the
1277 // KeyMint instance.
1278 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1279 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1280 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1281 }
1282 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1283 << GetParam();
Seth Moore7dc1fda2022-12-12 16:56:20 -08001284
1285 // Generate a P-256 keypair to use as an attestation key.
1286 MacedPublicKey macedPubKey;
1287 std::vector<uint8_t> privateKeyBlob;
1288 auto status =
1289 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1290 ASSERT_TRUE(status.isOk());
1291 vector<uint8_t> coseKeyData;
1292 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1293
1294 AttestationKey attestation_key;
1295 attestation_key.keyBlob = std::move(privateKeyBlob);
1296 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1297
1298 for (auto curve : ValidCurves()) {
1299 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
1300 auto challenge = "hello";
1301 auto app_id = "foo";
1302
1303 vector<uint8_t> key_blob;
1304 vector<KeyCharacteristics> key_characteristics;
1305 ASSERT_EQ(ErrorCode::OK,
1306 GenerateKey(AuthorizationSetBuilder()
1307 .EcdsaSigningKey(curve)
1308 .Digest(Digest::NONE)
1309 .AttestationChallenge(challenge)
1310 .AttestationApplicationId(app_id)
1311 .Authorization(TAG_NO_AUTH_REQUIRED)
1312 .SetDefaultValidity(),
1313 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
David Drysdale1b9febc2023-06-07 13:43:24 +01001314 KeyBlobDeleter deleter(keymint_, key_blob);
Seth Moore7dc1fda2022-12-12 16:56:20 -08001315
1316 ASSERT_GT(key_blob.size(), 0U);
1317 CheckBaseParams(key_characteristics);
1318 CheckCharacteristics(key_blob, key_characteristics);
1319
1320 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1321
1322 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1323 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1324
1325 // Attestation by itself is not valid (last entry is not self-signed).
1326 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1327
1328 // The signature over the attested key should correspond to the P256 public key.
1329 ASSERT_GT(cert_chain_.size(), 0);
1330 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1331 ASSERT_TRUE(key_cert.get());
1332 EVP_PKEY_Ptr signing_pubkey;
1333 p256_pub_key(coseKeyData, &signing_pubkey);
1334 ASSERT_TRUE(signing_pubkey.get());
1335
1336 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1337 << "Verification of attested certificate failed "
1338 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Seth Moore7dc1fda2022-12-12 16:56:20 -08001339 }
1340}
1341
1342/*
Selene Huang4f64c222021-04-13 19:54:36 -07001343 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1344 *
1345 * Verifies that keymint attestation for RSA encryption keys with challenge and
1346 * app id is also successful.
1347 */
1348TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1349 auto key_size = 2048;
1350 auto challenge = "hello";
1351 auto app_id = "foo";
1352
Selene Huang6e46f142021-04-20 19:20:11 -07001353 auto subject = "subj 2";
1354 vector<uint8_t> subject_der(make_name_from_str(subject));
1355
1356 uint64_t serial_int = 111166;
1357 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1358
Selene Huang4f64c222021-04-13 19:54:36 -07001359 vector<uint8_t> key_blob;
1360 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001361 auto builder = AuthorizationSetBuilder()
1362 .RsaEncryptionKey(key_size, 65537)
1363 .Padding(PaddingMode::NONE)
1364 .AttestationChallenge(challenge)
1365 .AttestationApplicationId(app_id)
1366 .Authorization(TAG_NO_AUTH_REQUIRED)
1367 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1368 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1369 .SetDefaultValidity();
1370
1371 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001372 // Strongbox may not support factory provisioned attestation key.
1373 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001374 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1375 result = GenerateKeyWithSelfSignedAttestKey(
1376 AuthorizationSetBuilder()
1377 .RsaKey(key_size, 65537)
1378 .AttestKey()
1379 .SetDefaultValidity(), /* attest key params */
1380 builder, &key_blob, &key_characteristics);
1381 }
subrahmanyaman05642492022-02-05 07:10:56 +00001382 }
1383 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001384 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001385
1386 ASSERT_GT(key_blob.size(), 0U);
1387 AuthorizationSet auths;
1388 for (auto& entry : key_characteristics) {
1389 auths.push_back(AuthorizationSet(entry.authorizations));
1390 }
1391
1392 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1393 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1394
1395 // Verify that App data and ROT are NOT included.
1396 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1397 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1398
1399 // Check that some unexpected tags/values are NOT present.
1400 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1401 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1402
1403 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1404
1405 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1406 ASSERT_TRUE(os_ver);
1407 EXPECT_EQ(*os_ver, os_version());
1408
1409 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1410
1411 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1412 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1413 << "Key size " << key_size << "missing";
1414 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1415
David Drysdalea8a888e2022-06-08 12:43:56 +01001416 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001417 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001418 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001419
1420 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1421 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001422 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001423 sw_enforced, hw_enforced, SecLevel(),
1424 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07001425}
1426
1427/*
1428 * NewKeyGenerationTest.RsaWithSelfSign
1429 *
1430 * Verifies that attesting to RSA key generation is successful, and returns
1431 * self signed certificate if no challenge is provided. And signing etc
1432 * works as expected.
1433 */
1434TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001435 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1436 vector<uint8_t> subject_der(make_name_from_str(subject));
1437
1438 uint64_t serial_int = 0;
1439 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1440
Selene Huang4f64c222021-04-13 19:54:36 -07001441 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001442 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang4f64c222021-04-13 19:54:36 -07001443 vector<uint8_t> key_blob;
1444 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001445 ASSERT_EQ(ErrorCode::OK,
1446 GenerateKey(AuthorizationSetBuilder()
1447 .RsaSigningKey(key_size, 65537)
1448 .Digest(Digest::NONE)
1449 .Padding(PaddingMode::NONE)
1450 .Authorization(TAG_NO_AUTH_REQUIRED)
1451 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1452 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1453 .SetDefaultValidity(),
1454 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001455 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001456
1457 ASSERT_GT(key_blob.size(), 0U);
1458 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001459 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001460
1461 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1462
1463 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1464 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1465 << "Key size " << key_size << "missing";
1466 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1467
David Drysdalea8a888e2022-06-08 12:43:56 +01001468 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001469 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001470 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001471 }
1472}
1473
1474/*
1475 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1476 *
1477 * Verifies that attesting to RSA checks for missing app ID.
1478 */
1479TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1480 auto challenge = "hello";
1481 vector<uint8_t> key_blob;
1482 vector<KeyCharacteristics> key_characteristics;
1483
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001484 auto builder = AuthorizationSetBuilder()
1485 .RsaSigningKey(2048, 65537)
1486 .Digest(Digest::NONE)
1487 .Padding(PaddingMode::NONE)
1488 .AttestationChallenge(challenge)
1489 .Authorization(TAG_NO_AUTH_REQUIRED)
1490 .SetDefaultValidity();
1491
1492 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001493 // Strongbox may not support factory provisioned attestation key.
1494 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001495 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1496 result = GenerateKeyWithSelfSignedAttestKey(
1497 AuthorizationSetBuilder()
1498 .RsaKey(2048, 65537)
1499 .AttestKey()
1500 .SetDefaultValidity(), /* attest key params */
1501 builder, &key_blob, &key_characteristics);
1502 }
subrahmanyaman05642492022-02-05 07:10:56 +00001503 }
1504 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001505}
1506
1507/*
1508 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1509 *
1510 * Verifies that attesting to RSA ignores app id if challenge is missing.
1511 */
1512TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1513 auto key_size = 2048;
1514 auto app_id = "foo";
1515
Selene Huang6e46f142021-04-20 19:20:11 -07001516 auto subject = "cert subj 2";
1517 vector<uint8_t> subject_der(make_name_from_str(subject));
1518
1519 uint64_t serial_int = 1;
1520 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1521
Selene Huang4f64c222021-04-13 19:54:36 -07001522 vector<uint8_t> key_blob;
1523 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001524 ASSERT_EQ(ErrorCode::OK,
1525 GenerateKey(AuthorizationSetBuilder()
1526 .RsaSigningKey(key_size, 65537)
1527 .Digest(Digest::NONE)
1528 .Padding(PaddingMode::NONE)
1529 .AttestationApplicationId(app_id)
1530 .Authorization(TAG_NO_AUTH_REQUIRED)
1531 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1532 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1533 .SetDefaultValidity(),
1534 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001535 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001536
1537 ASSERT_GT(key_blob.size(), 0U);
1538 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001539 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001540
1541 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1542
1543 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1544 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1545 << "Key size " << key_size << "missing";
1546 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1547
David Drysdalea8a888e2022-06-08 12:43:56 +01001548 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001549 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001550 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1551 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang4f64c222021-04-13 19:54:36 -07001552}
1553
1554/*
Qi Wud22ec842020-11-26 13:27:53 +08001555 * NewKeyGenerationTest.LimitedUsageRsa
1556 *
1557 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1558 * resulting keys have correct characteristics.
1559 */
1560TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1561 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001562 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wud22ec842020-11-26 13:27:53 +08001563 vector<uint8_t> key_blob;
1564 vector<KeyCharacteristics> key_characteristics;
1565 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1566 .RsaSigningKey(key_size, 65537)
1567 .Digest(Digest::NONE)
1568 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001569 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1570 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001571 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001572 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08001573
1574 ASSERT_GT(key_blob.size(), 0U);
1575 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001576 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001577
1578 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1579
1580 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1581 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1582 << "Key size " << key_size << "missing";
1583 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1584
1585 // Check the usage count limit tag appears in the authorizations.
1586 AuthorizationSet auths;
1587 for (auto& entry : key_characteristics) {
1588 auths.push_back(AuthorizationSet(entry.authorizations));
1589 }
1590 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1591 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08001592 }
1593}
1594
1595/*
Qi Wubeefae42021-01-28 23:16:37 +08001596 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1597 *
1598 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1599 * resulting keys have correct characteristics and attestation.
1600 */
1601TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001602 auto challenge = "hello";
1603 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001604
Selene Huang6e46f142021-04-20 19:20:11 -07001605 auto subject = "cert subj 2";
1606 vector<uint8_t> subject_der(make_name_from_str(subject));
1607
1608 uint64_t serial_int = 66;
1609 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1610
Selene Huang4f64c222021-04-13 19:54:36 -07001611 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001612 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wubeefae42021-01-28 23:16:37 +08001613 vector<uint8_t> key_blob;
1614 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001615 auto builder = AuthorizationSetBuilder()
1616 .RsaSigningKey(key_size, 65537)
1617 .Digest(Digest::NONE)
1618 .Padding(PaddingMode::NONE)
1619 .AttestationChallenge(challenge)
1620 .AttestationApplicationId(app_id)
1621 .Authorization(TAG_NO_AUTH_REQUIRED)
1622 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1623 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1624 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1625 .SetDefaultValidity();
1626
1627 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001628 // Strongbox may not support factory provisioned attestation key.
1629 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001630 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1631 result = GenerateKeyWithSelfSignedAttestKey(
1632 AuthorizationSetBuilder()
1633 .RsaKey(key_size, 65537)
1634 .AttestKey()
1635 .SetDefaultValidity(), /* attest key params */
1636 builder, &key_blob, &key_characteristics);
1637 }
subrahmanyaman05642492022-02-05 07:10:56 +00001638 }
1639 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001640 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wubeefae42021-01-28 23:16:37 +08001641
1642 ASSERT_GT(key_blob.size(), 0U);
1643 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001644 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001645
1646 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1647
1648 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1649 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1650 << "Key size " << key_size << "missing";
1651 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1652
1653 // Check the usage count limit tag appears in the authorizations.
1654 AuthorizationSet auths;
1655 for (auto& entry : key_characteristics) {
1656 auths.push_back(AuthorizationSet(entry.authorizations));
1657 }
1658 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1659 << "key usage count limit " << 1U << " missing";
1660
1661 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001662 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001663 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001664 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001665
1666 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1667 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001668 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001669 sw_enforced, hw_enforced, SecLevel(),
1670 cert_chain_[0].encodedCertificate));
Qi Wubeefae42021-01-28 23:16:37 +08001671 }
1672}
1673
1674/*
Selene Huang31ab4042020-04-29 04:22:39 -07001675 * NewKeyGenerationTest.NoInvalidRsaSizes
1676 *
1677 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1678 */
1679TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1680 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001681 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07001682 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001683 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001684 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1685 GenerateKey(AuthorizationSetBuilder()
1686 .RsaSigningKey(key_size, 65537)
1687 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001688 .Padding(PaddingMode::NONE)
1689 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001690 &key_blob, &key_characteristics));
1691 }
1692}
1693
1694/*
1695 * NewKeyGenerationTest.RsaNoDefaultSize
1696 *
1697 * Verifies that failing to specify a key size for RSA key generation returns
1698 * UNSUPPORTED_KEY_SIZE.
1699 */
1700TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1701 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1702 GenerateKey(AuthorizationSetBuilder()
1703 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1704 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001705 .SigningKey()
1706 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001707}
1708
1709/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001710 * NewKeyGenerationTest.RsaMissingParams
1711 *
1712 * Verifies that omitting optional tags works.
1713 */
1714TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1715 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001716 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdaled2cc8c22021-04-15 13:29:45 +01001717 ASSERT_EQ(ErrorCode::OK,
1718 GenerateKey(
1719 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1720 CheckedDeleteKey();
1721 }
1722}
1723
1724/*
Selene Huang31ab4042020-04-29 04:22:39 -07001725 * NewKeyGenerationTest.Ecdsa
1726 *
David Drysdale42fe1892021-10-14 14:43:46 +01001727 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001728 * have correct characteristics.
1729 */
1730TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001731 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001732 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07001733 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001734 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001735 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001736 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001737 .Digest(Digest::NONE)
1738 .SetDefaultValidity(),
1739 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001740 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07001741 ASSERT_GT(key_blob.size(), 0U);
1742 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001743 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001744
Shawn Willden7f424372021-01-10 18:06:50 -07001745 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001746
1747 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001748 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001749 }
1750}
1751
1752/*
David Drysdale42fe1892021-10-14 14:43:46 +01001753 * NewKeyGenerationTest.EcdsaCurve25519
1754 *
1755 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1756 * has correct characteristics.
1757 */
1758TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1759 if (!Curve25519Supported()) {
1760 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1761 }
1762
1763 EcCurve curve = EcCurve::CURVE_25519;
1764 vector<uint8_t> key_blob;
1765 vector<KeyCharacteristics> key_characteristics;
1766 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1767 .EcdsaSigningKey(curve)
1768 .Digest(Digest::NONE)
1769 .SetDefaultValidity(),
1770 &key_blob, &key_characteristics);
1771 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01001772 KeyBlobDeleter deleter(keymint_, key_blob);
1773
David Drysdale42fe1892021-10-14 14:43:46 +01001774 ASSERT_GT(key_blob.size(), 0U);
1775
1776 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1777 ASSERT_GT(cert_chain_.size(), 0);
1778
1779 CheckBaseParams(key_characteristics);
1780 CheckCharacteristics(key_blob, key_characteristics);
1781
1782 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1783
1784 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1785 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
David Drysdale42fe1892021-10-14 14:43:46 +01001786}
1787
1788/*
1789 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1790 *
1791 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1792 * SIGN and AGREE_KEY.
1793 */
1794TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1795 if (!Curve25519Supported()) {
1796 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1797 }
1798
1799 EcCurve curve = EcCurve::CURVE_25519;
1800 vector<uint8_t> key_blob;
1801 vector<KeyCharacteristics> key_characteristics;
1802 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1803 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1804 .EcdsaSigningKey(curve)
1805 .Digest(Digest::NONE)
1806 .SetDefaultValidity(),
1807 &key_blob, &key_characteristics);
1808 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1809}
1810
1811/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001812 * NewKeyGenerationTest.EcdsaWithMissingValidity
1813 *
1814 * Verifies that keymint returns an error while generating asymmetric key
1815 * without providing NOT_BEFORE and NOT_AFTER parameters.
1816 */
1817TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001818 if (AidlVersion() < 2) {
1819 /*
1820 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1821 * specified for asymmetric key generation. However, this was not
1822 * checked at the time so we can only be strict about checking this for
1823 * implementations of KeyMint version 2 and above.
1824 */
1825 GTEST_SKIP() << "Validity strict since KeyMint v2";
1826 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001827 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1828 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1829 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1830
1831 vector<uint8_t> key_blob;
1832 vector<KeyCharacteristics> key_characteristics;
1833 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1834 GenerateKey(AuthorizationSetBuilder()
1835 .EcdsaSigningKey(EcCurve::P_256)
1836 .Digest(Digest::NONE)
1837 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1838 kUndefinedExpirationDateTime),
1839 &key_blob, &key_characteristics));
1840
1841 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1842 GenerateKey(AuthorizationSetBuilder()
1843 .EcdsaSigningKey(EcCurve::P_256)
1844 .Digest(Digest::NONE)
1845 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1846 &key_blob, &key_characteristics));
1847}
1848
1849/*
Selene Huang4f64c222021-04-13 19:54:36 -07001850 * NewKeyGenerationTest.EcdsaAttestation
1851 *
1852 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1853 * an attestation will be generated.
1854 */
1855TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1856 auto challenge = "hello";
1857 auto app_id = "foo";
1858
Selene Huang6e46f142021-04-20 19:20:11 -07001859 auto subject = "cert subj 2";
1860 vector<uint8_t> subject_der(make_name_from_str(subject));
1861
1862 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1863 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1864
David Drysdaledf09e542021-06-08 15:46:11 +01001865 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001866 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07001867 vector<uint8_t> key_blob;
1868 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001869 auto builder = AuthorizationSetBuilder()
1870 .Authorization(TAG_NO_AUTH_REQUIRED)
1871 .EcdsaSigningKey(curve)
1872 .Digest(Digest::NONE)
1873 .AttestationChallenge(challenge)
1874 .AttestationApplicationId(app_id)
1875 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1876 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1877 .SetDefaultValidity();
1878
1879 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001880 // Strongbox may not support factory provisioned attestation key.
1881 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001882 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1883 result = GenerateKeyWithSelfSignedAttestKey(
1884 AuthorizationSetBuilder()
1885 .EcdsaKey(curve)
1886 .AttestKey()
1887 .SetDefaultValidity(), /* attest key params */
1888 builder, &key_blob, &key_characteristics);
1889 }
subrahmanyaman05642492022-02-05 07:10:56 +00001890 }
1891 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001892 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001893 ASSERT_GT(key_blob.size(), 0U);
1894 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001895 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001896
1897 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1898
1899 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001900 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001901
1902 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1903 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001904 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001905
1906 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1907 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001908 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001909 sw_enforced, hw_enforced, SecLevel(),
1910 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07001911 }
1912}
1913
1914/*
David Drysdale42fe1892021-10-14 14:43:46 +01001915 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1916 *
1917 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1918 * an attestation will be generated.
1919 */
1920TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1921 if (!Curve25519Supported()) {
1922 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1923 }
1924
1925 EcCurve curve = EcCurve::CURVE_25519;
1926 auto challenge = "hello";
1927 auto app_id = "foo";
1928
1929 auto subject = "cert subj 2";
1930 vector<uint8_t> subject_der(make_name_from_str(subject));
1931
1932 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1933 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1934
1935 vector<uint8_t> key_blob;
1936 vector<KeyCharacteristics> key_characteristics;
1937 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1938 .Authorization(TAG_NO_AUTH_REQUIRED)
1939 .EcdsaSigningKey(curve)
1940 .Digest(Digest::NONE)
1941 .AttestationChallenge(challenge)
1942 .AttestationApplicationId(app_id)
1943 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1944 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1945 .SetDefaultValidity(),
1946 &key_blob, &key_characteristics);
1947 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001948 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale42fe1892021-10-14 14:43:46 +01001949 ASSERT_GT(key_blob.size(), 0U);
1950 CheckBaseParams(key_characteristics);
1951 CheckCharacteristics(key_blob, key_characteristics);
1952
1953 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1954
1955 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1956 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1957
1958 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1959 ASSERT_GT(cert_chain_.size(), 0);
1960 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1961
1962 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1963 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1964 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1965 sw_enforced, hw_enforced, SecLevel(),
1966 cert_chain_[0].encodedCertificate));
David Drysdale42fe1892021-10-14 14:43:46 +01001967}
1968
1969/*
David Drysdale37af4b32021-05-14 16:46:59 +01001970 * NewKeyGenerationTest.EcdsaAttestationTags
1971 *
1972 * Verifies that creation of an attested ECDSA key includes various tags in the
1973 * attestation extension.
1974 */
1975TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1976 auto challenge = "hello";
1977 auto app_id = "foo";
1978 auto subject = "cert subj 2";
1979 vector<uint8_t> subject_der(make_name_from_str(subject));
1980 uint64_t serial_int = 0x1010;
1981 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1982 const AuthorizationSetBuilder base_builder =
1983 AuthorizationSetBuilder()
1984 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001985 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001986 .Digest(Digest::NONE)
1987 .AttestationChallenge(challenge)
1988 .AttestationApplicationId(app_id)
1989 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1990 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1991 .SetDefaultValidity();
1992
1993 // Various tags that map to fields in the attestation extension ASN.1 schema.
1994 auto extra_tags = AuthorizationSetBuilder()
1995 .Authorization(TAG_ROLLBACK_RESISTANCE)
1996 .Authorization(TAG_EARLY_BOOT_ONLY)
1997 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1998 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1999 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
2000 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
2001 .Authorization(TAG_AUTH_TIMEOUT, 100000)
2002 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
2003 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
2004 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2005 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
2006 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01002007
David Drysdale37af4b32021-05-14 16:46:59 +01002008 for (const KeyParameter& tag : extra_tags) {
2009 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2010 vector<uint8_t> key_blob;
2011 vector<KeyCharacteristics> key_characteristics;
2012 AuthorizationSetBuilder builder = base_builder;
2013 builder.push_back(tag);
2014 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
2015 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
2016 tag.tag == TAG_ROLLBACK_RESISTANCE) {
2017 continue;
2018 }
Seth Mooreb393b082021-07-12 14:18:28 -07002019 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
2020 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01002021 continue;
2022 }
subrahmanyaman05642492022-02-05 07:10:56 +00002023 // Strongbox may not support factory provisioned attestation key.
2024 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002025 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2026 result = GenerateKeyWithSelfSignedAttestKey(
2027 AuthorizationSetBuilder()
2028 .EcdsaKey(EcCurve::P_256)
2029 .AttestKey()
2030 .SetDefaultValidity(), /* attest key params */
2031 builder, &key_blob, &key_characteristics);
2032 }
subrahmanyaman05642492022-02-05 07:10:56 +00002033 }
David Drysdale37af4b32021-05-14 16:46:59 +01002034 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002035 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale37af4b32021-05-14 16:46:59 +01002036 ASSERT_GT(key_blob.size(), 0U);
2037
2038 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2039 ASSERT_GT(cert_chain_.size(), 0);
2040 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2041
2042 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2043 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07002044 // Some tags are optional, so don't require them to be in the enforcements.
2045 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01002046 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
2047 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
2048 }
2049
2050 // Verifying the attestation record will check for the specific tag because
2051 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002052 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2053 hw_enforced, SecLevel(),
2054 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002055 }
2056
David Drysdalec53b7d92021-10-11 12:35:58 +01002057 // Collection of invalid attestation ID tags.
2058 auto invalid_tags =
2059 AuthorizationSetBuilder()
2060 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
2061 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
2062 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
2063 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
2064 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
2065 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
2066 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
2067 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01002068 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01002069 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01002070 vector<uint8_t> key_blob;
2071 vector<KeyCharacteristics> key_characteristics;
2072 AuthorizationSetBuilder builder =
2073 AuthorizationSetBuilder()
2074 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002075 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01002076 .Digest(Digest::NONE)
2077 .AttestationChallenge(challenge)
2078 .AttestationApplicationId(app_id)
2079 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2080 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2081 .SetDefaultValidity();
2082 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002083
2084 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
2085 // Strongbox may not support factory provisioned attestation key.
2086 if (SecLevel() == SecurityLevel::STRONGBOX) {
2087 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2088 error = GenerateKeyWithSelfSignedAttestKey(
2089 AuthorizationSetBuilder()
2090 .EcdsaKey(EcCurve::P_256)
2091 .AttestKey()
2092 .SetDefaultValidity(), /* attest key params */
2093 builder, &key_blob, &key_characteristics);
2094 }
2095 }
David Drysdalec68dc932023-07-06 10:05:12 +01002096
2097 device_id_attestation_check_acceptable_error(tag.tag, error);
David Drysdale37af4b32021-05-14 16:46:59 +01002098 }
2099}
2100
2101/*
David Drysdalec53b7d92021-10-11 12:35:58 +01002102 * NewKeyGenerationTest.EcdsaAttestationIdTags
2103 *
2104 * Verifies that creation of an attested ECDSA key includes various ID tags in the
2105 * attestation extension.
2106 */
2107TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
2108 auto challenge = "hello";
2109 auto app_id = "foo";
2110 auto subject = "cert subj 2";
2111 vector<uint8_t> subject_der(make_name_from_str(subject));
2112 uint64_t serial_int = 0x1010;
2113 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2114 const AuthorizationSetBuilder base_builder =
2115 AuthorizationSetBuilder()
2116 .Authorization(TAG_NO_AUTH_REQUIRED)
2117 .EcdsaSigningKey(EcCurve::P_256)
2118 .Digest(Digest::NONE)
2119 .AttestationChallenge(challenge)
2120 .AttestationApplicationId(app_id)
2121 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2122 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2123 .SetDefaultValidity();
2124
2125 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2126 auto extra_tags = AuthorizationSetBuilder();
Prashant Patil24f75792023-09-07 15:25:14 +00002127 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_BRAND, "brand");
2128 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "device");
2129 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "name");
2130 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer");
2131 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MODEL, "model");
Tri Vo799e4352022-11-07 17:23:50 -08002132 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
David Drysdalec53b7d92021-10-11 12:35:58 +01002133
2134 for (const KeyParameter& tag : extra_tags) {
2135 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2136 vector<uint8_t> key_blob;
2137 vector<KeyCharacteristics> key_characteristics;
2138 AuthorizationSetBuilder builder = base_builder;
2139 builder.push_back(tag);
2140 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002141 // Strongbox may not support factory provisioned attestation key.
2142 if (SecLevel() == SecurityLevel::STRONGBOX) {
2143 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2144 }
Prashant Patil88ad1892022-03-15 16:31:02 +00002145 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2146 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002147 continue;
2148 }
2149 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002150 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdalec53b7d92021-10-11 12:35:58 +01002151 ASSERT_GT(key_blob.size(), 0U);
2152
2153 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2154 ASSERT_GT(cert_chain_.size(), 0);
2155 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2156
2157 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2158 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2159
2160 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2161 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2162 // attestation extension should contain them, so make sure the extra tag is added.
2163 hw_enforced.push_back(tag);
2164
2165 // Verifying the attestation record will check for the specific tag because
2166 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002167 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2168 hw_enforced, SecLevel(),
2169 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002170 }
2171}
2172
2173/*
David Drysdale565ccc72021-10-11 12:49:50 +01002174 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2175 *
2176 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2177 */
2178TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2179 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002180 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002181 auto challenge = "hello";
2182 auto subject = "cert subj 2";
2183 vector<uint8_t> subject_der(make_name_from_str(subject));
2184 uint64_t serial_int = 0x1010;
2185 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002186 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002187 AuthorizationSetBuilder()
2188 .Authorization(TAG_NO_AUTH_REQUIRED)
2189 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2190 .EcdsaSigningKey(EcCurve::P_256)
2191 .Digest(Digest::NONE)
2192 .AttestationChallenge(challenge)
2193 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2194 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2195 .AttestationApplicationId(app_id)
2196 .Authorization(TAG_CREATION_DATETIME, datetime)
2197 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002198 if (reset) {
2199 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2200 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002201 auto result = GenerateKey(builder);
2202 if (SecLevel() == SecurityLevel::STRONGBOX) {
2203 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2204 result = GenerateKeyWithSelfSignedAttestKey(
2205 AuthorizationSetBuilder()
2206 .EcdsaKey(EcCurve::P_256)
2207 .AttestKey()
2208 .SetDefaultValidity(), /* attest key params */
2209 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2210 }
2211 }
2212 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002213 ASSERT_GT(key_blob_.size(), 0U);
2214
2215 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2216 ASSERT_GT(cert_chain_.size(), 0);
2217 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2218
2219 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2220 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2221
2222 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002223 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2224 hw_enforced, SecLevel(),
2225 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002226 EXPECT_GT(unique_id->size(), 0);
2227 CheckedDeleteKey();
2228 };
2229
2230 // Generate unique ID
2231 auto app_id = "foo";
2232 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2233 vector<uint8_t> unique_id;
2234 get_unique_id(app_id, cert_date, &unique_id);
2235
2236 // Generating a new key with the same parameters should give the same unique ID.
2237 vector<uint8_t> unique_id2;
2238 get_unique_id(app_id, cert_date, &unique_id2);
2239 EXPECT_EQ(unique_id, unique_id2);
2240
2241 // Generating a new key with a slightly different date should give the same unique ID.
2242 uint64_t rounded_date = cert_date / 2592000000LLU;
2243 uint64_t min_date = rounded_date * 2592000000LLU;
2244 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2245
2246 vector<uint8_t> unique_id3;
2247 get_unique_id(app_id, min_date, &unique_id3);
2248 EXPECT_EQ(unique_id, unique_id3);
2249
2250 vector<uint8_t> unique_id4;
2251 get_unique_id(app_id, max_date, &unique_id4);
2252 EXPECT_EQ(unique_id, unique_id4);
2253
2254 // A different attestation application ID should yield a different unique ID.
2255 auto app_id2 = "different_foo";
2256 vector<uint8_t> unique_id5;
2257 get_unique_id(app_id2, cert_date, &unique_id5);
2258 EXPECT_NE(unique_id, unique_id5);
2259
2260 // A radically different date should yield a different unique ID.
2261 vector<uint8_t> unique_id6;
2262 get_unique_id(app_id, 1611621648000, &unique_id6);
2263 EXPECT_NE(unique_id, unique_id6);
2264
2265 vector<uint8_t> unique_id7;
2266 get_unique_id(app_id, max_date + 1, &unique_id7);
2267 EXPECT_NE(unique_id, unique_id7);
2268
2269 vector<uint8_t> unique_id8;
2270 get_unique_id(app_id, min_date - 1, &unique_id8);
2271 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002272
2273 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2274 vector<uint8_t> unique_id9;
2275 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2276 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002277}
2278
2279/*
David Drysdale37af4b32021-05-14 16:46:59 +01002280 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2281 *
2282 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2283 */
2284TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2285 auto challenge = "hello";
2286 auto attest_app_id = "foo";
2287 auto subject = "cert subj 2";
2288 vector<uint8_t> subject_der(make_name_from_str(subject));
2289 uint64_t serial_int = 0x1010;
2290 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2291
2292 // Earlier versions of the attestation extension schema included a slot:
2293 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2294 // This should never have been included, and should never be filled in.
2295 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2296 // to confirm that this field never makes it into the attestation extension.
2297 vector<uint8_t> key_blob;
2298 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002299 auto builder = AuthorizationSetBuilder()
2300 .Authorization(TAG_NO_AUTH_REQUIRED)
2301 .EcdsaSigningKey(EcCurve::P_256)
2302 .Digest(Digest::NONE)
2303 .AttestationChallenge(challenge)
2304 .AttestationApplicationId(attest_app_id)
2305 .Authorization(TAG_APPLICATION_ID, "client_id")
2306 .Authorization(TAG_APPLICATION_DATA, "appdata")
2307 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2308 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2309 .SetDefaultValidity();
2310
2311 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002312 // Strongbox may not support factory provisioned attestation key.
2313 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002314 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2315 result = GenerateKeyWithSelfSignedAttestKey(
2316 AuthorizationSetBuilder()
2317 .EcdsaKey(EcCurve::P_256)
2318 .AttestKey()
2319 .SetDefaultValidity(), /* attest key params */
2320 builder, &key_blob, &key_characteristics);
2321 }
subrahmanyaman05642492022-02-05 07:10:56 +00002322 }
David Drysdale37af4b32021-05-14 16:46:59 +01002323 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002324 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale37af4b32021-05-14 16:46:59 +01002325 ASSERT_GT(key_blob.size(), 0U);
2326
2327 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2328 ASSERT_GT(cert_chain_.size(), 0);
2329 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2330
2331 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2332 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002333 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2334 hw_enforced, SecLevel(),
2335 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002336
2337 // Check that the app id is not in the cert.
2338 string app_id = "clientid";
2339 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2340 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2341 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2342 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2343 cert_chain_[0].encodedCertificate.end());
David Drysdale37af4b32021-05-14 16:46:59 +01002344}
2345
2346/*
Selene Huang4f64c222021-04-13 19:54:36 -07002347 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2348 *
2349 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2350 * the key will generate a self signed attestation.
2351 */
2352TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002353 auto subject = "cert subj 2";
2354 vector<uint8_t> subject_der(make_name_from_str(subject));
2355
2356 uint64_t serial_int = 0x123456FFF1234;
2357 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2358
David Drysdaledf09e542021-06-08 15:46:11 +01002359 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002360 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002361 vector<uint8_t> key_blob;
2362 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002363 ASSERT_EQ(ErrorCode::OK,
2364 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002365 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002366 .Digest(Digest::NONE)
2367 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2368 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2369 .SetDefaultValidity(),
2370 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002371 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002372 ASSERT_GT(key_blob.size(), 0U);
2373 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002374 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002375
2376 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2377
2378 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002379 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002380
2381 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2382 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002383 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002384
2385 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2386 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002387 }
2388}
2389
2390/*
2391 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2392 *
2393 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2394 * app id must also be provided or else it will fail.
2395 */
2396TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2397 auto challenge = "hello";
2398 vector<uint8_t> key_blob;
2399 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002400 auto builder = AuthorizationSetBuilder()
2401 .EcdsaSigningKey(EcCurve::P_256)
2402 .Digest(Digest::NONE)
2403 .AttestationChallenge(challenge)
2404 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002405
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002406 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002407 // Strongbox may not support factory provisioned attestation key.
2408 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002409 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2410 result = GenerateKeyWithSelfSignedAttestKey(
2411 AuthorizationSetBuilder()
2412 .EcdsaKey(EcCurve::P_256)
2413 .AttestKey()
2414 .SetDefaultValidity(), /* attest key params */
2415 builder, &key_blob, &key_characteristics);
2416 }
subrahmanyaman05642492022-02-05 07:10:56 +00002417 }
2418 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002419}
2420
2421/*
2422 * NewKeyGenerationTest.EcdsaIgnoreAppId
2423 *
2424 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2425 * any appid will be ignored, and keymint will generate a self sign certificate.
2426 */
2427TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2428 auto app_id = "foo";
2429
David Drysdaledf09e542021-06-08 15:46:11 +01002430 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002431 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002432 vector<uint8_t> key_blob;
2433 vector<KeyCharacteristics> key_characteristics;
2434 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002435 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002436 .Digest(Digest::NONE)
2437 .AttestationApplicationId(app_id)
2438 .SetDefaultValidity(),
2439 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002440 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002441
2442 ASSERT_GT(key_blob.size(), 0U);
2443 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002444 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002445
2446 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2447
2448 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002449 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002450
2451 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2452 ASSERT_EQ(cert_chain_.size(), 1);
2453
2454 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2455 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002456 }
2457}
2458
2459/*
2460 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2461 *
2462 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2463 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2464 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2465 * to specify how many following bytes will be used to encode the length.
2466 */
2467TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2468 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002469 std::vector<uint32_t> app_id_lengths{143, 258};
2470
2471 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002472 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002473 const string app_id(length, 'a');
2474 vector<uint8_t> key_blob;
2475 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002476 auto builder = AuthorizationSetBuilder()
2477 .Authorization(TAG_NO_AUTH_REQUIRED)
2478 .EcdsaSigningKey(EcCurve::P_256)
2479 .Digest(Digest::NONE)
2480 .AttestationChallenge(challenge)
2481 .AttestationApplicationId(app_id)
2482 .SetDefaultValidity();
2483
2484 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002485 // Strongbox may not support factory provisioned attestation key.
2486 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002487 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2488 result = GenerateKeyWithSelfSignedAttestKey(
2489 AuthorizationSetBuilder()
2490 .EcdsaKey(EcCurve::P_256)
2491 .AttestKey()
2492 .SetDefaultValidity(), /* attest key params */
2493 builder, &key_blob, &key_characteristics);
2494 }
subrahmanyaman05642492022-02-05 07:10:56 +00002495 }
2496 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01002497 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002498 ASSERT_GT(key_blob.size(), 0U);
2499 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002500 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002501
2502 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2503
2504 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002505 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002506
2507 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2508 ASSERT_GT(cert_chain_.size(), 0);
2509
2510 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2511 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002512 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002513 sw_enforced, hw_enforced, SecLevel(),
2514 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07002515 }
2516}
2517
2518/*
Qi Wud22ec842020-11-26 13:27:53 +08002519 * NewKeyGenerationTest.LimitedUsageEcdsa
2520 *
2521 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2522 * resulting keys have correct characteristics.
2523 */
2524TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002525 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002526 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002527 vector<uint8_t> key_blob;
2528 vector<KeyCharacteristics> key_characteristics;
2529 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002530 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002531 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002532 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2533 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002534 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002535 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002536
2537 ASSERT_GT(key_blob.size(), 0U);
2538 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002539 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002540
2541 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2542
2543 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002544 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002545
2546 // Check the usage count limit tag appears in the authorizations.
2547 AuthorizationSet auths;
2548 for (auto& entry : key_characteristics) {
2549 auths.push_back(AuthorizationSet(entry.authorizations));
2550 }
2551 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2552 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002553 }
2554}
2555
2556/*
Selene Huang31ab4042020-04-29 04:22:39 -07002557 * NewKeyGenerationTest.EcdsaDefaultSize
2558 *
David Drysdaledf09e542021-06-08 15:46:11 +01002559 * Verifies that failing to specify a curve for EC key generation returns
David Drysdale84b685a2023-08-09 07:00:34 +01002560 * UNSUPPORTED_KEY_SIZE or UNSUPPORTED_EC_CURVE.
Selene Huang31ab4042020-04-29 04:22:39 -07002561 */
2562TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
David Drysdale84b685a2023-08-09 07:00:34 +01002563 auto result = GenerateKey(AuthorizationSetBuilder()
2564 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2565 .SigningKey()
2566 .Digest(Digest::NONE)
2567 .SetDefaultValidity());
2568 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2569 result == ErrorCode::UNSUPPORTED_EC_CURVE)
2570 << "unexpected result " << result;
Selene Huang31ab4042020-04-29 04:22:39 -07002571}
2572
2573/*
David Drysdale42fe1892021-10-14 14:43:46 +01002574 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002575 *
David Drysdale42fe1892021-10-14 14:43:46 +01002576 * Verifies that specifying an invalid curve for EC key generation returns
David Drysdale84b685a2023-08-09 07:00:34 +01002577 * UNSUPPORTED_KEY_SIZE or UNSUPPORTED_EC_CURVE.
Selene Huang31ab4042020-04-29 04:22:39 -07002578 */
David Drysdale42fe1892021-10-14 14:43:46 +01002579TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002580 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002581 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002582 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002583 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002584 auto result = GenerateKey(AuthorizationSetBuilder()
2585 .EcdsaSigningKey(curve)
2586 .Digest(Digest::NONE)
2587 .SetDefaultValidity(),
2588 &key_blob, &key_characteristics);
2589 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
David Drysdale84b685a2023-08-09 07:00:34 +01002590 result == ErrorCode::UNSUPPORTED_EC_CURVE)
2591 << "unexpected result " << result;
Selene Huang31ab4042020-04-29 04:22:39 -07002592 }
2593
David Drysdaledf09e542021-06-08 15:46:11 +01002594 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2595 GenerateKey(AuthorizationSetBuilder()
2596 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2597 .Authorization(TAG_KEY_SIZE, 190)
2598 .SigningKey()
2599 .Digest(Digest::NONE)
2600 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002601}
2602
2603/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002604 * NewKeyGenerationTest.EcdsaMissingCurve
2605 *
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002606 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V3.
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002607 */
2608TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002609 if (AidlVersion() < 3) {
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002610 /*
2611 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2612 * However, this was not checked at the time so we can only be strict about checking this
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002613 * for implementations of KeyMint version 3 and above.
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002614 */
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002615 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v3";
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002616 }
2617 /* If EC_CURVE not provided, generateKey
2618 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2619 */
2620 auto result = GenerateKey(
2621 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2622 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2623 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2624}
2625
2626/*
Selene Huang31ab4042020-04-29 04:22:39 -07002627 * NewKeyGenerationTest.EcdsaMismatchKeySize
2628 *
2629 * Verifies that specifying mismatched key size and curve for EC key generation returns
2630 * INVALID_ARGUMENT.
2631 */
2632TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002633 if (SecLevel() == SecurityLevel::STRONGBOX) {
2634 GTEST_SKIP() << "Test not applicable to StrongBox device";
2635 }
Selene Huang31ab4042020-04-29 04:22:39 -07002636
David Drysdaledf09e542021-06-08 15:46:11 +01002637 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002638 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002639 .Authorization(TAG_KEY_SIZE, 224)
2640 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002641 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002642 .Digest(Digest::NONE)
2643 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002644 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002645}
2646
2647/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002648 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002649 *
2650 * Verifies that keymint does not support any curve designated as unsupported.
2651 */
2652TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2653 Digest digest;
2654 if (SecLevel() == SecurityLevel::STRONGBOX) {
2655 digest = Digest::SHA_2_256;
2656 } else {
2657 digest = Digest::SHA_2_512;
2658 }
2659 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002660 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002661 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2662 .EcdsaSigningKey(curve)
2663 .Digest(digest)
2664 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002665 << "Failed to generate key on curve: " << curve;
2666 CheckedDeleteKey();
2667 }
2668}
2669
2670/*
2671 * NewKeyGenerationTest.Hmac
2672 *
2673 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2674 * characteristics.
2675 */
2676TEST_P(NewKeyGenerationTest, Hmac) {
2677 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002678 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002679 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002680 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002681 constexpr size_t key_size = 128;
2682 ASSERT_EQ(ErrorCode::OK,
2683 GenerateKey(
2684 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2685 TAG_MIN_MAC_LENGTH, 128),
2686 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002687 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07002688
2689 ASSERT_GT(key_blob.size(), 0U);
2690 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002691 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002692
Shawn Willden7f424372021-01-10 18:06:50 -07002693 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2694 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2695 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2696 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002697 }
2698}
2699
2700/*
Selene Huang4f64c222021-04-13 19:54:36 -07002701 * NewKeyGenerationTest.HmacNoAttestation
2702 *
2703 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2704 * and app id are provided.
2705 */
2706TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2707 auto challenge = "hello";
2708 auto app_id = "foo";
2709
2710 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002711 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002712 vector<uint8_t> key_blob;
2713 vector<KeyCharacteristics> key_characteristics;
2714 constexpr size_t key_size = 128;
2715 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2716 .HmacKey(key_size)
2717 .Digest(digest)
2718 .AttestationChallenge(challenge)
2719 .AttestationApplicationId(app_id)
2720 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2721 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002722 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002723
2724 ASSERT_GT(key_blob.size(), 0U);
2725 ASSERT_EQ(cert_chain_.size(), 0);
2726 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002727 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002728
2729 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2730 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2731 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2732 << "Key size " << key_size << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002733 }
2734}
2735
2736/*
Qi Wud22ec842020-11-26 13:27:53 +08002737 * NewKeyGenerationTest.LimitedUsageHmac
2738 *
2739 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2740 * resulting keys have correct characteristics.
2741 */
2742TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2743 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002744 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002745 vector<uint8_t> key_blob;
2746 vector<KeyCharacteristics> key_characteristics;
2747 constexpr size_t key_size = 128;
2748 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2749 .HmacKey(key_size)
2750 .Digest(digest)
2751 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2752 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2753 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002754 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002755
2756 ASSERT_GT(key_blob.size(), 0U);
2757 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002758 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002759
2760 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2761 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2762 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2763 << "Key size " << key_size << "missing";
2764
2765 // Check the usage count limit tag appears in the authorizations.
2766 AuthorizationSet auths;
2767 for (auto& entry : key_characteristics) {
2768 auths.push_back(AuthorizationSet(entry.authorizations));
2769 }
2770 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2771 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002772 }
2773}
2774
2775/*
Selene Huang31ab4042020-04-29 04:22:39 -07002776 * NewKeyGenerationTest.HmacCheckKeySizes
2777 *
2778 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2779 */
2780TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2781 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002782 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002783 if (key_size < 64 || key_size % 8 != 0) {
2784 // To keep this test from being very slow, we only test a random fraction of
2785 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2786 // them, we expect to run ~40 of them in each run.
2787 if (key_size % 8 == 0 || random() % 10 == 0) {
2788 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2789 GenerateKey(AuthorizationSetBuilder()
2790 .HmacKey(key_size)
2791 .Digest(Digest::SHA_2_256)
2792 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2793 << "HMAC key size " << key_size << " invalid";
2794 }
2795 } else {
2796 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2797 .HmacKey(key_size)
2798 .Digest(Digest::SHA_2_256)
2799 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2800 << "Failed to generate HMAC key of size " << key_size;
2801 CheckedDeleteKey();
2802 }
2803 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002804 if (SecLevel() == SecurityLevel::STRONGBOX) {
2805 // STRONGBOX devices must not support keys larger than 512 bits.
2806 size_t key_size = 520;
2807 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2808 GenerateKey(AuthorizationSetBuilder()
2809 .HmacKey(key_size)
2810 .Digest(Digest::SHA_2_256)
2811 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2812 << "HMAC key size " << key_size << " unexpectedly valid";
2813 }
Selene Huang31ab4042020-04-29 04:22:39 -07002814}
2815
2816/*
2817 * NewKeyGenerationTest.HmacCheckMinMacLengths
2818 *
2819 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2820 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2821 * specific MAC length that failed, so reproducing a failed run will be easy.
2822 */
2823TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2824 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002825 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002826 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2827 // To keep this test from being very long, we only test a random fraction of
2828 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2829 // we expect to run ~17 of them in each run.
2830 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2831 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2832 GenerateKey(AuthorizationSetBuilder()
2833 .HmacKey(128)
2834 .Digest(Digest::SHA_2_256)
2835 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2836 << "HMAC min mac length " << min_mac_length << " invalid.";
2837 }
2838 } else {
2839 EXPECT_EQ(ErrorCode::OK,
2840 GenerateKey(AuthorizationSetBuilder()
2841 .HmacKey(128)
2842 .Digest(Digest::SHA_2_256)
2843 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2844 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2845 CheckedDeleteKey();
2846 }
2847 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002848
2849 // Minimum MAC length must be no more than 512 bits.
2850 size_t min_mac_length = 520;
2851 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2852 GenerateKey(AuthorizationSetBuilder()
2853 .HmacKey(128)
2854 .Digest(Digest::SHA_2_256)
2855 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2856 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002857}
2858
2859/*
2860 * NewKeyGenerationTest.HmacMultipleDigests
2861 *
2862 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2863 */
2864TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002865 if (SecLevel() == SecurityLevel::STRONGBOX) {
2866 GTEST_SKIP() << "Test not applicable to StrongBox device";
2867 }
Selene Huang31ab4042020-04-29 04:22:39 -07002868
2869 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2870 GenerateKey(AuthorizationSetBuilder()
2871 .HmacKey(128)
2872 .Digest(Digest::SHA1)
2873 .Digest(Digest::SHA_2_256)
2874 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2875}
2876
2877/*
2878 * NewKeyGenerationTest.HmacDigestNone
2879 *
2880 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2881 */
2882TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2883 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2884 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2885 128)));
2886
2887 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2888 GenerateKey(AuthorizationSetBuilder()
2889 .HmacKey(128)
2890 .Digest(Digest::NONE)
2891 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2892}
2893
Selene Huang4f64c222021-04-13 19:54:36 -07002894/*
2895 * NewKeyGenerationTest.AesNoAttestation
2896 *
2897 * Verifies that attestation parameters to AES keys are ignored and generateKey
2898 * will succeed.
2899 */
2900TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2901 auto challenge = "hello";
2902 auto app_id = "foo";
2903
2904 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2905 .Authorization(TAG_NO_AUTH_REQUIRED)
2906 .AesEncryptionKey(128)
2907 .EcbMode()
2908 .Padding(PaddingMode::PKCS7)
2909 .AttestationChallenge(challenge)
2910 .AttestationApplicationId(app_id)));
2911
2912 ASSERT_EQ(cert_chain_.size(), 0);
2913}
2914
2915/*
2916 * NewKeyGenerationTest.TripleDesNoAttestation
2917 *
2918 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2919 * will be successful. No attestation should be generated.
2920 */
2921TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2922 auto challenge = "hello";
2923 auto app_id = "foo";
2924
2925 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2926 .TripleDesEncryptionKey(168)
2927 .BlockMode(BlockMode::ECB)
2928 .Authorization(TAG_NO_AUTH_REQUIRED)
2929 .Padding(PaddingMode::NONE)
2930 .AttestationChallenge(challenge)
2931 .AttestationApplicationId(app_id)));
2932 ASSERT_EQ(cert_chain_.size(), 0);
2933}
2934
Selene Huang31ab4042020-04-29 04:22:39 -07002935INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2936
2937typedef KeyMintAidlTestBase SigningOperationsTest;
2938
2939/*
2940 * SigningOperationsTest.RsaSuccess
2941 *
2942 * Verifies that raw RSA signature operations succeed.
2943 */
2944TEST_P(SigningOperationsTest, RsaSuccess) {
2945 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2946 .RsaSigningKey(2048, 65537)
2947 .Digest(Digest::NONE)
2948 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002949 .Authorization(TAG_NO_AUTH_REQUIRED)
2950 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002951 string message = "12345678901234567890123456789012";
2952 string signature = SignMessage(
2953 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002954 LocalVerifyMessage(message, signature,
2955 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2956}
2957
2958/*
2959 * SigningOperationsTest.RsaAllPaddingsAndDigests
2960 *
2961 * Verifies RSA signature/verification for all padding modes and digests.
2962 */
2963TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2964 auto authorizations = AuthorizationSetBuilder()
2965 .Authorization(TAG_NO_AUTH_REQUIRED)
2966 .RsaSigningKey(2048, 65537)
2967 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2968 .Padding(PaddingMode::NONE)
2969 .Padding(PaddingMode::RSA_PSS)
2970 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2971 .SetDefaultValidity();
2972
2973 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2974
2975 string message(128, 'a');
2976 string corrupt_message(message);
2977 ++corrupt_message[corrupt_message.size() / 2];
2978
2979 for (auto padding :
2980 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2981 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002982 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002983 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2984 // Digesting only makes sense with padding.
2985 continue;
2986 }
2987
2988 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2989 // PSS requires digesting.
2990 continue;
2991 }
2992
2993 string signature =
2994 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2995 LocalVerifyMessage(message, signature,
2996 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2997 }
2998 }
Selene Huang31ab4042020-04-29 04:22:39 -07002999}
3000
3001/*
3002 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
3003 *
Shawn Willden7f424372021-01-10 18:06:50 -07003004 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07003005 */
3006TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
3007 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3008 .Authorization(TAG_NO_AUTH_REQUIRED)
3009 .RsaSigningKey(2048, 65537)
3010 .Digest(Digest::NONE)
3011 .Padding(PaddingMode::NONE)
3012 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003013 .Authorization(TAG_APPLICATION_DATA, "appdata")
3014 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003015
3016 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3017
Selene Huang31ab4042020-04-29 04:22:39 -07003018 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3019 Begin(KeyPurpose::SIGN,
3020 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3021 AbortIfNeeded();
3022 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3023 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3024 .Digest(Digest::NONE)
3025 .Padding(PaddingMode::NONE)
3026 .Authorization(TAG_APPLICATION_ID, "clientid")));
3027 AbortIfNeeded();
3028 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3029 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3030 .Digest(Digest::NONE)
3031 .Padding(PaddingMode::NONE)
3032 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3033 AbortIfNeeded();
3034 EXPECT_EQ(ErrorCode::OK,
3035 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3036 .Digest(Digest::NONE)
3037 .Padding(PaddingMode::NONE)
3038 .Authorization(TAG_APPLICATION_DATA, "appdata")
3039 .Authorization(TAG_APPLICATION_ID, "clientid")));
3040 AbortIfNeeded();
3041}
3042
3043/*
3044 * SigningOperationsTest.RsaPssSha256Success
3045 *
3046 * Verifies that RSA-PSS signature operations succeed.
3047 */
3048TEST_P(SigningOperationsTest, RsaPssSha256Success) {
3049 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3050 .RsaSigningKey(2048, 65537)
3051 .Digest(Digest::SHA_2_256)
3052 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003053 .Authorization(TAG_NO_AUTH_REQUIRED)
3054 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003055 // Use large message, which won't work without digesting.
3056 string message(1024, 'a');
3057 string signature = SignMessage(
3058 message,
3059 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
3060}
3061
3062/*
3063 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
3064 *
3065 * Verifies that keymint rejects signature operations that specify a padding mode when the key
3066 * supports only unpadded operations.
3067 */
3068TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
3069 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3070 .RsaSigningKey(2048, 65537)
3071 .Digest(Digest::NONE)
3072 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003073 .Padding(PaddingMode::NONE)
3074 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003075 string message = "12345678901234567890123456789012";
3076 string signature;
3077
3078 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3079 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3080 .Digest(Digest::NONE)
3081 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3082}
3083
3084/*
3085 * SigningOperationsTest.NoUserConfirmation
3086 *
3087 * Verifies that keymint rejects signing operations for keys with
3088 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
3089 * presented.
3090 */
3091TEST_P(SigningOperationsTest, NoUserConfirmation) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08003092 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Subrahmanyamance2bebd2023-04-28 23:37:02 +00003093 .RsaSigningKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003094 .Digest(Digest::NONE)
3095 .Padding(PaddingMode::NONE)
3096 .Authorization(TAG_NO_AUTH_REQUIRED)
3097 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3098 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003099
3100 const string message = "12345678901234567890123456789012";
3101 EXPECT_EQ(ErrorCode::OK,
3102 Begin(KeyPurpose::SIGN,
3103 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3104 string signature;
3105 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3106}
3107
3108/*
3109 * SigningOperationsTest.RsaPkcs1Sha256Success
3110 *
3111 * Verifies that digested RSA-PKCS1 signature operations succeed.
3112 */
3113TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3114 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3115 .RsaSigningKey(2048, 65537)
3116 .Digest(Digest::SHA_2_256)
3117 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003118 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3119 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003120 string message(1024, 'a');
3121 string signature = SignMessage(message, AuthorizationSetBuilder()
3122 .Digest(Digest::SHA_2_256)
3123 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3124}
3125
3126/*
3127 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3128 *
3129 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3130 */
3131TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3132 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3133 .RsaSigningKey(2048, 65537)
3134 .Digest(Digest::NONE)
3135 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003136 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3137 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003138 string message(53, 'a');
3139 string signature = SignMessage(message, AuthorizationSetBuilder()
3140 .Digest(Digest::NONE)
3141 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3142}
3143
3144/*
3145 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3146 *
3147 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3148 * given a too-long message.
3149 */
3150TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3151 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3152 .RsaSigningKey(2048, 65537)
3153 .Digest(Digest::NONE)
3154 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003155 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3156 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003157 string message(257, 'a');
3158
3159 EXPECT_EQ(ErrorCode::OK,
3160 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3161 .Digest(Digest::NONE)
3162 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3163 string signature;
3164 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3165}
3166
3167/*
3168 * SigningOperationsTest.RsaPssSha512TooSmallKey
3169 *
3170 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3171 * used with a key that is too small for the message.
3172 *
3173 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3174 * keymint specification requires that salt_size == digest_size, so the message will be
3175 * digest_size * 2 +
3176 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3177 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3178 * for a 1024-bit key.
3179 */
3180TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003181 if (SecLevel() == SecurityLevel::STRONGBOX) {
3182 GTEST_SKIP() << "Test not applicable to StrongBox device";
3183 }
Selene Huang31ab4042020-04-29 04:22:39 -07003184 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3185 .RsaSigningKey(1024, 65537)
3186 .Digest(Digest::SHA_2_512)
3187 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003188 .Padding(PaddingMode::RSA_PSS)
3189 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003190 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3191 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3192 .Digest(Digest::SHA_2_512)
3193 .Padding(PaddingMode::RSA_PSS)));
3194}
3195
3196/*
3197 * SigningOperationsTest.RsaNoPaddingTooLong
3198 *
3199 * Verifies that raw RSA signature operations fail with the correct error code when
3200 * given a too-long message.
3201 */
3202TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3203 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3204 .RsaSigningKey(2048, 65537)
3205 .Digest(Digest::NONE)
3206 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003207 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3208 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003209 // One byte too long
3210 string message(2048 / 8 + 1, 'a');
3211 ASSERT_EQ(ErrorCode::OK,
3212 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3213 .Digest(Digest::NONE)
3214 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3215 string result;
3216 ErrorCode finish_error_code = Finish(message, &result);
3217 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3218 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3219
3220 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3221 message = string(128 * 1024, 'a');
3222 ASSERT_EQ(ErrorCode::OK,
3223 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3224 .Digest(Digest::NONE)
3225 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3226 finish_error_code = Finish(message, &result);
3227 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3228 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3229}
3230
3231/*
3232 * SigningOperationsTest.RsaAbort
3233 *
3234 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3235 * test, but the behavior should be algorithm and purpose-independent.
3236 */
3237TEST_P(SigningOperationsTest, RsaAbort) {
3238 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3239 .RsaSigningKey(2048, 65537)
3240 .Digest(Digest::NONE)
3241 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003242 .Padding(PaddingMode::NONE)
3243 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003244
3245 ASSERT_EQ(ErrorCode::OK,
3246 Begin(KeyPurpose::SIGN,
3247 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3248 EXPECT_EQ(ErrorCode::OK, Abort());
3249
3250 // Another abort should fail
3251 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3252
3253 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003254 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003255}
3256
3257/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003258 * SigningOperationsTest.RsaNonUniqueParams
3259 *
3260 * Verifies that an operation with multiple padding modes is rejected.
3261 */
3262TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3263 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3264 .RsaSigningKey(2048, 65537)
3265 .Digest(Digest::NONE)
3266 .Digest(Digest::SHA1)
3267 .Authorization(TAG_NO_AUTH_REQUIRED)
3268 .Padding(PaddingMode::NONE)
3269 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3270 .SetDefaultValidity()));
3271
3272 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3273 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3274 .Digest(Digest::NONE)
3275 .Padding(PaddingMode::NONE)
3276 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3277
Tommy Chiuc93c4392021-05-11 18:36:50 +08003278 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3279 .Digest(Digest::NONE)
3280 .Digest(Digest::SHA1)
3281 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3282 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003283
3284 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3285 Begin(KeyPurpose::SIGN,
3286 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3287}
3288
3289/*
Selene Huang31ab4042020-04-29 04:22:39 -07003290 * SigningOperationsTest.RsaUnsupportedPadding
3291 *
3292 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3293 * with a padding mode inappropriate for RSA.
3294 */
3295TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3297 .RsaSigningKey(2048, 65537)
3298 .Authorization(TAG_NO_AUTH_REQUIRED)
3299 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003300 .Padding(PaddingMode::PKCS7)
3301 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003302 ASSERT_EQ(
3303 ErrorCode::UNSUPPORTED_PADDING_MODE,
3304 Begin(KeyPurpose::SIGN,
3305 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003306 CheckedDeleteKey();
3307
3308 ASSERT_EQ(ErrorCode::OK,
3309 GenerateKey(
3310 AuthorizationSetBuilder()
3311 .RsaSigningKey(2048, 65537)
3312 .Authorization(TAG_NO_AUTH_REQUIRED)
3313 .Digest(Digest::SHA_2_256 /* supported digest */)
3314 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3315 .SetDefaultValidity()));
3316 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3317 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3318 .Digest(Digest::SHA_2_256)
3319 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003320}
3321
3322/*
3323 * SigningOperationsTest.RsaPssNoDigest
3324 *
3325 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3326 */
3327TEST_P(SigningOperationsTest, RsaNoDigest) {
3328 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3329 .RsaSigningKey(2048, 65537)
3330 .Authorization(TAG_NO_AUTH_REQUIRED)
3331 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003332 .Padding(PaddingMode::RSA_PSS)
3333 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003334 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3335 Begin(KeyPurpose::SIGN,
3336 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3337
3338 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3339 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3340}
3341
3342/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003343 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003344 *
3345 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3346 * supported in some cases (as validated in other tests), but a mode must be specified.
3347 */
3348TEST_P(SigningOperationsTest, RsaNoPadding) {
3349 // Padding must be specified
3350 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3351 .RsaKey(2048, 65537)
3352 .Authorization(TAG_NO_AUTH_REQUIRED)
3353 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003354 .Digest(Digest::NONE)
3355 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003356 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3357 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3358}
3359
3360/*
3361 * SigningOperationsTest.RsaShortMessage
3362 *
3363 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3364 */
3365TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3366 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3367 .Authorization(TAG_NO_AUTH_REQUIRED)
3368 .RsaSigningKey(2048, 65537)
3369 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003370 .Padding(PaddingMode::NONE)
3371 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003372
3373 // Barely shorter
3374 string message(2048 / 8 - 1, 'a');
3375 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3376
3377 // Much shorter
3378 message = "a";
3379 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3380}
3381
3382/*
3383 * SigningOperationsTest.RsaSignWithEncryptionKey
3384 *
3385 * Verifies that RSA encryption keys cannot be used to sign.
3386 */
3387TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3388 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3389 .Authorization(TAG_NO_AUTH_REQUIRED)
3390 .RsaEncryptionKey(2048, 65537)
3391 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003392 .Padding(PaddingMode::NONE)
3393 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003394 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3395 Begin(KeyPurpose::SIGN,
3396 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3397}
3398
3399/*
3400 * SigningOperationsTest.RsaSignTooLargeMessage
3401 *
3402 * Verifies that attempting a raw signature of a message which is the same length as the key,
3403 * but numerically larger than the public modulus, fails with the correct error.
3404 */
3405TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3406 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3407 .Authorization(TAG_NO_AUTH_REQUIRED)
3408 .RsaSigningKey(2048, 65537)
3409 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003410 .Padding(PaddingMode::NONE)
3411 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003412
3413 // Largest possible message will always be larger than the public modulus.
3414 string message(2048 / 8, static_cast<char>(0xff));
3415 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3416 .Authorization(TAG_NO_AUTH_REQUIRED)
3417 .Digest(Digest::NONE)
3418 .Padding(PaddingMode::NONE)));
3419 string signature;
3420 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3421}
3422
3423/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003424 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3425 *
David Drysdale42fe1892021-10-14 14:43:46 +01003426 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003427 */
3428TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003429 string message = "1234567890";
3430 string corrupt_message = "2234567890";
3431 for (auto curve : ValidCurves()) {
3432 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003433 // Ed25519 only allows Digest::NONE.
3434 auto digests = (curve == EcCurve::CURVE_25519)
3435 ? std::vector<Digest>(1, Digest::NONE)
3436 : ValidDigests(true /* withNone */, false /* withMD5 */);
3437
David Drysdaledf8f52e2021-05-06 08:10:58 +01003438 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3439 .Authorization(TAG_NO_AUTH_REQUIRED)
3440 .EcdsaSigningKey(curve)
3441 .Digest(digests)
3442 .SetDefaultValidity());
3443 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3444 if (error != ErrorCode::OK) {
3445 continue;
3446 }
3447
3448 for (auto digest : digests) {
3449 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3450 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3451 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3452 }
3453
3454 auto rc = DeleteKey();
3455 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3456 }
3457}
3458
3459/*
Selene Huang31ab4042020-04-29 04:22:39 -07003460 * SigningOperationsTest.EcdsaAllCurves
3461 *
David Drysdale42fe1892021-10-14 14:43:46 +01003462 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003463 */
3464TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3465 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003466 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3467 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003468 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3469 .Authorization(TAG_NO_AUTH_REQUIRED)
3470 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003471 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003472 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003473 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3474 if (error != ErrorCode::OK) continue;
3475
3476 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003477 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003478 CheckedDeleteKey();
3479 }
3480}
3481
3482/*
David Drysdale42fe1892021-10-14 14:43:46 +01003483 * SigningOperationsTest.EcdsaCurve25519
3484 *
3485 * Verifies that ECDSA operations succeed with curve25519.
3486 */
3487TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3488 if (!Curve25519Supported()) {
3489 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3490 }
3491
3492 EcCurve curve = EcCurve::CURVE_25519;
3493 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3494 .Authorization(TAG_NO_AUTH_REQUIRED)
3495 .EcdsaSigningKey(curve)
3496 .Digest(Digest::NONE)
3497 .SetDefaultValidity());
3498 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3499
3500 string message(1024, 'a');
3501 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3502 CheckedDeleteKey();
3503}
3504
3505/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003506 * SigningOperationsTest.EcdsaCurve25519MaxSize
3507 *
3508 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3509 */
3510TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3511 if (!Curve25519Supported()) {
3512 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3513 }
3514
3515 EcCurve curve = EcCurve::CURVE_25519;
3516 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3517 .Authorization(TAG_NO_AUTH_REQUIRED)
3518 .EcdsaSigningKey(curve)
3519 .Digest(Digest::NONE)
3520 .SetDefaultValidity());
3521 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3522
3523 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3524
3525 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3526 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3527 string message(msg_size, 'a');
3528
3529 // Attempt to sign via Begin+Finish.
3530 AuthorizationSet out_params;
3531 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3532 EXPECT_TRUE(out_params.empty());
3533 string signature;
3534 auto result = Finish(message, &signature);
3535 EXPECT_EQ(result, ErrorCode::OK);
3536 LocalVerifyMessage(message, signature, params);
3537
3538 // Attempt to sign via Begin+Update+Finish
3539 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3540 EXPECT_TRUE(out_params.empty());
3541 string output;
3542 result = Update(message, &output);
3543 EXPECT_EQ(result, ErrorCode::OK);
3544 EXPECT_EQ(output.size(), 0);
3545 string signature2;
3546 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3547 LocalVerifyMessage(message, signature2, params);
3548 }
3549
3550 CheckedDeleteKey();
3551}
3552
3553/*
3554 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3555 *
3556 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3557 */
3558TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3559 if (!Curve25519Supported()) {
3560 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3561 }
3562
3563 EcCurve curve = EcCurve::CURVE_25519;
3564 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3565 .Authorization(TAG_NO_AUTH_REQUIRED)
3566 .EcdsaSigningKey(curve)
3567 .Digest(Digest::NONE)
3568 .SetDefaultValidity());
3569 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3570
3571 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3572
3573 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3574 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3575 string message(msg_size, 'a');
3576
3577 // Attempt to sign via Begin+Finish.
3578 AuthorizationSet out_params;
3579 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3580 EXPECT_TRUE(out_params.empty());
3581 string signature;
3582 auto result = Finish(message, &signature);
3583 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3584
3585 // Attempt to sign via Begin+Update (but never get to Finish)
3586 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3587 EXPECT_TRUE(out_params.empty());
3588 string output;
3589 result = Update(message, &output);
3590 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3591 }
3592
3593 CheckedDeleteKey();
3594}
3595
3596/*
Selene Huang31ab4042020-04-29 04:22:39 -07003597 * SigningOperationsTest.EcdsaNoDigestHugeData
3598 *
3599 * Verifies that ECDSA operations support very large messages, even without digesting. This
3600 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3601 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3602 * the framework.
3603 */
3604TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3605 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3606 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003607 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003608 .Digest(Digest::NONE)
3609 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003610 string message(1 * 1024, 'a');
3611 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3612}
3613
3614/*
3615 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3616 *
3617 * Verifies that using an EC key requires the correct app ID/data.
3618 */
3619TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3620 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3621 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003622 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003623 .Digest(Digest::NONE)
3624 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003625 .Authorization(TAG_APPLICATION_DATA, "appdata")
3626 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003627
3628 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3629
Selene Huang31ab4042020-04-29 04:22:39 -07003630 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3631 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3632 AbortIfNeeded();
3633 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3634 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3635 .Digest(Digest::NONE)
3636 .Authorization(TAG_APPLICATION_ID, "clientid")));
3637 AbortIfNeeded();
3638 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3639 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3640 .Digest(Digest::NONE)
3641 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3642 AbortIfNeeded();
3643 EXPECT_EQ(ErrorCode::OK,
3644 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3645 .Digest(Digest::NONE)
3646 .Authorization(TAG_APPLICATION_DATA, "appdata")
3647 .Authorization(TAG_APPLICATION_ID, "clientid")));
3648 AbortIfNeeded();
3649}
3650
3651/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003652 * SigningOperationsTest.EcdsaIncompatibleDigest
3653 *
3654 * Verifies that using an EC key requires compatible digest.
3655 */
3656TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3657 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3658 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003659 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003660 .Digest(Digest::NONE)
3661 .Digest(Digest::SHA1)
3662 .SetDefaultValidity()));
3663 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3664 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3665 AbortIfNeeded();
3666}
3667
3668/*
Selene Huang31ab4042020-04-29 04:22:39 -07003669 * SigningOperationsTest.AesEcbSign
3670 *
3671 * Verifies that attempts to use AES keys to sign fail in the correct way.
3672 */
3673TEST_P(SigningOperationsTest, AesEcbSign) {
3674 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3675 .Authorization(TAG_NO_AUTH_REQUIRED)
3676 .SigningKey()
3677 .AesEncryptionKey(128)
3678 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3679
3680 AuthorizationSet out_params;
3681 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3682 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3683 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3684 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3685}
3686
3687/*
3688 * SigningOperationsTest.HmacAllDigests
3689 *
3690 * Verifies that HMAC works with all digests.
3691 */
3692TEST_P(SigningOperationsTest, HmacAllDigests) {
3693 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003694 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003695 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3696 .Authorization(TAG_NO_AUTH_REQUIRED)
3697 .HmacKey(128)
3698 .Digest(digest)
3699 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3700 << "Failed to create HMAC key with digest " << digest;
3701 string message = "12345678901234567890123456789012";
3702 string signature = MacMessage(message, digest, 160);
3703 EXPECT_EQ(160U / 8U, signature.size())
3704 << "Failed to sign with HMAC key with digest " << digest;
3705 CheckedDeleteKey();
3706 }
3707}
3708
3709/*
3710 * SigningOperationsTest.HmacSha256TooLargeMacLength
3711 *
3712 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3713 * digest size.
3714 */
3715TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3716 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3717 .Authorization(TAG_NO_AUTH_REQUIRED)
3718 .HmacKey(128)
3719 .Digest(Digest::SHA_2_256)
3720 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3721 AuthorizationSet output_params;
3722 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3723 AuthorizationSetBuilder()
3724 .Digest(Digest::SHA_2_256)
3725 .Authorization(TAG_MAC_LENGTH, 264),
3726 &output_params));
3727}
3728
3729/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003730 * SigningOperationsTest.HmacSha256InvalidMacLength
3731 *
3732 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3733 * not a multiple of 8.
3734 */
3735TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3736 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3737 .Authorization(TAG_NO_AUTH_REQUIRED)
3738 .HmacKey(128)
3739 .Digest(Digest::SHA_2_256)
3740 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3741 AuthorizationSet output_params;
3742 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3743 AuthorizationSetBuilder()
3744 .Digest(Digest::SHA_2_256)
3745 .Authorization(TAG_MAC_LENGTH, 161),
3746 &output_params));
3747}
3748
3749/*
Selene Huang31ab4042020-04-29 04:22:39 -07003750 * SigningOperationsTest.HmacSha256TooSmallMacLength
3751 *
3752 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3753 * specified minimum MAC length.
3754 */
3755TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3756 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3757 .Authorization(TAG_NO_AUTH_REQUIRED)
3758 .HmacKey(128)
3759 .Digest(Digest::SHA_2_256)
3760 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3761 AuthorizationSet output_params;
3762 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3763 AuthorizationSetBuilder()
3764 .Digest(Digest::SHA_2_256)
3765 .Authorization(TAG_MAC_LENGTH, 120),
3766 &output_params));
3767}
3768
3769/*
3770 * SigningOperationsTest.HmacRfc4231TestCase3
3771 *
3772 * Validates against the test vectors from RFC 4231 test case 3.
3773 */
3774TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3775 string key(20, 0xaa);
3776 string message(50, 0xdd);
3777 uint8_t sha_224_expected[] = {
3778 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3779 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3780 };
3781 uint8_t sha_256_expected[] = {
3782 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3783 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3784 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3785 };
3786 uint8_t sha_384_expected[] = {
3787 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3788 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3789 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3790 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3791 };
3792 uint8_t sha_512_expected[] = {
3793 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3794 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3795 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3796 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3797 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3798 };
3799
3800 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3801 if (SecLevel() != SecurityLevel::STRONGBOX) {
3802 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3803 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3804 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3805 }
3806}
3807
3808/*
3809 * SigningOperationsTest.HmacRfc4231TestCase5
3810 *
3811 * Validates against the test vectors from RFC 4231 test case 5.
3812 */
3813TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3814 string key(20, 0x0c);
3815 string message = "Test With Truncation";
3816
3817 uint8_t sha_224_expected[] = {
3818 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3819 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3820 };
3821 uint8_t sha_256_expected[] = {
3822 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3823 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3824 };
3825 uint8_t sha_384_expected[] = {
3826 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3827 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3828 };
3829 uint8_t sha_512_expected[] = {
3830 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3831 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3832 };
3833
3834 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3835 if (SecLevel() != SecurityLevel::STRONGBOX) {
3836 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3837 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3838 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3839 }
3840}
3841
3842INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3843
3844typedef KeyMintAidlTestBase VerificationOperationsTest;
3845
3846/*
Selene Huang31ab4042020-04-29 04:22:39 -07003847 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3848 *
3849 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3850 */
3851TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3852 string key_material = "HelloThisIsAKey";
3853
3854 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003855 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003856 EXPECT_EQ(ErrorCode::OK,
3857 ImportKey(AuthorizationSetBuilder()
3858 .Authorization(TAG_NO_AUTH_REQUIRED)
3859 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3860 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3861 .Digest(Digest::SHA_2_256)
3862 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3863 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003864 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003865 EXPECT_EQ(ErrorCode::OK,
3866 ImportKey(AuthorizationSetBuilder()
3867 .Authorization(TAG_NO_AUTH_REQUIRED)
3868 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3869 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3870 .Digest(Digest::SHA_2_256)
3871 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3872 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003873 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003874
3875 string message = "This is a message.";
3876 string signature = SignMessage(
3877 signing_key, message,
3878 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3879
3880 // Signing key should not work.
3881 AuthorizationSet out_params;
3882 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3883 Begin(KeyPurpose::VERIFY, signing_key,
3884 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3885
3886 // Verification key should work.
3887 VerifyMessage(verification_key, message, signature,
3888 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Selene Huang31ab4042020-04-29 04:22:39 -07003889}
3890
Prashant Patildec9fdc2021-12-08 15:25:47 +00003891/*
3892 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3893 *
3894 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3895 */
3896TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3897 string key_material = "HelloThisIsAKey";
3898
3899 vector<uint8_t> signing_key, verification_key;
3900 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3901 EXPECT_EQ(ErrorCode::OK,
3902 ImportKey(AuthorizationSetBuilder()
3903 .Authorization(TAG_NO_AUTH_REQUIRED)
3904 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3905 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3906 .Digest(Digest::SHA_2_256)
3907 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3908 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003909 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003910 EXPECT_EQ(ErrorCode::OK,
3911 ImportKey(AuthorizationSetBuilder()
3912 .Authorization(TAG_NO_AUTH_REQUIRED)
3913 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3914 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3915 .Digest(Digest::SHA_2_256)
3916 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3917 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003918 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003919
3920 string message = "This is a message.";
3921 string signature = SignMessage(
3922 signing_key, message,
3923 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3924
3925 AuthorizationSet begin_out_params;
3926 ASSERT_EQ(ErrorCode::OK,
3927 Begin(KeyPurpose::VERIFY, verification_key,
3928 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3929
3930 string corruptMessage = "This is b message."; // Corrupted message
3931 string output;
3932 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3933
3934 ASSERT_EQ(ErrorCode::OK,
3935 Begin(KeyPurpose::VERIFY, verification_key,
3936 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3937
3938 signature[0] += 1; // Corrupt a signature
3939 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
Prashant Patildec9fdc2021-12-08 15:25:47 +00003940}
3941
Selene Huang31ab4042020-04-29 04:22:39 -07003942INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3943
3944typedef KeyMintAidlTestBase ExportKeyTest;
3945
3946/*
3947 * ExportKeyTest.RsaUnsupportedKeyFormat
3948 *
3949 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3950 */
3951// TODO(seleneh) add ExportKey to GenerateKey
3952// check result
3953
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003954class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003955 public:
3956 template <TagType tag_type, Tag tag, typename ValueT>
3957 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3958 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003959 for (auto& entry : key_characteristics_) {
3960 if (entry.securityLevel == SecLevel()) {
3961 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3962 << "Tag " << tag << " with value " << expected
3963 << " not found at security level" << entry.securityLevel;
3964 } else {
3965 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3966 << "Tag " << tag << " found at security level " << entry.securityLevel;
3967 }
Selene Huang31ab4042020-04-29 04:22:39 -07003968 }
3969 }
3970
3971 void CheckOrigin() {
3972 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003973 // Origin isn't a crypto param, but it always lives with them.
3974 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003975 }
3976};
3977
3978/*
3979 * ImportKeyTest.RsaSuccess
3980 *
3981 * Verifies that importing and using an RSA key pair works correctly.
3982 */
3983TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003984 uint32_t key_size;
3985 string key;
3986
3987 if (SecLevel() == SecurityLevel::STRONGBOX) {
3988 key_size = 2048;
3989 key = rsa_2048_key;
3990 } else {
3991 key_size = 1024;
3992 key = rsa_key;
3993 }
3994
Selene Huang31ab4042020-04-29 04:22:39 -07003995 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3996 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003997 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003998 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003999 .Padding(PaddingMode::RSA_PSS)
4000 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07004001 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07004002
4003 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07004004 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07004005 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4006 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4007 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4008 CheckOrigin();
4009
4010 string message(1024 / 8, 'a');
4011 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4012 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004013 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004014}
4015
4016/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004017 * ImportKeyTest.RsaSuccessWithoutParams
4018 *
4019 * Verifies that importing and using an RSA key pair without specifying parameters
4020 * works correctly.
4021 */
4022TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
4023 uint32_t key_size;
4024 string key;
4025
4026 if (SecLevel() == SecurityLevel::STRONGBOX) {
4027 key_size = 2048;
4028 key = rsa_2048_key;
4029 } else {
4030 key_size = 1024;
4031 key = rsa_key;
4032 }
4033
4034 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4035 .Authorization(TAG_NO_AUTH_REQUIRED)
4036 .SigningKey()
4037 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4038 .Digest(Digest::SHA_2_256)
4039 .Padding(PaddingMode::RSA_PSS)
4040 .SetDefaultValidity(),
4041 KeyFormat::PKCS8, key));
4042
4043 // Key size and public exponent are determined from the imported key material.
4044 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4045 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4046
4047 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4048 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4049 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4050 CheckOrigin();
4051
4052 string message(1024 / 8, 'a');
4053 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4054 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004055 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004056}
4057
4058/*
Selene Huang31ab4042020-04-29 04:22:39 -07004059 * ImportKeyTest.RsaKeySizeMismatch
4060 *
4061 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4062 * correct way.
4063 */
4064TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4065 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4066 ImportKey(AuthorizationSetBuilder()
4067 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4068 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004069 .Padding(PaddingMode::NONE)
4070 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004071 KeyFormat::PKCS8, rsa_key));
4072}
4073
4074/*
4075 * ImportKeyTest.RsaPublicExponentMismatch
4076 *
4077 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4078 * fails in the correct way.
4079 */
4080TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4081 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4082 ImportKey(AuthorizationSetBuilder()
4083 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4084 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004085 .Padding(PaddingMode::NONE)
4086 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004087 KeyFormat::PKCS8, rsa_key));
4088}
4089
4090/*
David Drysdalee60248c2021-10-04 12:54:13 +01004091 * ImportKeyTest.RsaAttestMultiPurposeFail
4092 *
4093 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4094 */
4095TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004096 if (AidlVersion() < 2) {
4097 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4098 // with other key purposes. However, this was not checked at the time
4099 // so we can only be strict about checking this for implementations of KeyMint
4100 // version 2 and above.
4101 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4102 }
David Drysdalee60248c2021-10-04 12:54:13 +01004103 uint32_t key_size = 2048;
4104 string key = rsa_2048_key;
4105
4106 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4107 ImportKey(AuthorizationSetBuilder()
4108 .Authorization(TAG_NO_AUTH_REQUIRED)
4109 .RsaSigningKey(key_size, 65537)
4110 .AttestKey()
4111 .Digest(Digest::SHA_2_256)
4112 .Padding(PaddingMode::RSA_PSS)
4113 .SetDefaultValidity(),
4114 KeyFormat::PKCS8, key));
4115}
4116
4117/*
Selene Huang31ab4042020-04-29 04:22:39 -07004118 * ImportKeyTest.EcdsaSuccess
4119 *
4120 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4121 */
4122TEST_P(ImportKeyTest, EcdsaSuccess) {
4123 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4124 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004125 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004126 .Digest(Digest::SHA_2_256)
4127 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004128 KeyFormat::PKCS8, ec_256_key));
4129
4130 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004131 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4132 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4133
4134 CheckOrigin();
4135
4136 string message(32, 'a');
4137 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4138 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004139 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004140}
4141
4142/*
David Drysdale9b8d75e2023-09-05 15:16:47 +01004143 * ImportKeyTest.EcdsaSuccessCurveNotSpecified
4144 *
4145 * Verifies that importing and using an ECDSA P-256 key pair works correctly
4146 * when the EC_CURVE is not explicitly specified.
4147 */
4148TEST_P(ImportKeyTest, EcdsaSuccessCurveNotSpecified) {
David Drysdale1405dbc2023-11-02 09:26:44 +00004149 if (get_vsr_api_level() < __ANDROID_API_V__) {
David Drysdale9b8d75e2023-09-05 15:16:47 +01004150 /*
David Drysdale1405dbc2023-11-02 09:26:44 +00004151 * The KeyMint spec was previously not clear as to whether EC_CURVE was optional on import
4152 * of EC keys. However, this was not checked at the time so we can only be strict about
4153 * checking this for implementations at VSR-V or later.
David Drysdale9b8d75e2023-09-05 15:16:47 +01004154 */
David Drysdale1405dbc2023-11-02 09:26:44 +00004155 GTEST_SKIP() << "Skipping EC_CURVE on import only strict >= VSR-V";
David Drysdale9b8d75e2023-09-05 15:16:47 +01004156 }
4157
4158 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4159 .Authorization(TAG_NO_AUTH_REQUIRED)
4160 .Authorization(TAG_ALGORITHM, Algorithm::EC)
4161 .SigningKey()
4162 .Digest(Digest::SHA_2_256)
4163 .SetDefaultValidity(),
4164 KeyFormat::PKCS8, ec_256_key));
4165
4166 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4167 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4168 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4169
4170 CheckOrigin();
4171
4172 string message(32, 'a');
4173 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4174 string signature = SignMessage(message, params);
4175 LocalVerifyMessage(message, signature, params);
4176}
4177
4178/*
Selene Huang31ab4042020-04-29 04:22:39 -07004179 * ImportKeyTest.EcdsaP256RFC5915Success
4180 *
4181 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4182 * correctly.
4183 */
4184TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4185 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4186 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004187 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004188 .Digest(Digest::SHA_2_256)
4189 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004190 KeyFormat::PKCS8, ec_256_key_rfc5915));
4191
4192 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004193 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4194 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4195
4196 CheckOrigin();
4197
4198 string message(32, 'a');
4199 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4200 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004201 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004202}
4203
4204/*
4205 * ImportKeyTest.EcdsaP256SEC1Success
4206 *
4207 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4208 */
4209TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4210 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4211 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004212 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004213 .Digest(Digest::SHA_2_256)
4214 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004215 KeyFormat::PKCS8, ec_256_key_sec1));
4216
4217 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004218 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4219 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4220
4221 CheckOrigin();
4222
4223 string message(32, 'a');
4224 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4225 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004226 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004227}
4228
4229/*
4230 * ImportKeyTest.Ecdsa521Success
4231 *
4232 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4233 */
4234TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004235 if (SecLevel() == SecurityLevel::STRONGBOX) {
4236 GTEST_SKIP() << "Test not applicable to StrongBox device";
4237 }
Selene Huang31ab4042020-04-29 04:22:39 -07004238 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4239 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004240 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004241 .Digest(Digest::SHA_2_256)
4242 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004243 KeyFormat::PKCS8, ec_521_key));
4244
4245 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004246 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4247 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4248 CheckOrigin();
4249
4250 string message(32, 'a');
4251 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4252 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004253 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004254}
4255
4256/*
Selene Huang31ab4042020-04-29 04:22:39 -07004257 * ImportKeyTest.EcdsaCurveMismatch
4258 *
4259 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4260 * the correct way.
4261 */
4262TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4263 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4264 ImportKey(AuthorizationSetBuilder()
4265 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004266 .Digest(Digest::NONE)
4267 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004268 KeyFormat::PKCS8, ec_256_key));
4269}
4270
4271/*
David Drysdalee60248c2021-10-04 12:54:13 +01004272 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4273 *
4274 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4275 */
4276TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004277 if (AidlVersion() < 2) {
4278 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4279 // with other key purposes. However, this was not checked at the time
4280 // so we can only be strict about checking this for implementations of KeyMint
4281 // version 2 and above.
4282 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4283 }
David Drysdalee60248c2021-10-04 12:54:13 +01004284 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4285 ImportKey(AuthorizationSetBuilder()
4286 .Authorization(TAG_NO_AUTH_REQUIRED)
4287 .EcdsaSigningKey(EcCurve::P_256)
4288 .AttestKey()
4289 .Digest(Digest::SHA_2_256)
4290 .SetDefaultValidity(),
4291 KeyFormat::PKCS8, ec_256_key));
4292}
4293
4294/*
David Drysdale42fe1892021-10-14 14:43:46 +01004295 * ImportKeyTest.Ed25519RawSuccess
4296 *
4297 * Verifies that importing and using a raw Ed25519 private key works correctly.
4298 */
4299TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4300 if (!Curve25519Supported()) {
4301 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4302 }
4303
4304 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4305 .Authorization(TAG_NO_AUTH_REQUIRED)
4306 .EcdsaSigningKey(EcCurve::CURVE_25519)
4307 .Digest(Digest::NONE)
4308 .SetDefaultValidity(),
4309 KeyFormat::RAW, ed25519_key));
4310 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4311 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4312 CheckOrigin();
4313
4314 // The returned cert should hold the correct public key.
4315 ASSERT_GT(cert_chain_.size(), 0);
4316 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4317 ASSERT_NE(kmKeyCert, nullptr);
4318 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4319 ASSERT_NE(kmPubKey.get(), nullptr);
4320 size_t kmPubKeySize = 32;
4321 uint8_t kmPubKeyData[32];
4322 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4323 ASSERT_EQ(kmPubKeySize, 32);
4324 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4325
4326 string message(32, 'a');
4327 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4328 string signature = SignMessage(message, params);
4329 LocalVerifyMessage(message, signature, params);
4330}
4331
4332/*
4333 * ImportKeyTest.Ed25519Pkcs8Success
4334 *
4335 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4336 */
4337TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4338 if (!Curve25519Supported()) {
4339 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4340 }
4341
4342 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4343 .Authorization(TAG_NO_AUTH_REQUIRED)
4344 .EcdsaSigningKey(EcCurve::CURVE_25519)
4345 .Digest(Digest::NONE)
4346 .SetDefaultValidity(),
4347 KeyFormat::PKCS8, ed25519_pkcs8_key));
4348 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4349 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4350 CheckOrigin();
4351
4352 // The returned cert should hold the correct public key.
4353 ASSERT_GT(cert_chain_.size(), 0);
4354 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4355 ASSERT_NE(kmKeyCert, nullptr);
4356 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4357 ASSERT_NE(kmPubKey.get(), nullptr);
4358 size_t kmPubKeySize = 32;
4359 uint8_t kmPubKeyData[32];
4360 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4361 ASSERT_EQ(kmPubKeySize, 32);
4362 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4363
4364 string message(32, 'a');
4365 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4366 string signature = SignMessage(message, params);
4367 LocalVerifyMessage(message, signature, params);
4368}
4369
4370/*
4371 * ImportKeyTest.Ed25519CurveMismatch
4372 *
4373 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4374 * the correct way.
4375 */
4376TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4377 if (!Curve25519Supported()) {
4378 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4379 }
4380
4381 ASSERT_NE(ErrorCode::OK,
4382 ImportKey(AuthorizationSetBuilder()
4383 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4384 .Digest(Digest::NONE)
4385 .SetDefaultValidity(),
4386 KeyFormat::RAW, ed25519_key));
4387}
4388
4389/*
4390 * ImportKeyTest.Ed25519FormatMismatch
4391 *
4392 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4393 */
4394TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4395 if (!Curve25519Supported()) {
4396 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4397 }
4398
4399 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4400 .EcdsaSigningKey(EcCurve::CURVE_25519)
4401 .Digest(Digest::NONE)
4402 .SetDefaultValidity(),
4403 KeyFormat::PKCS8, ed25519_key));
4404 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4405 .EcdsaSigningKey(EcCurve::CURVE_25519)
4406 .Digest(Digest::NONE)
4407 .SetDefaultValidity(),
4408 KeyFormat::RAW, ed25519_pkcs8_key));
4409}
4410
4411/*
4412 * ImportKeyTest.Ed25519PurposeMismatch
4413 *
4414 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4415 */
4416TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4417 if (!Curve25519Supported()) {
4418 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4419 }
4420
4421 // Can't have both SIGN and ATTEST_KEY
4422 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4423 .EcdsaSigningKey(EcCurve::CURVE_25519)
4424 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4425 .Digest(Digest::NONE)
4426 .SetDefaultValidity(),
4427 KeyFormat::RAW, ed25519_key));
4428 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4429 // PKCS#8 format and so includes an OID).
4430 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4431 .EcdsaKey(EcCurve::CURVE_25519)
4432 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4433 .Digest(Digest::NONE)
4434 .SetDefaultValidity(),
4435 KeyFormat::PKCS8, ed25519_pkcs8_key));
4436}
4437
4438/*
4439 * ImportKeyTest.X25519RawSuccess
4440 *
4441 * Verifies that importing and using a raw X25519 private key works correctly.
4442 */
4443TEST_P(ImportKeyTest, X25519RawSuccess) {
4444 if (!Curve25519Supported()) {
4445 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4446 }
4447
4448 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4449 .Authorization(TAG_NO_AUTH_REQUIRED)
4450 .EcdsaKey(EcCurve::CURVE_25519)
4451 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4452 .SetDefaultValidity(),
4453 KeyFormat::RAW, x25519_key));
4454
4455 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4456 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4457 CheckOrigin();
4458}
4459
4460/*
4461 * ImportKeyTest.X25519Pkcs8Success
4462 *
4463 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4464 */
4465TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4466 if (!Curve25519Supported()) {
4467 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4468 }
4469
4470 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4471 .Authorization(TAG_NO_AUTH_REQUIRED)
4472 .EcdsaKey(EcCurve::CURVE_25519)
4473 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4474 .SetDefaultValidity(),
4475 KeyFormat::PKCS8, x25519_pkcs8_key));
4476
4477 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4478 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4479 CheckOrigin();
4480}
4481
4482/*
4483 * ImportKeyTest.X25519CurveMismatch
4484 *
4485 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4486 * the correct way.
4487 */
4488TEST_P(ImportKeyTest, X25519CurveMismatch) {
4489 if (!Curve25519Supported()) {
4490 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4491 }
4492
4493 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4494 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4495 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4496 .SetDefaultValidity(),
4497 KeyFormat::RAW, x25519_key));
4498}
4499
4500/*
4501 * ImportKeyTest.X25519FormatMismatch
4502 *
4503 * Verifies that importing an X25519 key with an invalid format fails.
4504 */
4505TEST_P(ImportKeyTest, X25519FormatMismatch) {
4506 if (!Curve25519Supported()) {
4507 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4508 }
4509
4510 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4511 .EcdsaKey(EcCurve::CURVE_25519)
4512 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4513 .SetDefaultValidity(),
4514 KeyFormat::PKCS8, x25519_key));
4515 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4516 .EcdsaKey(EcCurve::CURVE_25519)
4517 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4518 .SetDefaultValidity(),
4519 KeyFormat::RAW, x25519_pkcs8_key));
4520}
4521
4522/*
4523 * ImportKeyTest.X25519PurposeMismatch
4524 *
4525 * Verifies that importing an X25519 key pair with an invalid format fails.
4526 */
4527TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4528 if (!Curve25519Supported()) {
4529 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4530 }
4531
4532 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4533 .EcdsaKey(EcCurve::CURVE_25519)
4534 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4535 .SetDefaultValidity(),
4536 KeyFormat::PKCS8, x25519_pkcs8_key));
4537 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4538 .EcdsaSigningKey(EcCurve::CURVE_25519)
4539 .SetDefaultValidity(),
4540 KeyFormat::PKCS8, x25519_pkcs8_key));
4541}
4542
4543/*
Selene Huang31ab4042020-04-29 04:22:39 -07004544 * ImportKeyTest.AesSuccess
4545 *
4546 * Verifies that importing and using an AES key works.
4547 */
4548TEST_P(ImportKeyTest, AesSuccess) {
4549 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4550 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4551 .Authorization(TAG_NO_AUTH_REQUIRED)
4552 .AesEncryptionKey(key.size() * 8)
4553 .EcbMode()
4554 .Padding(PaddingMode::PKCS7),
4555 KeyFormat::RAW, key));
4556
4557 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4558 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4559 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4560 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4561 CheckOrigin();
4562
4563 string message = "Hello World!";
4564 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4565 string ciphertext = EncryptMessage(message, params);
4566 string plaintext = DecryptMessage(ciphertext, params);
4567 EXPECT_EQ(message, plaintext);
4568}
4569
4570/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004571 * ImportKeyTest.AesFailure
4572 *
4573 * Verifies that importing an invalid AES key fails.
4574 */
4575TEST_P(ImportKeyTest, AesFailure) {
4576 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4577 uint32_t bitlen = key.size() * 8;
4578 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004579 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004580 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004581 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004582 .Authorization(TAG_NO_AUTH_REQUIRED)
4583 .AesEncryptionKey(key_size)
4584 .EcbMode()
4585 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004586 KeyFormat::RAW, key);
4587 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004588 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4589 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004590 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004591
4592 // Explicit key size matches that of the provided key, but it's not a valid size.
4593 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4594 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4595 ImportKey(AuthorizationSetBuilder()
4596 .Authorization(TAG_NO_AUTH_REQUIRED)
4597 .AesEncryptionKey(long_key.size() * 8)
4598 .EcbMode()
4599 .Padding(PaddingMode::PKCS7),
4600 KeyFormat::RAW, long_key));
4601 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4602 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4603 ImportKey(AuthorizationSetBuilder()
4604 .Authorization(TAG_NO_AUTH_REQUIRED)
4605 .AesEncryptionKey(short_key.size() * 8)
4606 .EcbMode()
4607 .Padding(PaddingMode::PKCS7),
4608 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004609}
4610
4611/*
4612 * ImportKeyTest.TripleDesSuccess
4613 *
4614 * Verifies that importing and using a 3DES key works.
4615 */
4616TEST_P(ImportKeyTest, TripleDesSuccess) {
4617 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4618 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4619 .Authorization(TAG_NO_AUTH_REQUIRED)
4620 .TripleDesEncryptionKey(168)
4621 .EcbMode()
4622 .Padding(PaddingMode::PKCS7),
4623 KeyFormat::RAW, key));
4624
4625 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4626 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4627 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4628 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4629 CheckOrigin();
4630
4631 string message = "Hello World!";
4632 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4633 string ciphertext = EncryptMessage(message, params);
4634 string plaintext = DecryptMessage(ciphertext, params);
4635 EXPECT_EQ(message, plaintext);
4636}
4637
4638/*
4639 * ImportKeyTest.TripleDesFailure
4640 *
4641 * Verifies that importing an invalid 3DES key fails.
4642 */
4643TEST_P(ImportKeyTest, TripleDesFailure) {
4644 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004645 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004646 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004647 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004648 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004649 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004650 .Authorization(TAG_NO_AUTH_REQUIRED)
4651 .TripleDesEncryptionKey(key_size)
4652 .EcbMode()
4653 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004654 KeyFormat::RAW, key);
4655 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004656 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4657 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004658 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004659 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004660 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004661 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4662 ImportKey(AuthorizationSetBuilder()
4663 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004664 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004665 .EcbMode()
4666 .Padding(PaddingMode::PKCS7),
4667 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004668 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004669 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4670 ImportKey(AuthorizationSetBuilder()
4671 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004672 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004673 .EcbMode()
4674 .Padding(PaddingMode::PKCS7),
4675 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004676}
4677
4678/*
4679 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004680 *
4681 * Verifies that importing and using an HMAC key works.
4682 */
4683TEST_P(ImportKeyTest, HmacKeySuccess) {
4684 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4685 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4686 .Authorization(TAG_NO_AUTH_REQUIRED)
4687 .HmacKey(key.size() * 8)
4688 .Digest(Digest::SHA_2_256)
4689 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4690 KeyFormat::RAW, key));
4691
4692 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4693 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4694 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4695 CheckOrigin();
4696
4697 string message = "Hello World!";
4698 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4699 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4700}
4701
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004702/*
4703 * ImportKeyTest.GetKeyCharacteristics
4704 *
4705 * Verifies that imported keys have the correct characteristics.
4706 */
4707TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4708 vector<uint8_t> key_blob;
4709 vector<KeyCharacteristics> key_characteristics;
4710 auto base_builder = AuthorizationSetBuilder()
4711 .Padding(PaddingMode::NONE)
4712 .Authorization(TAG_NO_AUTH_REQUIRED)
4713 .SetDefaultValidity();
4714 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4715 Algorithm::TRIPLE_DES};
4716 ErrorCode result;
4717 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4718 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4719 for (auto alg : algorithms) {
4720 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4721 AuthorizationSetBuilder builder(base_builder);
4722 switch (alg) {
4723 case Algorithm::RSA:
4724 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4725
4726 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4727 &key_characteristics);
4728 break;
4729 case Algorithm::EC:
4730 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4731 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4732 &key_characteristics);
4733 break;
4734 case Algorithm::HMAC:
4735 builder.HmacKey(128)
4736 .Digest(Digest::SHA_2_256)
4737 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4738 result =
4739 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4740 break;
4741 case Algorithm::AES:
4742 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4743 result =
4744 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4745 break;
4746 case Algorithm::TRIPLE_DES:
4747 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4748 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4749 &key_characteristics);
4750 break;
4751 default:
4752 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4753 continue;
4754 }
4755 ASSERT_EQ(ErrorCode::OK, result);
4756 CheckCharacteristics(key_blob, key_characteristics);
4757 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4758 }
4759}
4760
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004761/*
4762 * ImportKeyTest.RsaOaepMGFDigestSuccess
4763 *
4764 * Include MGF-Digest explicitly in import key authorization list.
4765 * Test should import RSA key with OAEP padding and mgf-digests and verify that imported key
4766 * should have the correct characteristics.
4767 */
4768TEST_P(ImportKeyTest, RsaOaepMGFDigestSuccess) {
Prashant Patil2114dca2023-09-21 14:57:10 +00004769 // There was no test to assert that MGF1 digest was present in generated/imported key
4770 // characteristics before Keymint V3, so there are some Keymint implementations where
4771 // this test case fails(b/297306437), hence this test is skipped for Keymint < 3.
4772 if (AidlVersion() < 3) {
4773 GTEST_SKIP() << "Test not applicable to Keymint < V3";
4774 }
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004775 auto mgf_digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4776 size_t key_size = 2048;
4777
4778 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4779 .OaepMGFDigest(mgf_digests)
4780 .Authorization(TAG_NO_AUTH_REQUIRED)
4781 .RsaEncryptionKey(key_size, 65537)
4782 .Digest(Digest::SHA_2_256)
4783 .Padding(PaddingMode::RSA_OAEP)
4784 .SetDefaultValidity(),
4785 KeyFormat::PKCS8, rsa_2048_key));
4786
4787 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4788 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4789 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4790 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4791 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4792 CheckOrigin();
4793
4794 // Make sure explicitly specified mgf-digests exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00004795 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digests, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004796
4797 string message = "Hello";
4798
4799 for (auto digest : mgf_digests) {
4800 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4801 auto params = AuthorizationSetBuilder()
4802 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4803 .Digest(Digest::SHA_2_256)
4804 .Padding(PaddingMode::RSA_OAEP);
4805 string ciphertext1 = LocalRsaEncryptMessage(message, params);
4806 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4807 EXPECT_EQ(key_size / 8, ciphertext1.size());
4808
4809 string ciphertext2 = LocalRsaEncryptMessage(message, params);
4810 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4811 EXPECT_EQ(key_size / 8, ciphertext2.size());
4812
4813 // OAEP randomizes padding so every result should be different (with astronomically high
4814 // probability).
4815 EXPECT_NE(ciphertext1, ciphertext2);
4816
4817 string plaintext1 = DecryptMessage(ciphertext1, params);
4818 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4819 string plaintext2 = DecryptMessage(ciphertext2, params);
4820 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4821
4822 // Decrypting corrupted ciphertext should fail.
4823 size_t offset_to_corrupt = ciphertext1.size() - 1;
4824 char corrupt_byte = ~ciphertext1[offset_to_corrupt];
4825 ciphertext1[offset_to_corrupt] = corrupt_byte;
4826
4827 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4828 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04004829 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004830 EXPECT_EQ(0U, result.size());
4831 }
4832}
4833
4834/*
4835 * ImportKeyTest.RsaOaepMGFDigestDefaultSuccess
4836 *
4837 * Don't specify MGF-Digest explicitly in import key authorization list.
4838 * Test should import RSA key with OAEP padding and default mgf-digest (SHA1) and
4839 * verify that imported key should have the correct characteristics. Default
4840 * mgf-digest shouldn't be included in key charecteristics.
4841 */
4842TEST_P(ImportKeyTest, RsaOaepMGFDigestDefaultSuccess) {
4843 size_t key_size = 2048;
4844 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4845 .Authorization(TAG_NO_AUTH_REQUIRED)
4846 .RsaEncryptionKey(key_size, 65537)
4847 .Digest(Digest::SHA_2_256)
4848 .Padding(PaddingMode::RSA_OAEP)
4849 .SetDefaultValidity(),
4850 KeyFormat::PKCS8, rsa_2048_key));
4851
4852 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4853 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4854 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4855 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4856 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4857 CheckOrigin();
4858
Prashant Patil2114dca2023-09-21 14:57:10 +00004859 vector defaultDigest = {Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004860 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00004861 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004862}
4863
Selene Huang31ab4042020-04-29 04:22:39 -07004864INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4865
4866auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004867 // IKeyMintDevice.aidl
4868 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4869 "020100" // INTEGER length 1 value 0x00 (version)
4870 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4871 "934bf94e2aa28a3f83c9f79297250262"
4872 "fbe3276b5a1c91159bbfa3ef8957aac8"
4873 "4b59b30b455a79c2973480823d8b3863"
4874 "c3deef4a8e243590268d80e18751a0e1"
4875 "30f67ce6a1ace9f79b95e097474febc9"
4876 "81195b1d13a69086c0863f66a7b7fdb4"
4877 "8792227b1ac5e2489febdf087ab54864"
4878 "83033a6f001ca5d1ec1e27f5c30f4cec"
4879 "2642074a39ae68aee552e196627a8e3d"
4880 "867e67a8c01b11e75f13cca0a97ab668"
4881 "b50cda07a8ecb7cd8e3dd7009c963653"
4882 "4f6f239cffe1fc8daa466f78b676c711"
4883 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4884 "99b801597d5220e307eaa5bee507fb94"
4885 "d1fa69f9e519b2de315bac92c36f2ea1"
4886 "fa1df4478c0ddedeae8c70e0233cd098"
4887 "040c" // OCTET STRING length 0x0c (initializationVector)
4888 "d796b02c370f1fa4cc0124f1"
4889 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4890 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4891 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4892 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4893 "3106" // SET length 0x06
4894 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4895 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4896 // } end SET
4897 // } end [1]
4898 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4899 "020120" // INTEGER length 1 value 0x20 (AES)
4900 // } end [2]
4901 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4902 "02020100" // INTEGER length 2 value 0x100
4903 // } end [3]
4904 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4905 "3103" // SET length 0x03 {
4906 "020101" // INTEGER length 1 value 0x01 (ECB)
4907 // } end SET
4908 // } end [4]
4909 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4910 "3103" // SET length 0x03 {
4911 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4912 // } end SET
4913 // } end [5]
4914 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4915 // (noAuthRequired)
4916 "0500" // NULL
4917 // } end [503]
4918 // } end SEQUENCE (AuthorizationList)
4919 // } end SEQUENCE (KeyDescription)
4920 "0420" // OCTET STRING length 0x20 (encryptedKey)
4921 "ccd540855f833a5e1480bfd2d36faf3a"
4922 "eee15df5beabe2691bc82dde2a7aa910"
4923 "0410" // OCTET STRING length 0x10 (tag)
4924 "64c9f689c60ff6223ab6e6999e0eb6e5"
4925 // } SEQUENCE (SecureKeyWrapper)
4926);
Selene Huang31ab4042020-04-29 04:22:39 -07004927
4928auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004929 // IKeyMintDevice.aidl
4930 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4931 "020100" // INTEGER length 1 value 0x00 (version)
4932 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4933 "aad93ed5924f283b4bb5526fbe7a1412"
4934 "f9d9749ec30db9062b29e574a8546f33"
4935 "c88732452f5b8e6a391ee76c39ed1712"
4936 "c61d8df6213dec1cffbc17a8c6d04c7b"
4937 "30893d8daa9b2015213e219468215532"
4938 "07f8f9931c4caba23ed3bee28b36947e"
4939 "47f10e0a5c3dc51c988a628daad3e5e1"
4940 "f4005e79c2d5a96c284b4b8d7e4948f3"
4941 "31e5b85dd5a236f85579f3ea1d1b8484"
4942 "87470bdb0ab4f81a12bee42c99fe0df4"
4943 "bee3759453e69ad1d68a809ce06b949f"
4944 "7694a990429b2fe81e066ff43e56a216"
4945 "02db70757922a4bcc23ab89f1e35da77"
4946 "586775f423e519c2ea394caf48a28d0c"
4947 "8020f1dcf6b3a68ec246f615ae96dae9"
4948 "a079b1f6eb959033c1af5c125fd94168"
4949 "040c" // OCTET STRING length 0x0c (initializationVector)
4950 "6d9721d08589581ab49204a3"
4951 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4952 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4953 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4954 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4955 "3106" // SET length 0x06
4956 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4957 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4958 // } end SET
4959 // } end [1]
4960 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4961 "020120" // INTEGER length 1 value 0x20 (AES)
4962 // } end [2]
4963 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4964 "02020100" // INTEGER length 2 value 0x100
4965 // } end [3]
4966 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4967 "3103" // SET length 0x03 {
4968 "020101" // INTEGER length 1 value 0x01 (ECB)
4969 // } end SET
4970 // } end [4]
4971 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4972 "3103" // SET length 0x03 {
4973 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4974 // } end SET
4975 // } end [5]
4976 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4977 // (noAuthRequired)
4978 "0500" // NULL
4979 // } end [503]
4980 // } end SEQUENCE (AuthorizationList)
4981 // } end SEQUENCE (KeyDescription)
4982 "0420" // OCTET STRING length 0x20 (encryptedKey)
4983 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4984 "c20d1f99a9a024a76f35c8e2cab9b68d"
4985 "0410" // OCTET STRING length 0x10 (tag)
4986 "2560c70109ae67c030f00b98b512a670"
4987 // } SEQUENCE (SecureKeyWrapper)
4988);
Selene Huang31ab4042020-04-29 04:22:39 -07004989
4990auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004991 // RFC 5208 s5
4992 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4993 "020100" // INTEGER length 1 value 0x00 (version)
4994 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4995 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4996 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4997 "0500" // NULL (parameters)
4998 // } SEQUENCE (AlgorithmIdentifier)
4999 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
5000 // RFC 8017 A.1.2
5001 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
5002 "020100" // INTEGER length 1 value 0x00 (version)
5003 "02820101" // INTEGER length 0x0101 (modulus) value...
5004 "00aec367931d8900ce56b0067f7d70e1" // 0x10
5005 "fc653f3f34d194c1fed50018fb43db93" // 0x20
5006 "7b06e673a837313d56b1c725150a3fef" // 0x30
5007 "86acbddc41bb759c2854eae32d35841e" // 0x40
5008 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
5009 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
5010 "312d7bd5921ffaea1347c157406fef71" // 0x70
5011 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
5012 "f4645c11f5c1374c3886427411c44979" // 0x90
5013 "6792e0bef75dec858a2123c36753e02a" // 0xa0
5014 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
5015 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
5016 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
5017 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
5018 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
5019 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
5020 "55" // 0x101
5021 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
5022 "02820100" // INTEGER length 0x100 (privateExponent) value...
5023 "431447b6251908112b1ee76f99f3711a" // 0x10
5024 "52b6630960046c2de70de188d833f8b8" // 0x20
5025 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
5026 "641f7fe24f14c67a88959bdb27766df9" // 0x40
5027 "e710b630a03adc683b5d2c43080e52be" // 0x50
5028 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
5029 "822bccff087d63c940ba8a45f670feb2" // 0x70
5030 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
5031 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
5032 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
5033 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
5034 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
5035 "52659d5a5ba05b663737a8696281865b" // 0xd0
5036 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
5037 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
5038 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
5039 "028181" // INTEGER length 0x81 (prime1) value...
5040 "00de392e18d682c829266cc3454e1d61" // 0x10
5041 "66242f32d9a1d10577753e904ea7d08b" // 0x20
5042 "ff841be5bac82a164c5970007047b8c5" // 0x30
5043 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
5044 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
5045 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
5046 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
5047 "9e91346130748a6e3c124f9149d71c74" // 0x80
5048 "35"
5049 "028181" // INTEGER length 0x81 (prime2) value...
5050 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
5051 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
5052 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
5053 "7349db6c4a95affdae0dae612e1afac9" // 0x40
5054 "9ed39a2d934c880440aed8832f984316" // 0x50
5055 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
5056 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
5057 "b880677c068e1be936e81288815252a8" // 0x80
5058 "a1"
5059 "028180" // INTEGER length 0x80 (exponent1) value...
5060 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
5061 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
5062 "5a063212a4f105a3764743e53281988a" // 0x30
5063 "ba073f6e0027298e1c4378556e0efca0" // 0x40
5064 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
5065 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
5066 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
5067 "4719d6e2b9439823719cd08bcd031781" // 0x80
5068 "028181" // INTEGER length 0x81 (exponent2) value...
5069 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
5070 "1241acc607976c4ddccc90e65b6556ca" // 0x20
5071 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
5072 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
5073 "1254186af30b22c10582a8a43e34fe94" // 0x50
5074 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
5075 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
5076 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
5077 "61"
5078 "028181" // INTEGER length 0x81 (coefficient) value...
5079 "00c931617c77829dfb1270502be9195c" // 0x10
5080 "8f2830885f57dba869536811e6864236" // 0x20
5081 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
5082 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
5083 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
5084 "959356210723287b0affcc9f727044d4" // 0x60
5085 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
5086 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
5087 "22"
5088 // } SEQUENCE
5089 // } SEQUENCE ()
5090);
Selene Huang31ab4042020-04-29 04:22:39 -07005091
5092string zero_masking_key =
5093 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
5094string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
5095
5096class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
5097
5098TEST_P(ImportWrappedKeyTest, Success) {
5099 auto wrapping_key_desc = AuthorizationSetBuilder()
5100 .RsaEncryptionKey(2048, 65537)
5101 .Digest(Digest::SHA_2_256)
5102 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005103 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5104 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005105
5106 ASSERT_EQ(ErrorCode::OK,
5107 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5108 AuthorizationSetBuilder()
5109 .Digest(Digest::SHA_2_256)
5110 .Padding(PaddingMode::RSA_OAEP)));
5111
5112 string message = "Hello World!";
5113 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5114 string ciphertext = EncryptMessage(message, params);
5115 string plaintext = DecryptMessage(ciphertext, params);
5116 EXPECT_EQ(message, plaintext);
5117}
5118
David Drysdaled2cc8c22021-04-15 13:29:45 +01005119/*
5120 * ImportWrappedKeyTest.SuccessSidsIgnored
5121 *
5122 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
5123 * include Tag:USER_SECURE_ID.
5124 */
5125TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
5126 auto wrapping_key_desc = AuthorizationSetBuilder()
5127 .RsaEncryptionKey(2048, 65537)
5128 .Digest(Digest::SHA_2_256)
5129 .Padding(PaddingMode::RSA_OAEP)
5130 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5131 .SetDefaultValidity();
5132
5133 int64_t password_sid = 42;
5134 int64_t biometric_sid = 24;
5135 ASSERT_EQ(ErrorCode::OK,
5136 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5137 AuthorizationSetBuilder()
5138 .Digest(Digest::SHA_2_256)
5139 .Padding(PaddingMode::RSA_OAEP),
5140 password_sid, biometric_sid));
5141
5142 string message = "Hello World!";
5143 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5144 string ciphertext = EncryptMessage(message, params);
5145 string plaintext = DecryptMessage(ciphertext, params);
5146 EXPECT_EQ(message, plaintext);
5147}
5148
Selene Huang31ab4042020-04-29 04:22:39 -07005149TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5150 auto wrapping_key_desc = AuthorizationSetBuilder()
5151 .RsaEncryptionKey(2048, 65537)
5152 .Digest(Digest::SHA_2_256)
5153 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005154 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5155 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005156
5157 ASSERT_EQ(ErrorCode::OK,
5158 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5159 AuthorizationSetBuilder()
5160 .Digest(Digest::SHA_2_256)
5161 .Padding(PaddingMode::RSA_OAEP)));
5162}
5163
5164TEST_P(ImportWrappedKeyTest, WrongMask) {
5165 auto wrapping_key_desc = AuthorizationSetBuilder()
5166 .RsaEncryptionKey(2048, 65537)
5167 .Digest(Digest::SHA_2_256)
5168 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005169 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5170 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005171
5172 ASSERT_EQ(
5173 ErrorCode::VERIFICATION_FAILED,
5174 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5175 AuthorizationSetBuilder()
5176 .Digest(Digest::SHA_2_256)
5177 .Padding(PaddingMode::RSA_OAEP)));
5178}
5179
5180TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5181 auto wrapping_key_desc = AuthorizationSetBuilder()
5182 .RsaEncryptionKey(2048, 65537)
5183 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005184 .Padding(PaddingMode::RSA_OAEP)
5185 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005186
5187 ASSERT_EQ(
5188 ErrorCode::INCOMPATIBLE_PURPOSE,
5189 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5190 AuthorizationSetBuilder()
5191 .Digest(Digest::SHA_2_256)
5192 .Padding(PaddingMode::RSA_OAEP)));
5193}
5194
David Drysdaled2cc8c22021-04-15 13:29:45 +01005195TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5196 auto wrapping_key_desc = AuthorizationSetBuilder()
5197 .RsaEncryptionKey(2048, 65537)
5198 .Digest(Digest::SHA_2_256)
5199 .Padding(PaddingMode::RSA_PSS)
5200 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5201 .SetDefaultValidity();
5202
5203 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5204 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5205 AuthorizationSetBuilder()
5206 .Digest(Digest::SHA_2_256)
5207 .Padding(PaddingMode::RSA_OAEP)));
5208}
5209
5210TEST_P(ImportWrappedKeyTest, WrongDigest) {
5211 auto wrapping_key_desc = AuthorizationSetBuilder()
5212 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005213 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005214 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005215 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5216 .SetDefaultValidity();
5217
5218 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5219 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5220 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005221 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005222 .Padding(PaddingMode::RSA_OAEP)));
5223}
5224
Tri Vob02ff882023-09-29 14:49:20 -04005225auto wrapped_rsa_key = hex2str(
5226 "308206230201000482010060f81b63ae53aa4be2e91b0b7cbdabd108125836139e5b991f3e3c9a98eca6cb7188"
5227 "fba1c1232605747ed118975870c886e583a0ff766fc32b789a17029955caaff39a9c6c439be168e24b51046683"
5228 "ce16110e0df115ccabbadcbe7ea9118b9589e4cccf240b6f0a506dfee57e19738c3cabb7dbf63b43e1b9ab058b"
5229 "41b9480f2797210ef2bfbecb82526ac60ac006ebe0a053e825ad996d0ce8a98dc1ebf6ad889e491e03e9ddcc05"
5230 "63f31921b55a54c61aa7f846d814dfe548f2c7939940bc6cf20489733203732df924b2b2a5aa9b54d31e7e42b9"
5231 "e6cf107182edd33cb8e41db88167a79a264bbf883e69300ac82aac8de9dca0a13900150111efead81b74040c78"
5232 "01d20b1547cfef40de45da30350201013030a1083106020102020103a203020101a30402020800a40531030201"
5233 "01a5053103020104a6053103020103bf8377020500048204c126cd1642e83dea941151d872de12b8aaa835446e"
5234 "94d2c1ea99c030225c5cad125dabe2341d9aba63e4df7fefc51e8e6f623ffae2aab9927113562b674b3cc2d7fc"
5235 "fc34f199151a56ab114e792e6a21bd3b31fbf0d93050b9f90fb8e6cad3a067a4033848c4380184990f19a141d9"
5236 "527177fdc13d802c33d222206c36404518285fe7e631aaeb6072c22c351c8c9db06e0b24e11aecef305f6abefb"
5237 "4f31111534f7c55da8cf0d33882edbb43765304d1d45545c5207a858ea8d4369393bf1c54624df03da86c0ed47"
5238 "b9ce1297149622069d51d2512f656ad0d421e6ff746ce8f79920df6a204c31732414a2f7eb24f8c2950348187a"
5239 "4ba20b88a72355a4ec2b383be9f9b5b9ad564aa4c81de47dd95d77a8156ed0901d005a26f523b2a82c2d25d64d"
5240 "f7660a6d3a720a6ba1eafe71da9fed0265d37a475193525620e705a543a928827accad93aba90556da859808be"
5241 "dc2a8105af252e883892f41679d0600ddefb84415145bc28a2d9b0c60cea1ed3876486950ae0532cc1e953b0b5"
5242 "81314c74250550741b24e4221ebb2804428caa2f08356a7de853ccfc5b18c2179147a883fa5763dd54f0d45388"
5243 "c72f1bea19675d14014a725e125cdfac98d1701d9562be9d75362ea238b93244f46306cee4d77cbb8cbe7bf22d"
5244 "fe677bbb103c00a204e49a0731660a2b23ee73ec7297a17822d4c4468e271029f8f1e8995f1a37cdc38324ead3"
5245 "2474e6ee3ff671803d8a98a870324364d408c4d966d3cf0b9bbcbdbdff34a3e9666705362bc78beb96df4b8964"
5246 "d141022250f62d1433cba5d1f510859eff688e46ce65dea00f5ebcfe7a79081ef1f0f5584dba14b79bc5a5f309"
5247 "a1e48fe2bd9e94fcd9793d9b3632ccc51f18f7453e897e33b729abd2d34be324acbc22dfbf1d089aa93a178f79"
5248 "23344140a468ac120b2f0055c284576b968e1d5148c6879b207b6cdb4eb513bccca619ae12ef156a9df03d6d8c"
5249 "2c1c2ea7109dbcb61e5a74b36d0a7529f38b9ea742a956376da823251a6126693e2e1dab55b643c4e9783db835"
5250 "f64d91069a2de1cda55539da52cadeeba2d3278da9005d89b4de4c5571600823f53d9cab1b55f65a560479d9ee"
5251 "edeb361ab80ccedd0a067ddf5de639d115ffb3acf07fbba1cba6daa524b99db0b785273f7b6c15c4237ce1dce8"
5252 "1b81622f35f116b638c75f0e0b26ba6bd9c5caee60c8b4f9198052b25e8c101638598946cb02c14db0a21b46c6"
5253 "61ea123b2a2b5a51eb059715ce26940c977715a32e288b713013d66d0dae398d546abcd8c80966190b77732a7c"
5254 "e2b8fc83e0cd83f69adef2b24b69fba19c546362087c08c8dab941a8573a084be3407d45a318c9a299f69d79f6"
5255 "fae0859d6f08ee7708cf6041cccd815c3515f792aefc23a624e8e58bd9c6fe2f8f1ca6dcf04c6fdfa23eb3ff74"
5256 "c5e5c7388f9faa32c86b6cd7438774e6cf06cb23a32cddb04c30f7d11e221db306c7937796e70a4dcfb7415c04"
5257 "7823b965bedeaea196dc30fe648c52f3c1bcee62b19d4cccdb740ca35c3f3daad998c99dc117fffb7d150d500f"
5258 "812b60ebec8b2067b13938250d078768e77f898fcdfc5f3554b6eda9df3b42bef38bb4d67cb63b7ede01e93b4d"
5259 "c7768b52aa8ad8fb7fb288a529b84671f1ff9e44bb7c8f05d99806b65eb8e90b530fef3817f9fc4c921d0d46af"
5260 "11aee8252407adc6c54589e9f6e6c1e25fc7510cfe499ea20465610410bf575efdbeb5af763920c3b4cdc8401"
5261 "2");
5262
5263auto wrapped_ec_key = hex2str(
5264 "308201dd020100048201000bb910602f88b1419ada400c8ab7602cf2fdbb4ef5e36881255fd5f85d49c4110c52"
5265 "c75eab5e27a1732c1afa17bfe2cd393dea0a78a77ee08759e984411d1c7f0dbdcb6b77e05556694534be4434d8"
5266 "596a7152aec71481522c85f0cc4635df2875d58dc29a78317b2aedd3586055e6e2227616f6a8ac4b9db5a2ad0e"
5267 "10f5c4b43374bd6c9f57f79a103e64084414cfab3d3e0b7c2f26eb00a62105b7d1c7f41b7292fd6fce9395f39c"
5268 "e0b6da0b5bf0d29d8952b958bd29b47c5ebd20d53ade370f463e35a166c04af71e3d5ce550019d3d20a5544896"
5269 "65d169875d0e6a52348b7ec39b674f818e9b60dfa284d7ae4188471d05b9b2d9a5f750f5a00af999c568040c31"
5270 "4144bde8ada6279d32e61530270201013022a1083106020102020103a203020103a30402020100a50531030201"
5271 "04bf837702050004818a96e0f8be5a263616b506371d3c2ff3a3c2bcffc3ce067b242af66e30d5cd975b9546eb"
5272 "32216d4f083f08fde246ab05fd7e930a0f05701067b44840c01a6722e1b2408be5b6acd0b39a0329cb2f357515"
5273 "876433b193382c0b18aed9ed244dcbef5d61d98ca480f99a6cf2a00efda22eb8750db1725e30f64770ac6862ac"
5274 "44cfd08a2c55812b512a0b92f704105c80b6a23cf339b2b10c677613510b1b");
5275
5276auto wrapping_key_for_asym_keys = hex2str(
5277 "308204bd020100300d06092a864886f70d0101010500048204a7308204a30201000282010100a7f521fe024ebc"
5278 "659db8e7a32b41dba27c5d446cb3d064d594b811d4856c3a583d155b0ff9300df3745738c32c4c4cd15adb6090"
5279 "72ca870364bb7f3485784fde12e598b486c91950b9c45016bcb73c3842747c871be02dfc5f0e4b96d1ff5c8a09"
5280 "7ae77b27e46dc60f1f574d1bb5e97487c1c3f9b493509e07318e1a0f0e9fdae401f4a62a5dd54daa09bf88ef42"
5281 "9923f6f6f55d239908f227676d0f0b618238728dc4babd2a1f7d15fa9827346a1a160ab9427461533006fdf34d"
5282 "4efec9aeefcea80b3a7d4ee4a4550055f0030700c5d20abcc32ce74d90ffabf83e02a759ce9074809936564f3d"
5283 "3039af9c5e8a6afd9aa5459ab35c3eb851f10b3ae88ba91f0203010001028201001885515124451a7c3b6aa366"
5284 "cf09ee66ea81335c2b6461544d42125854a258624988b4a2c05ea3aac77174780a1f9997770c502cc6958ae093"
5285 "f44bbdff3e716a9a97aa93b099eb783da6cb8a8642ba27fc8bc522748f66275239640fc0d8e749bfd891b3093f"
5286 "f046da2e593088bb263a3d17ace4e7d81a0cf83fe3df2a139882bff509523a3f886922200168ddd8fb7b4c9f26"
5287 "62ff941c37937cebbbfeba24dd78d5ccd42025cb0276fa5661965f529274520bbb9faf36c501cafb48e5e47ae0"
5288 "6980334fa36b6c62e2da733a8c7f01067de17e38d32d4a0721a6d184405bceaebb39ed3838633e6fbe43ac8b23"
5289 "337bfe33cdf0b67ac3938ddccc37d775ad150102818100d538885135037730fad28e987d7562c1ef8ca58f95f7"
5290 "ed81cb165ca63e15e810552eb9d487c9b9cde563fb29d1de22a60d54a856385719a4028cf386bcdc88e858d963"
5291 "6d644cea25e0ee54ad1237983d9a06a66ea2f764eb540a4992ba2291ea96d20dfbd98bf5b313322cda4eb6710d"
5292 "020139e085beb8e52a3e69bd05c71c7b02818100c9a7c89b11fcf8d99eb41995b5641472ef972e5aaa1f1446d7"
5293 "ea57a9979e8e64f72ef1cde358649b71be7f21dc19dab52814f9a521d8620bd994a9bb621a8182a250066a0728"
5294 "f0b16ab93a106ed79bc19cd519e83196157a8c6f82b5144a285b9384415394905fe18863b0988b27e77c969a81"
5295 "c34a074e8fef5908fdf3c51ead02818019d5e8c6963ade45640f01523ed96b66fe64b766e7900c0a4f165d9193"
5296 "324a55384d1a1d437ad0f5bed6d78720b3ded4ea069903217e844fd833460acc75986d36ded86a57ddedfd3afd"
5297 "05eb96aa7fdaeeffe148c49c5f711854cac769a068b7d92088ab3c97f5e485eded7b62503ef0898ea679ab1b0a"
5298 "0252950f70e4f35463028181008ff4c027bb8aad17a5cd0a2aaea83854e8a73347340525d38115e0e8c7bd4007"
5299 "e1d1d87ad35e69cbf2423cbdae43a2b70a5b16f0849dd53882663758f6aad763ab7d97669f9fe15bb6456ea706"
5300 "89d2be3fb87d5b1df2f77859c2cd3b79b58ae3fd0640206b813981667d4c3749b7fdf01a0f48ad622e9f2def7e"
5301 "cf0583bd67ad0281805bd8f20cc82cb5e08dc2e7eea977d4180a5ef4c558e01255b8475feb9084475e20328c93"
5302 "5a2247a775c941d64372d01abb27c95ee7d4336b6cbce190808b2f7a8d314d785336397dd6edc0c778f563d37e"
5303 "0057b13695600b92fececc3edb067f69b374f9b9c343220a8b927deb6104768edc72b87751e0a3fb1585e679c9"
5304 "8564");
5305
5306TEST_P(ImportWrappedKeyTest, RsaKey) {
5307 int vsr_api_level = get_vsr_api_level();
5308 if (vsr_api_level < __ANDROID_API_V__) {
5309 /*
5310 * The Keymaster v4 spec introduced `importWrappedKey()` and did not restrict it to
5311 * just symmetric keys. However, the import of asymmetric wrapped keys was not tested
5312 * at the time, so we can only be strict about checking this for implementations claiming
5313 * support for VSR API level 35 and above.
5314 */
5315 GTEST_SKIP() << "Applies only to VSR API level 35, this device is: " << vsr_api_level;
5316 }
5317
5318 auto wrapping_key_desc = AuthorizationSetBuilder()
5319 .RsaEncryptionKey(2048, 65537)
5320 .Digest(Digest::SHA_2_256)
5321 .Padding(PaddingMode::RSA_OAEP)
5322 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5323 .SetDefaultValidity();
5324
5325 ASSERT_EQ(ErrorCode::OK, ImportWrappedKey(wrapped_rsa_key, wrapping_key_for_asym_keys,
5326 wrapping_key_desc, zero_masking_key,
5327 AuthorizationSetBuilder()
5328 .Digest(Digest::SHA_2_256)
5329 .Padding(PaddingMode::RSA_OAEP)));
5330
5331 string message = "Hello World!";
5332 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
5333 string signature = SignMessage(message, params);
5334 LocalVerifyMessage(message, signature, params);
5335}
5336
5337TEST_P(ImportWrappedKeyTest, EcKey) {
5338 int vsr_api_level = get_vsr_api_level();
5339 if (vsr_api_level < __ANDROID_API_V__) {
5340 /*
5341 * The Keymaster v4 spec introduced `importWrappedKey()` and did not restrict it to
5342 * just symmetric keys. However, the import of asymmetric wrapped keys was not tested
5343 * at the time, so we can only be strict about checking this for implementations claiming
5344 * support for VSR API level 35 and above.
5345 */
5346 GTEST_SKIP() << "Applies only to VSR API level 35, this device is: " << vsr_api_level;
5347 }
5348
5349 auto wrapping_key_desc = AuthorizationSetBuilder()
5350 .RsaEncryptionKey(2048, 65537)
5351 .Digest(Digest::SHA_2_256)
5352 .Padding(PaddingMode::RSA_OAEP)
5353 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5354 .SetDefaultValidity();
5355
5356 ASSERT_EQ(ErrorCode::OK, ImportWrappedKey(wrapped_ec_key, wrapping_key_for_asym_keys,
5357 wrapping_key_desc, zero_masking_key,
5358 AuthorizationSetBuilder()
5359 .Digest(Digest::SHA_2_256)
5360 .Padding(PaddingMode::RSA_OAEP)));
5361
5362 string message = "Hello World!";
5363 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
5364 string signature = SignMessage(message, params);
5365 LocalVerifyMessage(message, signature, params);
5366}
5367
Selene Huang31ab4042020-04-29 04:22:39 -07005368INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5369
5370typedef KeyMintAidlTestBase EncryptionOperationsTest;
5371
5372/*
5373 * EncryptionOperationsTest.RsaNoPaddingSuccess
5374 *
David Drysdale59cae642021-05-12 13:52:03 +01005375 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005376 */
5377TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005378 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005379 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005380 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5381 .Authorization(TAG_NO_AUTH_REQUIRED)
5382 .RsaEncryptionKey(2048, exponent)
5383 .Padding(PaddingMode::NONE)
5384 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005385
David Drysdaled2cc8c22021-04-15 13:29:45 +01005386 string message = string(2048 / 8, 'a');
5387 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005388 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005389 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005390
David Drysdale59cae642021-05-12 13:52:03 +01005391 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005392 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005393
David Drysdaled2cc8c22021-04-15 13:29:45 +01005394 // Unpadded RSA is deterministic
5395 EXPECT_EQ(ciphertext1, ciphertext2);
5396
5397 CheckedDeleteKey();
5398 }
Selene Huang31ab4042020-04-29 04:22:39 -07005399}
5400
5401/*
5402 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5403 *
David Drysdale59cae642021-05-12 13:52:03 +01005404 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005405 */
5406TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5407 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5408 .Authorization(TAG_NO_AUTH_REQUIRED)
5409 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005410 .Padding(PaddingMode::NONE)
5411 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005412
5413 string message = "1";
5414 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5415
David Drysdale59cae642021-05-12 13:52:03 +01005416 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005417 EXPECT_EQ(2048U / 8, ciphertext.size());
5418
5419 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5420 string plaintext = DecryptMessage(ciphertext, params);
5421
5422 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005423}
5424
5425/*
Selene Huang31ab4042020-04-29 04:22:39 -07005426 * EncryptionOperationsTest.RsaOaepSuccess
5427 *
David Drysdale59cae642021-05-12 13:52:03 +01005428 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005429 */
5430TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5431 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
Prashant Patil2114dca2023-09-21 14:57:10 +00005432 auto mgf_digest = vector{Digest::SHA1};
Selene Huang31ab4042020-04-29 04:22:39 -07005433
5434 size_t key_size = 2048; // Need largish key for SHA-512 test.
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005435 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5436 .Authorization(TAG_NO_AUTH_REQUIRED)
5437 .RsaEncryptionKey(key_size, 65537)
5438 .Padding(PaddingMode::RSA_OAEP)
5439 .Digest(digests)
Prashant Patil2114dca2023-09-21 14:57:10 +00005440 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005441 .SetDefaultValidity()));
5442
5443 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005444 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Selene Huang31ab4042020-04-29 04:22:39 -07005445
5446 string message = "Hello";
5447
5448 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005449 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5450
5451 auto params = AuthorizationSetBuilder()
5452 .Digest(digest)
5453 .Padding(PaddingMode::RSA_OAEP)
5454 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5455 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005456 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5457 EXPECT_EQ(key_size / 8, ciphertext1.size());
5458
David Drysdale59cae642021-05-12 13:52:03 +01005459 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005460 EXPECT_EQ(key_size / 8, ciphertext2.size());
5461
5462 // OAEP randomizes padding so every result should be different (with astronomically high
5463 // probability).
5464 EXPECT_NE(ciphertext1, ciphertext2);
5465
5466 string plaintext1 = DecryptMessage(ciphertext1, params);
5467 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5468 string plaintext2 = DecryptMessage(ciphertext2, params);
5469 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5470
5471 // Decrypting corrupted ciphertext should fail.
5472 size_t offset_to_corrupt = random() % ciphertext1.size();
5473 char corrupt_byte;
5474 do {
5475 corrupt_byte = static_cast<char>(random() % 256);
5476 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5477 ciphertext1[offset_to_corrupt] = corrupt_byte;
5478
5479 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5480 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005481 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005482 EXPECT_EQ(0U, result.size());
5483 }
5484}
5485
5486/*
5487 * EncryptionOperationsTest.RsaOaepInvalidDigest
5488 *
David Drysdale59cae642021-05-12 13:52:03 +01005489 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005490 * without a digest.
5491 */
5492TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5493 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5494 .Authorization(TAG_NO_AUTH_REQUIRED)
5495 .RsaEncryptionKey(2048, 65537)
5496 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005497 .Digest(Digest::NONE)
5498 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005499
5500 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005501 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005502}
5503
5504/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005505 * EncryptionOperationsTest.RsaOaepInvalidPadding
5506 *
David Drysdale59cae642021-05-12 13:52:03 +01005507 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005508 * with a padding value that is only suitable for signing/verifying.
5509 */
5510TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5511 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5512 .Authorization(TAG_NO_AUTH_REQUIRED)
5513 .RsaEncryptionKey(2048, 65537)
5514 .Padding(PaddingMode::RSA_PSS)
5515 .Digest(Digest::NONE)
5516 .SetDefaultValidity()));
5517
5518 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005519 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005520}
5521
5522/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005523 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005524 *
David Drysdale59cae642021-05-12 13:52:03 +01005525 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005526 * with a different digest than was used to encrypt.
5527 */
5528TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005529 if (SecLevel() == SecurityLevel::STRONGBOX) {
5530 GTEST_SKIP() << "Test not applicable to StrongBox device";
5531 }
Selene Huang31ab4042020-04-29 04:22:39 -07005532
5533 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5534 .Authorization(TAG_NO_AUTH_REQUIRED)
5535 .RsaEncryptionKey(1024, 65537)
5536 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005537 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5538 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005539 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005540 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005541 message,
5542 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5543
5544 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5545 .Digest(Digest::SHA_2_256)
5546 .Padding(PaddingMode::RSA_OAEP)));
5547 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005548 EXPECT_NE(ErrorCode::OK, Finish(ciphertext, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005549 EXPECT_EQ(0U, result.size());
5550}
5551
5552/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005553 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5554 *
David Drysdale59cae642021-05-12 13:52:03 +01005555 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005556 * digests.
5557 */
5558TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5559 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5560
5561 size_t key_size = 2048; // Need largish key for SHA-512 test.
5562 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5563 .OaepMGFDigest(digests)
5564 .Authorization(TAG_NO_AUTH_REQUIRED)
5565 .RsaEncryptionKey(key_size, 65537)
5566 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005567 .Digest(Digest::SHA_2_256)
5568 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005569 if (AidlVersion() >= 3) {
5570 std::vector<Digest> mgf1DigestsInAuths;
5571 mgf1DigestsInAuths.reserve(digests.size());
5572 const auto& hw_auths = SecLevelAuthorizations(key_characteristics_);
5573 std::for_each(hw_auths.begin(), hw_auths.end(), [&](auto& param) {
5574 if (param.tag == Tag::RSA_OAEP_MGF_DIGEST) {
5575 KeyParameterValue value = param.value;
5576 mgf1DigestsInAuths.push_back(param.value.template get<KeyParameterValue::digest>());
5577 }
5578 });
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005579
Prashant Patil2114dca2023-09-21 14:57:10 +00005580 std::sort(digests.begin(), digests.end());
5581 std::sort(mgf1DigestsInAuths.begin(), mgf1DigestsInAuths.end());
5582 EXPECT_EQ(digests, mgf1DigestsInAuths);
5583 }
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005584 string message = "Hello";
5585
5586 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005587 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005588 auto params = AuthorizationSetBuilder()
5589 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5590 .Digest(Digest::SHA_2_256)
5591 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005592 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005593 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5594 EXPECT_EQ(key_size / 8, ciphertext1.size());
5595
David Drysdale59cae642021-05-12 13:52:03 +01005596 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005597 EXPECT_EQ(key_size / 8, ciphertext2.size());
5598
5599 // OAEP randomizes padding so every result should be different (with astronomically high
5600 // probability).
5601 EXPECT_NE(ciphertext1, ciphertext2);
5602
5603 string plaintext1 = DecryptMessage(ciphertext1, params);
5604 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5605 string plaintext2 = DecryptMessage(ciphertext2, params);
5606 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5607
5608 // Decrypting corrupted ciphertext should fail.
5609 size_t offset_to_corrupt = random() % ciphertext1.size();
5610 char corrupt_byte;
5611 do {
5612 corrupt_byte = static_cast<char>(random() % 256);
5613 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5614 ciphertext1[offset_to_corrupt] = corrupt_byte;
5615
5616 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5617 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005618 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005619 EXPECT_EQ(0U, result.size());
5620 }
5621}
5622
5623/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005624 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5625 *
5626 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5627 * specified, defaulting to SHA-1.
5628 */
5629TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5630 size_t key_size = 2048;
5631 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5632 .Authorization(TAG_NO_AUTH_REQUIRED)
5633 .RsaEncryptionKey(key_size, 65537)
5634 .Padding(PaddingMode::RSA_OAEP)
5635 .Digest(Digest::SHA_2_256)
5636 .SetDefaultValidity()));
5637
Prashant Patil2114dca2023-09-21 14:57:10 +00005638 vector defaultDigest = vector{Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005639 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005640 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005641
David Drysdaleae3727b2021-11-11 09:00:14 +00005642 // Do local RSA encryption using the default MGF digest of SHA-1.
5643 string message = "Hello";
5644 auto params =
5645 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5646 string ciphertext = LocalRsaEncryptMessage(message, params);
5647 EXPECT_EQ(key_size / 8, ciphertext.size());
5648
5649 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5650 string plaintext = DecryptMessage(ciphertext, params);
5651 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5652
5653 // Decrypting corrupted ciphertext should fail.
5654 size_t offset_to_corrupt = random() % ciphertext.size();
5655 char corrupt_byte;
5656 do {
5657 corrupt_byte = static_cast<char>(random() % 256);
5658 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5659 ciphertext[offset_to_corrupt] = corrupt_byte;
5660
5661 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5662 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005663 EXPECT_NE(ErrorCode::OK, Finish(ciphertext, &result));
David Drysdaleae3727b2021-11-11 09:00:14 +00005664 EXPECT_EQ(0U, result.size());
5665}
5666
5667/*
5668 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5669 *
5670 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5671 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5672 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5673 */
5674TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5675 size_t key_size = 2048;
Prashant Patil2114dca2023-09-21 14:57:10 +00005676 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005677 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5678 .Authorization(TAG_NO_AUTH_REQUIRED)
Prashant Patil2114dca2023-09-21 14:57:10 +00005679 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005680 .RsaEncryptionKey(key_size, 65537)
5681 .Padding(PaddingMode::RSA_OAEP)
5682 .Digest(Digest::SHA_2_256)
5683 .SetDefaultValidity()));
5684
5685 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005686 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
5687 vector defaultDigest = vector{Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005688 // Make sure default mgf-digest is not included in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005689 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
David Drysdaleae3727b2021-11-11 09:00:14 +00005690
5691 // Do local RSA encryption using the default MGF digest of SHA-1.
5692 string message = "Hello";
5693 auto params =
5694 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5695 string ciphertext = LocalRsaEncryptMessage(message, params);
5696 EXPECT_EQ(key_size / 8, ciphertext.size());
5697
5698 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5699 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5700 // is checked against those values, and found absent.
5701 auto result = Begin(KeyPurpose::DECRYPT, params);
5702 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5703 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5704}
5705
5706/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005707 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5708 *
David Drysdale59cae642021-05-12 13:52:03 +01005709 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005710 * with incompatible MGF digest.
5711 */
5712TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
Prashant Patil2114dca2023-09-21 14:57:10 +00005713 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005714 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Prashant Patil2114dca2023-09-21 14:57:10 +00005715 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005716 .Authorization(TAG_NO_AUTH_REQUIRED)
5717 .RsaEncryptionKey(2048, 65537)
5718 .Padding(PaddingMode::RSA_OAEP)
5719 .Digest(Digest::SHA_2_256)
5720 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005721
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005722 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005723 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005724
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005725 string message = "Hello World!";
5726
5727 auto params = AuthorizationSetBuilder()
5728 .Padding(PaddingMode::RSA_OAEP)
5729 .Digest(Digest::SHA_2_256)
5730 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005731 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005732}
5733
5734/*
5735 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5736 *
5737 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5738 * with unsupported MGF digest.
5739 */
5740TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
Prashant Patil2114dca2023-09-21 14:57:10 +00005741 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005742 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Prashant Patil2114dca2023-09-21 14:57:10 +00005743 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005744 .Authorization(TAG_NO_AUTH_REQUIRED)
5745 .RsaEncryptionKey(2048, 65537)
5746 .Padding(PaddingMode::RSA_OAEP)
5747 .Digest(Digest::SHA_2_256)
5748 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005749
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005750 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005751 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005752
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005753 string message = "Hello World!";
5754
5755 auto params = AuthorizationSetBuilder()
5756 .Padding(PaddingMode::RSA_OAEP)
5757 .Digest(Digest::SHA_2_256)
5758 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005759 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005760}
5761
5762/*
Selene Huang31ab4042020-04-29 04:22:39 -07005763 * EncryptionOperationsTest.RsaPkcs1Success
5764 *
5765 * Verifies that RSA PKCS encryption/decrypts works.
5766 */
5767TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5768 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5769 .Authorization(TAG_NO_AUTH_REQUIRED)
5770 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005771 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5772 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005773
5774 string message = "Hello World!";
5775 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005776 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005777 EXPECT_EQ(2048U / 8, ciphertext1.size());
5778
David Drysdale59cae642021-05-12 13:52:03 +01005779 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005780 EXPECT_EQ(2048U / 8, ciphertext2.size());
5781
5782 // PKCS1 v1.5 randomizes padding so every result should be different.
5783 EXPECT_NE(ciphertext1, ciphertext2);
5784
5785 string plaintext = DecryptMessage(ciphertext1, params);
5786 EXPECT_EQ(message, plaintext);
5787
5788 // Decrypting corrupted ciphertext should fail.
5789 size_t offset_to_corrupt = random() % ciphertext1.size();
5790 char corrupt_byte;
5791 do {
5792 corrupt_byte = static_cast<char>(random() % 256);
5793 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5794 ciphertext1[offset_to_corrupt] = corrupt_byte;
5795
5796 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5797 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005798 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005799 EXPECT_EQ(0U, result.size());
5800}
5801
5802/*
Selene Huang31ab4042020-04-29 04:22:39 -07005803 * EncryptionOperationsTest.EcdsaEncrypt
5804 *
5805 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5806 */
5807TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5808 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5809 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005810 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005811 .Digest(Digest::NONE)
5812 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005813 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5814 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5815 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5816}
5817
5818/*
5819 * EncryptionOperationsTest.HmacEncrypt
5820 *
5821 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5822 */
5823TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5824 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5825 .Authorization(TAG_NO_AUTH_REQUIRED)
5826 .HmacKey(128)
5827 .Digest(Digest::SHA_2_256)
5828 .Padding(PaddingMode::NONE)
5829 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5830 auto params = AuthorizationSetBuilder()
5831 .Digest(Digest::SHA_2_256)
5832 .Padding(PaddingMode::NONE)
5833 .Authorization(TAG_MAC_LENGTH, 128);
5834 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5835 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5836}
5837
5838/*
5839 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5840 *
5841 * Verifies that AES ECB mode works.
5842 */
5843TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5844 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5845 .Authorization(TAG_NO_AUTH_REQUIRED)
5846 .AesEncryptionKey(128)
5847 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5848 .Padding(PaddingMode::NONE)));
5849
5850 ASSERT_GT(key_blob_.size(), 0U);
5851 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5852
5853 // Two-block message.
5854 string message = "12345678901234567890123456789012";
5855 string ciphertext1 = EncryptMessage(message, params);
5856 EXPECT_EQ(message.size(), ciphertext1.size());
5857
5858 string ciphertext2 = EncryptMessage(string(message), params);
5859 EXPECT_EQ(message.size(), ciphertext2.size());
5860
5861 // ECB is deterministic.
5862 EXPECT_EQ(ciphertext1, ciphertext2);
5863
5864 string plaintext = DecryptMessage(ciphertext1, params);
5865 EXPECT_EQ(message, plaintext);
5866}
5867
5868/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005869 * EncryptionOperationsTest.AesEcbUnknownTag
5870 *
5871 * Verifies that AES ECB operations ignore unknown tags.
5872 */
5873TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5874 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5875 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5876 KeyParameter unknown_param;
5877 unknown_param.tag = unknown_tag;
5878
5879 vector<KeyCharacteristics> key_characteristics;
5880 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5881 .Authorization(TAG_NO_AUTH_REQUIRED)
5882 .AesEncryptionKey(128)
5883 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5884 .Padding(PaddingMode::NONE)
5885 .Authorization(unknown_param),
5886 &key_blob_, &key_characteristics));
5887 ASSERT_GT(key_blob_.size(), 0U);
5888
5889 // Unknown tags should not be returned in key characteristics.
5890 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5891 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5892 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5893 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5894
5895 // Encrypt without mentioning the unknown parameter.
5896 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5897 string message = "12345678901234567890123456789012";
5898 string ciphertext = EncryptMessage(message, params);
5899 EXPECT_EQ(message.size(), ciphertext.size());
5900
5901 // Decrypt including the unknown parameter.
5902 auto decrypt_params = AuthorizationSetBuilder()
5903 .BlockMode(BlockMode::ECB)
5904 .Padding(PaddingMode::NONE)
5905 .Authorization(unknown_param);
5906 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5907 EXPECT_EQ(message, plaintext);
5908}
5909
5910/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005911 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005912 *
5913 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5914 */
5915TEST_P(EncryptionOperationsTest, AesWrongMode) {
5916 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5917 .Authorization(TAG_NO_AUTH_REQUIRED)
5918 .AesEncryptionKey(128)
5919 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5920 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005921 ASSERT_GT(key_blob_.size(), 0U);
5922
Selene Huang31ab4042020-04-29 04:22:39 -07005923 EXPECT_EQ(
5924 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5925 Begin(KeyPurpose::ENCRYPT,
5926 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5927}
5928
5929/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005930 * EncryptionOperationsTest.AesWrongPadding
5931 *
5932 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5933 */
5934TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5935 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5936 .Authorization(TAG_NO_AUTH_REQUIRED)
5937 .AesEncryptionKey(128)
5938 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5939 .Padding(PaddingMode::NONE)));
5940 ASSERT_GT(key_blob_.size(), 0U);
5941
5942 EXPECT_EQ(
5943 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5944 Begin(KeyPurpose::ENCRYPT,
5945 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5946}
5947
5948/*
5949 * EncryptionOperationsTest.AesInvalidParams
5950 *
5951 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5952 */
5953TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5954 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5955 .Authorization(TAG_NO_AUTH_REQUIRED)
5956 .AesEncryptionKey(128)
5957 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5958 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5959 .Padding(PaddingMode::NONE)
5960 .Padding(PaddingMode::PKCS7)));
5961 ASSERT_GT(key_blob_.size(), 0U);
5962
5963 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5964 .BlockMode(BlockMode::CBC)
5965 .BlockMode(BlockMode::ECB)
5966 .Padding(PaddingMode::NONE));
5967 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5968 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5969
5970 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5971 .BlockMode(BlockMode::ECB)
5972 .Padding(PaddingMode::NONE)
5973 .Padding(PaddingMode::PKCS7));
5974 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5975 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5976}
5977
5978/*
Selene Huang31ab4042020-04-29 04:22:39 -07005979 * EncryptionOperationsTest.AesWrongPurpose
5980 *
5981 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5982 * specified.
5983 */
5984TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5985 auto err = GenerateKey(AuthorizationSetBuilder()
5986 .Authorization(TAG_NO_AUTH_REQUIRED)
5987 .AesKey(128)
5988 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5989 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5990 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5991 .Padding(PaddingMode::NONE));
5992 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5993 ASSERT_GT(key_blob_.size(), 0U);
5994
5995 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5996 .BlockMode(BlockMode::GCM)
5997 .Padding(PaddingMode::NONE)
5998 .Authorization(TAG_MAC_LENGTH, 128));
5999 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
6000
6001 CheckedDeleteKey();
6002
6003 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6004 .Authorization(TAG_NO_AUTH_REQUIRED)
6005 .AesKey(128)
6006 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
6007 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6008 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6009 .Padding(PaddingMode::NONE)));
6010
6011 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
6012 .BlockMode(BlockMode::GCM)
6013 .Padding(PaddingMode::NONE)
6014 .Authorization(TAG_MAC_LENGTH, 128));
6015 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
6016}
6017
6018/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006019 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07006020 *
6021 * Verifies that AES encryption fails in the correct way when provided an input that is not a
6022 * multiple of the block size and no padding is specified.
6023 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01006024TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
6025 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006026 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01006027 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6028 .Authorization(TAG_NO_AUTH_REQUIRED)
6029 .AesEncryptionKey(128)
6030 .Authorization(TAG_BLOCK_MODE, blockMode)
6031 .Padding(PaddingMode::NONE)));
6032 // Message is slightly shorter than two blocks.
6033 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07006034
David Drysdaled2cc8c22021-04-15 13:29:45 +01006035 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
6036 AuthorizationSet out_params;
6037 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6038 string ciphertext;
6039 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
6040 EXPECT_EQ(0U, ciphertext.size());
6041
6042 CheckedDeleteKey();
6043 }
Selene Huang31ab4042020-04-29 04:22:39 -07006044}
6045
6046/*
6047 * EncryptionOperationsTest.AesEcbPkcs7Padding
6048 *
6049 * Verifies that AES PKCS7 padding works for any message length.
6050 */
6051TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
6052 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6053 .Authorization(TAG_NO_AUTH_REQUIRED)
6054 .AesEncryptionKey(128)
6055 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
6056 .Padding(PaddingMode::PKCS7)));
6057
6058 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6059
6060 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08006061 for (size_t i = 0; i <= 48; i++) {
6062 SCOPED_TRACE(testing::Message() << "i = " << i);
6063 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
6064 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07006065 string ciphertext = EncryptMessage(message, params);
6066 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
6067 string plaintext = DecryptMessage(ciphertext, params);
6068 EXPECT_EQ(message, plaintext);
6069 }
6070}
6071
6072/*
6073 * EncryptionOperationsTest.AesEcbWrongPadding
6074 *
6075 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
6076 * specified.
6077 */
6078TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
6079 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6080 .Authorization(TAG_NO_AUTH_REQUIRED)
6081 .AesEncryptionKey(128)
6082 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
6083 .Padding(PaddingMode::NONE)));
6084
6085 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6086
6087 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08006088 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07006089 string message(i, 'a');
6090 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6091 }
6092}
6093
6094/*
6095 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
6096 *
6097 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
6098 */
6099TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
6100 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6101 .Authorization(TAG_NO_AUTH_REQUIRED)
6102 .AesEncryptionKey(128)
6103 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
6104 .Padding(PaddingMode::PKCS7)));
6105
6106 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6107
6108 string message = "a";
6109 string ciphertext = EncryptMessage(message, params);
6110 EXPECT_EQ(16U, ciphertext.size());
6111 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006112
Seth Moore7a55ae32021-06-23 14:28:11 -07006113 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6114 ++ciphertext[ciphertext.size() / 2];
6115
6116 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6117 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01006118 ErrorCode error = Finish(ciphertext, &plaintext);
6119 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07006120 // This is the expected error, we can exit the test now.
6121 return;
6122 } else {
6123 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01006124 ASSERT_EQ(error, ErrorCode::OK)
6125 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07006126 }
6127 }
6128 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006129}
6130
David Drysdaleb8093292022-04-08 12:22:35 +01006131/*
6132 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
6133 *
6134 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
6135 */
6136TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
6137 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6138 .Authorization(TAG_NO_AUTH_REQUIRED)
6139 .AesEncryptionKey(128)
6140 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
6141 .Padding(PaddingMode::PKCS7)));
6142
6143 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6144
6145 string message = "a";
6146 string ciphertext = EncryptMessage(message, params);
6147 EXPECT_EQ(16U, ciphertext.size());
6148 EXPECT_NE(ciphertext, message);
6149
6150 // Shorten the ciphertext.
6151 ciphertext.resize(ciphertext.size() - 1);
6152 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6153 string plaintext;
6154 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
6155}
6156
Selene Huang31ab4042020-04-29 04:22:39 -07006157vector<uint8_t> CopyIv(const AuthorizationSet& set) {
6158 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006159 EXPECT_TRUE(iv);
6160 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07006161}
6162
6163/*
6164 * EncryptionOperationsTest.AesCtrRoundTripSuccess
6165 *
6166 * Verifies that AES CTR mode works.
6167 */
6168TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
6169 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6170 .Authorization(TAG_NO_AUTH_REQUIRED)
6171 .AesEncryptionKey(128)
6172 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6173 .Padding(PaddingMode::NONE)));
6174
6175 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6176
6177 string message = "123";
6178 AuthorizationSet out_params;
6179 string ciphertext1 = EncryptMessage(message, params, &out_params);
6180 vector<uint8_t> iv1 = CopyIv(out_params);
6181 EXPECT_EQ(16U, iv1.size());
6182
6183 EXPECT_EQ(message.size(), ciphertext1.size());
6184
6185 out_params.Clear();
6186 string ciphertext2 = EncryptMessage(message, params, &out_params);
6187 vector<uint8_t> iv2 = CopyIv(out_params);
6188 EXPECT_EQ(16U, iv2.size());
6189
6190 // IVs should be random, so ciphertexts should differ.
6191 EXPECT_NE(ciphertext1, ciphertext2);
6192
6193 auto params_iv1 =
6194 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
6195 auto params_iv2 =
6196 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
6197
6198 string plaintext = DecryptMessage(ciphertext1, params_iv1);
6199 EXPECT_EQ(message, plaintext);
6200 plaintext = DecryptMessage(ciphertext2, params_iv2);
6201 EXPECT_EQ(message, plaintext);
6202
6203 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
6204 plaintext = DecryptMessage(ciphertext1, params_iv2);
6205 EXPECT_NE(message, plaintext);
6206 plaintext = DecryptMessage(ciphertext2, params_iv1);
6207 EXPECT_NE(message, plaintext);
6208}
6209
6210/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306211 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07006212 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306213 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07006214 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306215TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
6216 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
6217}
Selene Huang31ab4042020-04-29 04:22:39 -07006218
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306219/*
6220 * EncryptionOperationsTest.AesCbcIncremental
6221 *
6222 * Verifies that AES works for CBC block mode, when provided data in various size increments.
6223 */
6224TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
6225 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
6226}
Selene Huang31ab4042020-04-29 04:22:39 -07006227
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306228/*
6229 * EncryptionOperationsTest.AesCtrIncremental
6230 *
6231 * Verifies that AES works for CTR block mode, when provided data in various size increments.
6232 */
6233TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
6234 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
6235}
Selene Huang31ab4042020-04-29 04:22:39 -07006236
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306237/*
6238 * EncryptionOperationsTest.AesGcmIncremental
6239 *
6240 * Verifies that AES works for GCM block mode, when provided data in various size increments.
6241 */
6242TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
6243 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07006244}
6245
Prashant Patildd5f7f02022-07-06 18:58:07 +00006246/*
6247 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
6248 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6249 */
6250TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
6251 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
6252 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
6253 string kat_plaintext =
6254 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
6255 "809FFF37081C22EF278F896AB213A2A631");
6256 string kat_ciphertext =
6257 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
6258 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
6259 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6260 kat_ciphertext);
6261}
6262
6263/*
6264 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
6265 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6266 */
6267TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
6268 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
6269 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
6270 string kat_plaintext =
6271 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
6272 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
6273 string kat_ciphertext =
6274 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
6275 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
6276 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6277 kat_plaintext, kat_ciphertext);
6278}
6279
6280/*
6281 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
6282 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6283 */
6284TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
6285 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
6286 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
6287 string kat_plaintext =
6288 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
6289 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
6290 string kat_ciphertext =
6291 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
6292 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
6293 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6294 kat_ciphertext);
6295}
6296
6297/*
6298 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
6299 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6300 */
6301TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
6302 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
6303 string kat_plaintext =
6304 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
6305 "7B6168A9A27BCE554BEA94EF26E6C742A0");
6306 string kat_ciphertext =
6307 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
6308 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
6309 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6310 kat_ciphertext);
6311}
6312
6313/*
6314 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
6315 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6316 */
6317TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
6318 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
6319 string kat_plaintext =
6320 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
6321 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
6322 string kat_ciphertext =
6323 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6324 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6325 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6326 kat_ciphertext);
6327}
6328
6329/*
6330 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6331 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6332 */
6333TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6334 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6335 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6336 string kat_plaintext =
6337 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6338 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6339 string kat_ciphertext =
6340 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6341 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6342 "bdfcc0cba0");
6343
6344 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6345 kat_ciphertext);
6346}
6347
6348/*
6349 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6350 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6351 */
6352TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6353 if (SecLevel() == SecurityLevel::STRONGBOX) {
6354 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6355 }
6356 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6357 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6358 string kat_plaintext =
6359 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6360 "167f2497c994bd496eb80bfb2ba2c9d5af");
6361 string kat_ciphertext =
6362 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6363 "72c134552f3a138e726fbe493b3a839598");
6364 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6365 kat_ciphertext);
6366}
6367
6368/*
6369 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6370 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6371 */
6372TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6373 if (SecLevel() == SecurityLevel::STRONGBOX) {
6374 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6375 }
6376 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6377 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6378 string kat_plaintext =
6379 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6380 "b170");
6381 string kat_ciphertext =
6382 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6383 "4e3884138ff403a41fd99818708ada301c");
6384 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6385 kat_plaintext, kat_ciphertext);
6386}
6387
6388/*
6389 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6390 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6391 */
6392TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6393 if (SecLevel() == SecurityLevel::STRONGBOX) {
6394 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6395 }
6396 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6397 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6398 string kat_plaintext =
6399 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6400 "28091e09cdbbd3b42b");
6401 string kat_ciphertext =
6402 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6403 "2ae0f90f0c19f42b4a");
6404 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6405 kat_ciphertext);
6406}
6407
6408/*
6409 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6410 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6411 */
6412TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6413 if (SecLevel() == SecurityLevel::STRONGBOX) {
6414 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6415 }
6416 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6417 string kat_plaintext =
6418 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6419 "44ab");
6420 string kat_ciphertext =
6421 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6422 "2453");
6423 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6424 kat_ciphertext);
6425}
6426
6427/*
6428 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6429 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6430 */
6431TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6432 if (SecLevel() == SecurityLevel::STRONGBOX) {
6433 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6434 }
6435 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6436 string kat_plaintext =
6437 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6438 "e2c7");
6439 string kat_ciphertext =
6440 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6441 "bb7e3a889dd4a9589098b44acf1056e7aa");
6442 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6443 kat_ciphertext);
6444}
6445
6446/*
6447 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6448 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6449 */
6450TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6451 if (SecLevel() == SecurityLevel::STRONGBOX) {
6452 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6453 }
6454 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6455 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6456 string kat_plaintext =
6457 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6458 "ff52");
6459 string kat_ciphertext =
6460 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6461 "1413ad70fb0e1970669095ad77ebb5974ae8");
6462
6463 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6464 kat_ciphertext);
6465}
6466
6467/*
6468 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6469 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6470 */
6471TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6472 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6473 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6474 string kat_plaintext =
6475 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6476 "494cb53caca353e4b637ba05687be20f8d");
6477 string kat_ciphertext =
6478 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6479 "6047da1e4fd7c4e1cf2656097f75ae8685");
6480 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6481 kat_ciphertext);
6482}
6483
6484/*
6485 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6486 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6487 */
6488TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6489 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6490 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6491 string kat_plaintext =
6492 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6493 "2545a82b73c48078b9dae62261c65909");
6494 string kat_ciphertext =
6495 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6496 "9403a71987b95124073d69f2a3cb95b0ab");
6497 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6498 kat_plaintext, kat_ciphertext);
6499}
6500
6501/*
6502 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6503 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6504 */
6505TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6506 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6507 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6508 string kat_plaintext =
6509 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6510 "1f6db3c884");
6511 string kat_ciphertext =
6512 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6513 "a7be30d4c3");
6514 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6515 kat_ciphertext);
6516}
6517
6518/*
6519 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6520 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6521 */
6522TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6523 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6524 string kat_plaintext =
6525 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6526 "31a476d6806b8116089c6ec50bb543200f");
6527 string kat_ciphertext =
6528 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6529 "c83e377faf246288931136bef2a07c0be4");
6530 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6531 kat_ciphertext);
6532}
6533
6534/*
6535 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6536 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6537 */
6538TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6539 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6540 string kat_plaintext =
6541 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6542 "6f");
6543 string kat_ciphertext =
6544 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6545 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6546 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6547 kat_ciphertext);
6548}
6549
6550/*
6551 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6552 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6553 */
6554TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6555 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6556 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6557 string kat_plaintext =
6558 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6559 "f0");
6560 string kat_ciphertext =
6561 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6562 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6563
6564 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6565 kat_ciphertext);
6566}
6567
Selene Huang31ab4042020-04-29 04:22:39 -07006568struct AesCtrSp80038aTestVector {
6569 const char* key;
6570 const char* nonce;
6571 const char* plaintext;
6572 const char* ciphertext;
6573};
6574
6575// These test vectors are taken from
6576// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6577static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6578 // AES-128
6579 {
6580 "2b7e151628aed2a6abf7158809cf4f3c",
6581 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6582 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6583 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6584 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6585 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6586 },
6587 // AES-192
6588 {
6589 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6590 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6591 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6592 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6593 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6594 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6595 },
6596 // AES-256
6597 {
6598 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6599 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6600 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6601 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6602 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6603 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6604 },
6605};
6606
6607/*
6608 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6609 *
6610 * Verifies AES CTR implementation against SP800-38A test vectors.
6611 */
6612TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6613 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6614 for (size_t i = 0; i < 3; i++) {
6615 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6616 const string key = hex2str(test.key);
6617 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6618 InvalidSizes.end())
6619 continue;
6620 const string nonce = hex2str(test.nonce);
6621 const string plaintext = hex2str(test.plaintext);
6622 const string ciphertext = hex2str(test.ciphertext);
6623 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6624 }
6625}
6626
6627/*
6628 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6629 *
6630 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6631 */
6632TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6633 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6634 .Authorization(TAG_NO_AUTH_REQUIRED)
6635 .AesEncryptionKey(128)
6636 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6637 .Padding(PaddingMode::PKCS7)));
6638 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6639 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6640}
6641
6642/*
6643 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6644 *
6645 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6646 */
6647TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6648 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6649 .Authorization(TAG_NO_AUTH_REQUIRED)
6650 .AesEncryptionKey(128)
6651 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6652 .Authorization(TAG_CALLER_NONCE)
6653 .Padding(PaddingMode::NONE)));
6654
6655 auto params = AuthorizationSetBuilder()
6656 .BlockMode(BlockMode::CTR)
6657 .Padding(PaddingMode::NONE)
6658 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6659 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6660
6661 params = AuthorizationSetBuilder()
6662 .BlockMode(BlockMode::CTR)
6663 .Padding(PaddingMode::NONE)
6664 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6665 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6666
6667 params = AuthorizationSetBuilder()
6668 .BlockMode(BlockMode::CTR)
6669 .Padding(PaddingMode::NONE)
6670 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6671 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6672}
6673
6674/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006675 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006676 *
6677 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6678 */
6679TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6680 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6681 .Authorization(TAG_NO_AUTH_REQUIRED)
6682 .AesEncryptionKey(128)
6683 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6684 .Padding(PaddingMode::NONE)));
6685 // Two-block message.
6686 string message = "12345678901234567890123456789012";
6687 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6688 AuthorizationSet out_params;
6689 string ciphertext1 = EncryptMessage(message, params, &out_params);
6690 vector<uint8_t> iv1 = CopyIv(out_params);
6691 EXPECT_EQ(message.size(), ciphertext1.size());
6692
6693 out_params.Clear();
6694
6695 string ciphertext2 = EncryptMessage(message, params, &out_params);
6696 vector<uint8_t> iv2 = CopyIv(out_params);
6697 EXPECT_EQ(message.size(), ciphertext2.size());
6698
6699 // IVs should be random, so ciphertexts should differ.
6700 EXPECT_NE(ciphertext1, ciphertext2);
6701
6702 params.push_back(TAG_NONCE, iv1);
6703 string plaintext = DecryptMessage(ciphertext1, params);
6704 EXPECT_EQ(message, plaintext);
6705}
6706
6707/*
Tommy Chiuee705692021-09-23 20:09:13 +08006708 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6709 *
6710 * Verifies that keymaster generates correct output on zero-input with
6711 * NonePadding mode
6712 */
6713TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6714 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6715 .Authorization(TAG_NO_AUTH_REQUIRED)
6716 .AesEncryptionKey(128)
6717 .BlockMode(BlockMode::CBC)
6718 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6719
6720 // Zero input message
6721 string message = "";
6722 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006723 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006724 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6725 AuthorizationSet out_params;
6726 string ciphertext1 = EncryptMessage(message, params, &out_params);
6727 vector<uint8_t> iv1 = CopyIv(out_params);
6728 if (padding == PaddingMode::NONE)
6729 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6730 else
6731 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6732
6733 out_params.Clear();
6734
6735 string ciphertext2 = EncryptMessage(message, params, &out_params);
6736 vector<uint8_t> iv2 = CopyIv(out_params);
6737 if (padding == PaddingMode::NONE)
6738 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6739 else
6740 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6741
6742 // IVs should be random
6743 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6744
6745 params.push_back(TAG_NONCE, iv1);
6746 string plaintext = DecryptMessage(ciphertext1, params);
6747 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6748 }
6749}
6750
6751/*
Selene Huang31ab4042020-04-29 04:22:39 -07006752 * EncryptionOperationsTest.AesCallerNonce
6753 *
6754 * Verifies that AES caller-provided nonces work correctly.
6755 */
6756TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6757 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6758 .Authorization(TAG_NO_AUTH_REQUIRED)
6759 .AesEncryptionKey(128)
6760 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6761 .Authorization(TAG_CALLER_NONCE)
6762 .Padding(PaddingMode::NONE)));
6763
6764 string message = "12345678901234567890123456789012";
6765
6766 // Don't specify nonce, should get a random one.
6767 AuthorizationSetBuilder params =
6768 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6769 AuthorizationSet out_params;
6770 string ciphertext = EncryptMessage(message, params, &out_params);
6771 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006772 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006773
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006774 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006775 string plaintext = DecryptMessage(ciphertext, params);
6776 EXPECT_EQ(message, plaintext);
6777
6778 // Now specify a nonce, should also work.
6779 params = AuthorizationSetBuilder()
6780 .BlockMode(BlockMode::CBC)
6781 .Padding(PaddingMode::NONE)
6782 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6783 out_params.Clear();
6784 ciphertext = EncryptMessage(message, params, &out_params);
6785
6786 // Decrypt with correct nonce.
6787 plaintext = DecryptMessage(ciphertext, params);
6788 EXPECT_EQ(message, plaintext);
6789
6790 // Try with wrong nonce.
6791 params = AuthorizationSetBuilder()
6792 .BlockMode(BlockMode::CBC)
6793 .Padding(PaddingMode::NONE)
6794 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6795 plaintext = DecryptMessage(ciphertext, params);
6796 EXPECT_NE(message, plaintext);
6797}
6798
6799/*
6800 * EncryptionOperationsTest.AesCallerNonceProhibited
6801 *
6802 * Verifies that caller-provided nonces are not permitted when not specified in the key
6803 * authorizations.
6804 */
6805TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6806 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6807 .Authorization(TAG_NO_AUTH_REQUIRED)
6808 .AesEncryptionKey(128)
6809 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6810 .Padding(PaddingMode::NONE)));
6811
6812 string message = "12345678901234567890123456789012";
6813
6814 // Don't specify nonce, should get a random one.
6815 AuthorizationSetBuilder params =
6816 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6817 AuthorizationSet out_params;
6818 string ciphertext = EncryptMessage(message, params, &out_params);
6819 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006820 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006821
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006822 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006823 string plaintext = DecryptMessage(ciphertext, params);
6824 EXPECT_EQ(message, plaintext);
6825
6826 // Now specify a nonce, should fail
6827 params = AuthorizationSetBuilder()
6828 .BlockMode(BlockMode::CBC)
6829 .Padding(PaddingMode::NONE)
6830 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6831 out_params.Clear();
6832 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6833}
6834
6835/*
6836 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6837 *
6838 * Verifies that AES GCM mode works.
6839 */
6840TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6841 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6842 .Authorization(TAG_NO_AUTH_REQUIRED)
6843 .AesEncryptionKey(128)
6844 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6845 .Padding(PaddingMode::NONE)
6846 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6847
6848 string aad = "foobar";
6849 string message = "123456789012345678901234567890123456";
6850
6851 auto begin_params = AuthorizationSetBuilder()
6852 .BlockMode(BlockMode::GCM)
6853 .Padding(PaddingMode::NONE)
6854 .Authorization(TAG_MAC_LENGTH, 128);
6855
Selene Huang31ab4042020-04-29 04:22:39 -07006856 // Encrypt
6857 AuthorizationSet begin_out_params;
6858 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6859 << "Begin encrypt";
6860 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006861 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6862 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006863 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6864
6865 // Grab nonce
6866 begin_params.push_back(begin_out_params);
6867
6868 // Decrypt.
6869 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006870 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006871 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006872 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006873 EXPECT_EQ(message.length(), plaintext.length());
6874 EXPECT_EQ(message, plaintext);
6875}
6876
6877/*
6878 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6879 *
6880 * Verifies that AES GCM mode works, even when there's a long delay
6881 * between operations.
6882 */
6883TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6884 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6885 .Authorization(TAG_NO_AUTH_REQUIRED)
6886 .AesEncryptionKey(128)
6887 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6888 .Padding(PaddingMode::NONE)
6889 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6890
6891 string aad = "foobar";
6892 string message = "123456789012345678901234567890123456";
6893
6894 auto begin_params = AuthorizationSetBuilder()
6895 .BlockMode(BlockMode::GCM)
6896 .Padding(PaddingMode::NONE)
6897 .Authorization(TAG_MAC_LENGTH, 128);
6898
Selene Huang31ab4042020-04-29 04:22:39 -07006899 // Encrypt
6900 AuthorizationSet begin_out_params;
6901 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6902 << "Begin encrypt";
6903 string ciphertext;
6904 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006905 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006906 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006907 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006908
6909 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6910
6911 // Grab nonce
6912 begin_params.push_back(begin_out_params);
6913
6914 // Decrypt.
6915 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6916 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006917 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006918 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006919 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006920 sleep(5);
6921 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6922 EXPECT_EQ(message.length(), plaintext.length());
6923 EXPECT_EQ(message, plaintext);
6924}
6925
6926/*
6927 * EncryptionOperationsTest.AesGcmDifferentNonces
6928 *
6929 * Verifies that encrypting the same data with different nonces produces different outputs.
6930 */
6931TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6932 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6933 .Authorization(TAG_NO_AUTH_REQUIRED)
6934 .AesEncryptionKey(128)
6935 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6936 .Padding(PaddingMode::NONE)
6937 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6938 .Authorization(TAG_CALLER_NONCE)));
6939
6940 string aad = "foobar";
6941 string message = "123456789012345678901234567890123456";
6942 string nonce1 = "000000000000";
6943 string nonce2 = "111111111111";
6944 string nonce3 = "222222222222";
6945
6946 string ciphertext1 =
6947 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6948 string ciphertext2 =
6949 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6950 string ciphertext3 =
6951 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6952
6953 ASSERT_NE(ciphertext1, ciphertext2);
6954 ASSERT_NE(ciphertext1, ciphertext3);
6955 ASSERT_NE(ciphertext2, ciphertext3);
6956}
6957
6958/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006959 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6960 *
6961 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6962 */
6963TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6964 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6965 .Authorization(TAG_NO_AUTH_REQUIRED)
6966 .AesEncryptionKey(128)
6967 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6968 .Padding(PaddingMode::NONE)
6969 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6970
6971 string aad = "foobar";
6972 string message = "123456789012345678901234567890123456";
6973
6974 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6975 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6976 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6977
6978 ASSERT_NE(ciphertext1, ciphertext2);
6979 ASSERT_NE(ciphertext1, ciphertext3);
6980 ASSERT_NE(ciphertext2, ciphertext3);
6981}
6982
6983/*
Selene Huang31ab4042020-04-29 04:22:39 -07006984 * EncryptionOperationsTest.AesGcmTooShortTag
6985 *
6986 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6987 */
6988TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6989 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6990 .Authorization(TAG_NO_AUTH_REQUIRED)
6991 .AesEncryptionKey(128)
6992 .BlockMode(BlockMode::GCM)
6993 .Padding(PaddingMode::NONE)
6994 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6995 string message = "123456789012345678901234567890123456";
6996 auto params = AuthorizationSetBuilder()
6997 .BlockMode(BlockMode::GCM)
6998 .Padding(PaddingMode::NONE)
6999 .Authorization(TAG_MAC_LENGTH, 96);
7000
7001 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
7002}
7003
7004/*
7005 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
7006 *
7007 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
7008 */
7009TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
7010 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7011 .Authorization(TAG_NO_AUTH_REQUIRED)
7012 .AesEncryptionKey(128)
7013 .BlockMode(BlockMode::GCM)
7014 .Padding(PaddingMode::NONE)
7015 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7016 string aad = "foobar";
7017 string message = "123456789012345678901234567890123456";
7018 auto params = AuthorizationSetBuilder()
7019 .BlockMode(BlockMode::GCM)
7020 .Padding(PaddingMode::NONE)
7021 .Authorization(TAG_MAC_LENGTH, 128);
7022
Selene Huang31ab4042020-04-29 04:22:39 -07007023 // Encrypt
7024 AuthorizationSet begin_out_params;
7025 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
7026 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08007027 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007028
7029 AuthorizationSet finish_out_params;
7030 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007031 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
7032 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007033
7034 params = AuthorizationSetBuilder()
7035 .Authorizations(begin_out_params)
7036 .BlockMode(BlockMode::GCM)
7037 .Padding(PaddingMode::NONE)
7038 .Authorization(TAG_MAC_LENGTH, 96);
7039
7040 // Decrypt.
7041 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
7042}
7043
7044/*
7045 * EncryptionOperationsTest.AesGcmCorruptKey
7046 *
7047 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
7048 */
7049TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
7050 const uint8_t nonce_bytes[] = {
7051 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
7052 };
7053 string nonce = make_string(nonce_bytes);
7054 const uint8_t ciphertext_bytes[] = {
7055 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
7056 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
7057 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
7058 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
7059 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
7060 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
7061 };
7062 string ciphertext = make_string(ciphertext_bytes);
7063
7064 auto params = AuthorizationSetBuilder()
7065 .BlockMode(BlockMode::GCM)
7066 .Padding(PaddingMode::NONE)
7067 .Authorization(TAG_MAC_LENGTH, 128)
7068 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
7069
7070 auto import_params = AuthorizationSetBuilder()
7071 .Authorization(TAG_NO_AUTH_REQUIRED)
7072 .AesEncryptionKey(128)
7073 .BlockMode(BlockMode::GCM)
7074 .Padding(PaddingMode::NONE)
7075 .Authorization(TAG_CALLER_NONCE)
7076 .Authorization(TAG_MIN_MAC_LENGTH, 128);
7077
7078 // Import correct key and decrypt
7079 const uint8_t key_bytes[] = {
7080 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
7081 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
7082 };
7083 string key = make_string(key_bytes);
7084 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
7085 string plaintext = DecryptMessage(ciphertext, params);
7086 CheckedDeleteKey();
7087
7088 // Corrupt key and attempt to decrypt
7089 key[0] = 0;
7090 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
7091 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
7092 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
7093 CheckedDeleteKey();
7094}
7095
7096/*
7097 * EncryptionOperationsTest.AesGcmAadNoData
7098 *
7099 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
7100 * encrypt.
7101 */
7102TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
7103 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7104 .Authorization(TAG_NO_AUTH_REQUIRED)
7105 .AesEncryptionKey(128)
7106 .BlockMode(BlockMode::GCM)
7107 .Padding(PaddingMode::NONE)
7108 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7109
7110 string aad = "1234567890123456";
7111 auto params = AuthorizationSetBuilder()
7112 .BlockMode(BlockMode::GCM)
7113 .Padding(PaddingMode::NONE)
7114 .Authorization(TAG_MAC_LENGTH, 128);
7115
Selene Huang31ab4042020-04-29 04:22:39 -07007116 // Encrypt
7117 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007118 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007119 string ciphertext;
7120 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07007121 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
7122 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007123 EXPECT_TRUE(finish_out_params.empty());
7124
7125 // Grab nonce
7126 params.push_back(begin_out_params);
7127
7128 // Decrypt.
7129 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007130 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007131 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007132 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007133
7134 EXPECT_TRUE(finish_out_params.empty());
7135
7136 EXPECT_EQ("", plaintext);
7137}
7138
7139/*
7140 * EncryptionOperationsTest.AesGcmMultiPartAad
7141 *
7142 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
7143 * chunks.
7144 */
7145TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
7146 const size_t tag_bits = 128;
7147 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7148 .Authorization(TAG_NO_AUTH_REQUIRED)
7149 .AesEncryptionKey(128)
7150 .BlockMode(BlockMode::GCM)
7151 .Padding(PaddingMode::NONE)
7152 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7153
7154 string message = "123456789012345678901234567890123456";
7155 auto begin_params = AuthorizationSetBuilder()
7156 .BlockMode(BlockMode::GCM)
7157 .Padding(PaddingMode::NONE)
7158 .Authorization(TAG_MAC_LENGTH, tag_bits);
7159 AuthorizationSet begin_out_params;
7160
David Drysdale7fc26b92022-05-13 09:54:24 +01007161 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007162
7163 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07007164 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
7165 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007166 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007167 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7168 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007169
Selene Huang31ab4042020-04-29 04:22:39 -07007170 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07007171 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07007172
7173 // Grab nonce.
7174 begin_params.push_back(begin_out_params);
7175
7176 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01007177 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007178 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007179 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007180 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007181 EXPECT_EQ(message, plaintext);
7182}
7183
7184/*
7185 * EncryptionOperationsTest.AesGcmAadOutOfOrder
7186 *
7187 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
7188 */
7189TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
7190 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7191 .Authorization(TAG_NO_AUTH_REQUIRED)
7192 .AesEncryptionKey(128)
7193 .BlockMode(BlockMode::GCM)
7194 .Padding(PaddingMode::NONE)
7195 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7196
7197 string message = "123456789012345678901234567890123456";
7198 auto begin_params = AuthorizationSetBuilder()
7199 .BlockMode(BlockMode::GCM)
7200 .Padding(PaddingMode::NONE)
7201 .Authorization(TAG_MAC_LENGTH, 128);
7202 AuthorizationSet begin_out_params;
7203
David Drysdale7fc26b92022-05-13 09:54:24 +01007204 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007205
Shawn Willden92d79c02021-02-19 07:31:55 -07007206 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007207 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007208 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7209 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007210
David Drysdaled2cc8c22021-04-15 13:29:45 +01007211 // The failure should have already cancelled the operation.
7212 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
7213
Shawn Willden92d79c02021-02-19 07:31:55 -07007214 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07007215}
7216
7217/*
7218 * EncryptionOperationsTest.AesGcmBadAad
7219 *
7220 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
7221 */
7222TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
7223 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7224 .Authorization(TAG_NO_AUTH_REQUIRED)
7225 .AesEncryptionKey(128)
7226 .BlockMode(BlockMode::GCM)
7227 .Padding(PaddingMode::NONE)
7228 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7229
7230 string message = "12345678901234567890123456789012";
7231 auto begin_params = AuthorizationSetBuilder()
7232 .BlockMode(BlockMode::GCM)
7233 .Padding(PaddingMode::NONE)
7234 .Authorization(TAG_MAC_LENGTH, 128);
7235
Selene Huang31ab4042020-04-29 04:22:39 -07007236 // Encrypt
7237 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007238 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007239 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007240 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007241 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007242
7243 // Grab nonce
7244 begin_params.push_back(begin_out_params);
7245
Selene Huang31ab4042020-04-29 04:22:39 -07007246 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007247 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007248 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007249 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007250 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007251}
7252
7253/*
7254 * EncryptionOperationsTest.AesGcmWrongNonce
7255 *
7256 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
7257 */
7258TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
7259 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7260 .Authorization(TAG_NO_AUTH_REQUIRED)
7261 .AesEncryptionKey(128)
7262 .BlockMode(BlockMode::GCM)
7263 .Padding(PaddingMode::NONE)
7264 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7265
7266 string message = "12345678901234567890123456789012";
7267 auto begin_params = AuthorizationSetBuilder()
7268 .BlockMode(BlockMode::GCM)
7269 .Padding(PaddingMode::NONE)
7270 .Authorization(TAG_MAC_LENGTH, 128);
7271
Selene Huang31ab4042020-04-29 04:22:39 -07007272 // Encrypt
7273 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007274 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007275 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007276 string ciphertext;
7277 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07007278 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007279
7280 // Wrong nonce
7281 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
7282
7283 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007284 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007285 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007286 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007287 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007288
7289 // With wrong nonce, should have gotten garbage plaintext (or none).
7290 EXPECT_NE(message, plaintext);
7291}
7292
7293/*
7294 * EncryptionOperationsTest.AesGcmCorruptTag
7295 *
7296 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
7297 */
7298TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
7299 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7300 .Authorization(TAG_NO_AUTH_REQUIRED)
7301 .AesEncryptionKey(128)
7302 .BlockMode(BlockMode::GCM)
7303 .Padding(PaddingMode::NONE)
7304 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7305
7306 string aad = "1234567890123456";
7307 string message = "123456789012345678901234567890123456";
7308
7309 auto params = AuthorizationSetBuilder()
7310 .BlockMode(BlockMode::GCM)
7311 .Padding(PaddingMode::NONE)
7312 .Authorization(TAG_MAC_LENGTH, 128);
7313
Selene Huang31ab4042020-04-29 04:22:39 -07007314 // Encrypt
7315 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007316 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007317 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007318 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007319 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007320
7321 // Corrupt tag
7322 ++(*ciphertext.rbegin());
7323
7324 // Grab nonce
7325 params.push_back(begin_out_params);
7326
7327 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007328 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007329 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007330 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007331 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007332}
7333
7334/*
7335 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7336 *
7337 * Verifies that 3DES is basically functional.
7338 */
7339TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7340 auto auths = AuthorizationSetBuilder()
7341 .TripleDesEncryptionKey(168)
7342 .BlockMode(BlockMode::ECB)
7343 .Authorization(TAG_NO_AUTH_REQUIRED)
7344 .Padding(PaddingMode::NONE);
7345
7346 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7347 // Two-block message.
7348 string message = "1234567890123456";
7349 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7350 string ciphertext1 = EncryptMessage(message, inParams);
7351 EXPECT_EQ(message.size(), ciphertext1.size());
7352
7353 string ciphertext2 = EncryptMessage(string(message), inParams);
7354 EXPECT_EQ(message.size(), ciphertext2.size());
7355
7356 // ECB is deterministic.
7357 EXPECT_EQ(ciphertext1, ciphertext2);
7358
7359 string plaintext = DecryptMessage(ciphertext1, inParams);
7360 EXPECT_EQ(message, plaintext);
7361}
7362
7363/*
7364 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7365 *
7366 * Verifies that CBC keys reject ECB usage.
7367 */
7368TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7369 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7370 .TripleDesEncryptionKey(168)
7371 .BlockMode(BlockMode::CBC)
7372 .Authorization(TAG_NO_AUTH_REQUIRED)
7373 .Padding(PaddingMode::NONE)));
7374
7375 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7376 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7377}
7378
7379/*
7380 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7381 *
7382 * Tests ECB mode with PKCS#7 padding, various message sizes.
7383 */
7384TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7385 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7386 .TripleDesEncryptionKey(168)
7387 .BlockMode(BlockMode::ECB)
7388 .Authorization(TAG_NO_AUTH_REQUIRED)
7389 .Padding(PaddingMode::PKCS7)));
7390
7391 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007392 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007393 string message(i, 'a');
7394 auto inParams =
7395 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7396 string ciphertext = EncryptMessage(message, inParams);
7397 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7398 string plaintext = DecryptMessage(ciphertext, inParams);
7399 EXPECT_EQ(message, plaintext);
7400 }
7401}
7402
7403/*
7404 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7405 *
7406 * Verifies that keys configured for no padding reject PKCS7 padding
7407 */
7408TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7409 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7410 .TripleDesEncryptionKey(168)
7411 .BlockMode(BlockMode::ECB)
7412 .Authorization(TAG_NO_AUTH_REQUIRED)
7413 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007414 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7415 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007416}
7417
7418/*
7419 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7420 *
7421 * Verifies that corrupted padding is detected.
7422 */
7423TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7424 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7425 .TripleDesEncryptionKey(168)
7426 .BlockMode(BlockMode::ECB)
7427 .Authorization(TAG_NO_AUTH_REQUIRED)
7428 .Padding(PaddingMode::PKCS7)));
7429
7430 string message = "a";
7431 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7432 EXPECT_EQ(8U, ciphertext.size());
7433 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007434
7435 AuthorizationSetBuilder begin_params;
7436 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7437 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007438
7439 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7440 ++ciphertext[ciphertext.size() / 2];
7441
David Drysdale7fc26b92022-05-13 09:54:24 +01007442 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007443 string plaintext;
7444 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7445 ErrorCode error = Finish(&plaintext);
7446 if (error == ErrorCode::INVALID_ARGUMENT) {
7447 // This is the expected error, we can exit the test now.
7448 return;
7449 } else {
7450 // Very small chance we got valid decryption, so try again.
7451 ASSERT_EQ(error, ErrorCode::OK);
7452 }
7453 }
7454 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007455}
7456
7457struct TripleDesTestVector {
7458 const char* name;
7459 const KeyPurpose purpose;
7460 const BlockMode block_mode;
7461 const PaddingMode padding_mode;
7462 const char* key;
7463 const char* iv;
7464 const char* input;
7465 const char* output;
7466};
7467
7468// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7469// of the NIST vectors are multiples of the block size.
7470static const TripleDesTestVector kTripleDesTestVectors[] = {
7471 {
7472 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7473 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7474 "", // IV
7475 "329d86bdf1bc5af4", // input
7476 "d946c2756d78633f", // output
7477 },
7478 {
7479 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7480 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7481 "", // IV
7482 "6b1540781b01ce1997adae102dbf3c5b", // input
7483 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7484 },
7485 {
7486 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7487 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7488 "", // IV
7489 "6daad94ce08acfe7", // input
7490 "660e7d32dcc90e79", // output
7491 },
7492 {
7493 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7494 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7495 "", // IV
7496 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7497 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7498 },
7499 {
7500 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7501 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7502 "43f791134c5647ba", // IV
7503 "dcc153cef81d6f24", // input
7504 "92538bd8af18d3ba", // output
7505 },
7506 {
7507 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7508 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7509 "c2e999cb6249023c", // IV
7510 "c689aee38a301bb316da75db36f110b5", // input
7511 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7512 },
7513 {
7514 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7515 PaddingMode::PKCS7,
7516 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7517 "c2e999cb6249023c", // IV
7518 "c689aee38a301bb316da75db36f110b500", // input
7519 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7520 },
7521 {
7522 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7523 PaddingMode::PKCS7,
7524 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7525 "c2e999cb6249023c", // IV
7526 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7527 "c689aee38a301bb316da75db36f110b500", // output
7528 },
7529 {
7530 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7531 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7532 "41746c7e442d3681", // IV
7533 "c53a7b0ec40600fe", // input
7534 "d4f00eb455de1034", // output
7535 },
7536 {
7537 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7538 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7539 "3982bc02c3727d45", // IV
7540 "6006f10adef52991fcc777a1238bbb65", // input
7541 "edae09288e9e3bc05746d872b48e3b29", // output
7542 },
7543};
7544
7545/*
7546 * EncryptionOperationsTest.TripleDesTestVector
7547 *
7548 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7549 */
7550TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7551 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7552 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7553 SCOPED_TRACE(test->name);
7554 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7555 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7556 hex2str(test->output));
7557 }
7558}
7559
7560/*
7561 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7562 *
7563 * Validates CBC mode functionality.
7564 */
7565TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7566 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7567 .TripleDesEncryptionKey(168)
7568 .BlockMode(BlockMode::CBC)
7569 .Authorization(TAG_NO_AUTH_REQUIRED)
7570 .Padding(PaddingMode::NONE)));
7571
7572 ASSERT_GT(key_blob_.size(), 0U);
7573
Brian J Murray734c8412022-01-13 14:55:30 -08007574 // Four-block message.
7575 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007576 vector<uint8_t> iv1;
7577 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7578 EXPECT_EQ(message.size(), ciphertext1.size());
7579
7580 vector<uint8_t> iv2;
7581 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7582 EXPECT_EQ(message.size(), ciphertext2.size());
7583
7584 // IVs should be random, so ciphertexts should differ.
7585 EXPECT_NE(iv1, iv2);
7586 EXPECT_NE(ciphertext1, ciphertext2);
7587
7588 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7589 EXPECT_EQ(message, plaintext);
7590}
7591
7592/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007593 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7594 *
7595 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7596 */
7597TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7598 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7599 .TripleDesEncryptionKey(168)
7600 .BlockMode(BlockMode::CBC)
7601 .Authorization(TAG_NO_AUTH_REQUIRED)
7602 .Authorization(TAG_CALLER_NONCE)
7603 .Padding(PaddingMode::NONE)));
7604 auto params = AuthorizationSetBuilder()
7605 .BlockMode(BlockMode::CBC)
7606 .Padding(PaddingMode::NONE)
7607 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7608 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7609}
7610
7611/*
Selene Huang31ab4042020-04-29 04:22:39 -07007612 * EncryptionOperationsTest.TripleDesCallerIv
7613 *
7614 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7615 */
7616TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7617 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7618 .TripleDesEncryptionKey(168)
7619 .BlockMode(BlockMode::CBC)
7620 .Authorization(TAG_NO_AUTH_REQUIRED)
7621 .Authorization(TAG_CALLER_NONCE)
7622 .Padding(PaddingMode::NONE)));
7623 string message = "1234567890123456";
7624 vector<uint8_t> iv;
7625 // Don't specify IV, should get a random one.
7626 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7627 EXPECT_EQ(message.size(), ciphertext1.size());
7628 EXPECT_EQ(8U, iv.size());
7629
7630 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7631 EXPECT_EQ(message, plaintext);
7632
7633 // Now specify an IV, should also work.
7634 iv = AidlBuf("abcdefgh");
7635 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7636
7637 // Decrypt with correct IV.
7638 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7639 EXPECT_EQ(message, plaintext);
7640
7641 // Now try with wrong IV.
7642 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7643 EXPECT_NE(message, plaintext);
7644}
7645
7646/*
7647 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7648 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007649 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007650 */
7651TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7652 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7653 .TripleDesEncryptionKey(168)
7654 .BlockMode(BlockMode::CBC)
7655 .Authorization(TAG_NO_AUTH_REQUIRED)
7656 .Padding(PaddingMode::NONE)));
7657
7658 string message = "12345678901234567890123456789012";
7659 vector<uint8_t> iv;
7660 // Don't specify nonce, should get a random one.
7661 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7662 EXPECT_EQ(message.size(), ciphertext1.size());
7663 EXPECT_EQ(8U, iv.size());
7664
7665 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7666 EXPECT_EQ(message, plaintext);
7667
7668 // Now specify a nonce, should fail.
7669 auto input_params = AuthorizationSetBuilder()
7670 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7671 .BlockMode(BlockMode::CBC)
7672 .Padding(PaddingMode::NONE);
7673 AuthorizationSet output_params;
7674 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7675 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7676}
7677
7678/*
7679 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7680 *
7681 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7682 */
7683TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7684 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7685 .TripleDesEncryptionKey(168)
7686 .BlockMode(BlockMode::ECB)
7687 .Authorization(TAG_NO_AUTH_REQUIRED)
7688 .Padding(PaddingMode::NONE)));
7689 // Two-block message.
7690 string message = "1234567890123456";
7691 auto begin_params =
7692 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7693 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7694}
7695
7696/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007697 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007698 *
7699 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7700 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007701TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7702 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007703 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007704 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7705 .TripleDesEncryptionKey(168)
7706 .BlockMode(blockMode)
7707 .Authorization(TAG_NO_AUTH_REQUIRED)
7708 .Padding(PaddingMode::NONE)));
7709 // Message is slightly shorter than two blocks.
7710 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007711
David Drysdaled2cc8c22021-04-15 13:29:45 +01007712 auto begin_params =
7713 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7714 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007715 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007716 string ciphertext;
7717 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7718
7719 CheckedDeleteKey();
7720 }
Selene Huang31ab4042020-04-29 04:22:39 -07007721}
7722
7723/*
7724 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7725 *
7726 * Verifies that PKCS7 padding works correctly in CBC mode.
7727 */
7728TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7729 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7730 .TripleDesEncryptionKey(168)
7731 .BlockMode(BlockMode::CBC)
7732 .Authorization(TAG_NO_AUTH_REQUIRED)
7733 .Padding(PaddingMode::PKCS7)));
7734
7735 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007736 for (size_t i = 0; i <= 32; i++) {
7737 SCOPED_TRACE(testing::Message() << "i = " << i);
7738 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7739 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007740 vector<uint8_t> iv;
7741 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7742 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7743 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7744 EXPECT_EQ(message, plaintext);
7745 }
7746}
7747
7748/*
7749 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7750 *
7751 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7752 */
7753TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7754 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7755 .TripleDesEncryptionKey(168)
7756 .BlockMode(BlockMode::CBC)
7757 .Authorization(TAG_NO_AUTH_REQUIRED)
7758 .Padding(PaddingMode::NONE)));
7759
7760 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007761 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007762 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007763 auto begin_params =
7764 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7765 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7766 }
7767}
7768
7769/*
7770 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7771 *
7772 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7773 */
7774TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7775 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7776 .TripleDesEncryptionKey(168)
7777 .BlockMode(BlockMode::CBC)
7778 .Authorization(TAG_NO_AUTH_REQUIRED)
7779 .Padding(PaddingMode::PKCS7)));
7780
7781 string message = "a";
7782 vector<uint8_t> iv;
7783 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7784 EXPECT_EQ(8U, ciphertext.size());
7785 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007786
7787 auto begin_params = AuthorizationSetBuilder()
7788 .BlockMode(BlockMode::CBC)
7789 .Padding(PaddingMode::PKCS7)
7790 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007791
7792 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007793 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007794 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007795 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007796 string plaintext;
7797 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7798 ErrorCode error = Finish(&plaintext);
7799 if (error == ErrorCode::INVALID_ARGUMENT) {
7800 // This is the expected error, we can exit the test now.
7801 return;
7802 } else {
7803 // Very small chance we got valid decryption, so try again.
7804 ASSERT_EQ(error, ErrorCode::OK);
7805 }
7806 }
7807 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007808}
7809
7810/*
7811 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7812 *
7813 * Verifies that 3DES CBC works with many different input sizes.
7814 */
7815TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7816 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7817 .TripleDesEncryptionKey(168)
7818 .BlockMode(BlockMode::CBC)
7819 .Authorization(TAG_NO_AUTH_REQUIRED)
7820 .Padding(PaddingMode::NONE)));
7821
7822 int increment = 7;
7823 string message(240, 'a');
7824 AuthorizationSet input_params =
7825 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7826 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007827 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007828
7829 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007830 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007831 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007832 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7833 EXPECT_EQ(message.size(), ciphertext.size());
7834
7835 // Move TAG_NONCE into input_params
7836 input_params = output_params;
7837 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7838 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7839 output_params.Clear();
7840
David Drysdale7fc26b92022-05-13 09:54:24 +01007841 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007842 string plaintext;
7843 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007844 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007845 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7846 EXPECT_EQ(ciphertext.size(), plaintext.size());
7847 EXPECT_EQ(message, plaintext);
7848}
7849
7850INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7851
7852typedef KeyMintAidlTestBase MaxOperationsTest;
7853
7854/*
7855 * MaxOperationsTest.TestLimitAes
7856 *
7857 * Verifies that the max uses per boot tag works correctly with AES keys.
7858 */
7859TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007860 if (SecLevel() == SecurityLevel::STRONGBOX) {
7861 GTEST_SKIP() << "Test not applicable to StrongBox device";
7862 }
Selene Huang31ab4042020-04-29 04:22:39 -07007863
7864 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7865 .Authorization(TAG_NO_AUTH_REQUIRED)
7866 .AesEncryptionKey(128)
7867 .EcbMode()
7868 .Padding(PaddingMode::NONE)
7869 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7870
7871 string message = "1234567890123456";
7872
7873 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7874
7875 EncryptMessage(message, params);
7876 EncryptMessage(message, params);
7877 EncryptMessage(message, params);
7878
7879 // Fourth time should fail.
7880 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7881}
7882
7883/*
Qi Wud22ec842020-11-26 13:27:53 +08007884 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007885 *
7886 * Verifies that the max uses per boot tag works correctly with RSA keys.
7887 */
7888TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007889 if (SecLevel() == SecurityLevel::STRONGBOX) {
7890 GTEST_SKIP() << "Test not applicable to StrongBox device";
7891 }
Selene Huang31ab4042020-04-29 04:22:39 -07007892
7893 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7894 .Authorization(TAG_NO_AUTH_REQUIRED)
7895 .RsaSigningKey(1024, 65537)
7896 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007897 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7898 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007899
7900 string message = "1234567890123456";
7901
7902 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7903
7904 SignMessage(message, params);
7905 SignMessage(message, params);
7906 SignMessage(message, params);
7907
7908 // Fourth time should fail.
7909 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7910}
7911
7912INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7913
Qi Wud22ec842020-11-26 13:27:53 +08007914typedef KeyMintAidlTestBase UsageCountLimitTest;
7915
7916/*
Qi Wubeefae42021-01-28 23:16:37 +08007917 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007918 *
Qi Wubeefae42021-01-28 23:16:37 +08007919 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007920 */
Qi Wubeefae42021-01-28 23:16:37 +08007921TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007922 if (SecLevel() == SecurityLevel::STRONGBOX) {
7923 GTEST_SKIP() << "Test not applicable to StrongBox device";
7924 }
Qi Wud22ec842020-11-26 13:27:53 +08007925
7926 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7927 .Authorization(TAG_NO_AUTH_REQUIRED)
7928 .AesEncryptionKey(128)
7929 .EcbMode()
7930 .Padding(PaddingMode::NONE)
7931 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7932
7933 // Check the usage count limit tag appears in the authorizations.
7934 AuthorizationSet auths;
7935 for (auto& entry : key_characteristics_) {
7936 auths.push_back(AuthorizationSet(entry.authorizations));
7937 }
7938 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7939 << "key usage count limit " << 1U << " missing";
7940
7941 string message = "1234567890123456";
7942 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7943
Qi Wubeefae42021-01-28 23:16:37 +08007944 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7945 AuthorizationSet keystore_auths =
7946 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7947
Qi Wud22ec842020-11-26 13:27:53 +08007948 // First usage of AES key should work.
7949 EncryptMessage(message, params);
7950
Qi Wud22ec842020-11-26 13:27:53 +08007951 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7952 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7953 // must be invalidated from secure storage (such as RPMB partition).
7954 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7955 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007956 // Usage count limit tag is enforced by keystore, keymint does nothing.
7957 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007958 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007959 }
7960}
7961
7962/*
Qi Wubeefae42021-01-28 23:16:37 +08007963 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007964 *
Qi Wubeefae42021-01-28 23:16:37 +08007965 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007966 */
Qi Wubeefae42021-01-28 23:16:37 +08007967TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007968 if (SecLevel() == SecurityLevel::STRONGBOX) {
7969 GTEST_SKIP() << "Test not applicable to StrongBox device";
7970 }
Qi Wubeefae42021-01-28 23:16:37 +08007971
7972 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7973 .Authorization(TAG_NO_AUTH_REQUIRED)
7974 .AesEncryptionKey(128)
7975 .EcbMode()
7976 .Padding(PaddingMode::NONE)
7977 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7978
7979 // Check the usage count limit tag appears in the authorizations.
7980 AuthorizationSet auths;
7981 for (auto& entry : key_characteristics_) {
7982 auths.push_back(AuthorizationSet(entry.authorizations));
7983 }
7984 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7985 << "key usage count limit " << 3U << " missing";
7986
7987 string message = "1234567890123456";
7988 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7989
7990 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7991 AuthorizationSet keystore_auths =
7992 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7993
7994 EncryptMessage(message, params);
7995 EncryptMessage(message, params);
7996 EncryptMessage(message, params);
7997
7998 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7999 // Usage count limit tag is enforced by hardware. After using the key, the key blob
8000 // must be invalidated from secure storage (such as RPMB partition).
8001 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
8002 } else {
8003 // Usage count limit tag is enforced by keystore, keymint does nothing.
8004 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01008005 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08008006 }
8007}
8008
8009/*
8010 * UsageCountLimitTest.TestSingleUseRsa
8011 *
8012 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
8013 */
8014TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01008015 if (SecLevel() == SecurityLevel::STRONGBOX) {
8016 GTEST_SKIP() << "Test not applicable to StrongBox device";
8017 }
Qi Wud22ec842020-11-26 13:27:53 +08008018
8019 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8020 .Authorization(TAG_NO_AUTH_REQUIRED)
8021 .RsaSigningKey(1024, 65537)
8022 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08008023 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
8024 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08008025
8026 // Check the usage count limit tag appears in the authorizations.
8027 AuthorizationSet auths;
8028 for (auto& entry : key_characteristics_) {
8029 auths.push_back(AuthorizationSet(entry.authorizations));
8030 }
8031 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
8032 << "key usage count limit " << 1U << " missing";
8033
8034 string message = "1234567890123456";
8035 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
8036
Qi Wubeefae42021-01-28 23:16:37 +08008037 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
8038 AuthorizationSet keystore_auths =
8039 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
8040
Qi Wud22ec842020-11-26 13:27:53 +08008041 // First usage of RSA key should work.
8042 SignMessage(message, params);
8043
Qi Wud22ec842020-11-26 13:27:53 +08008044 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
8045 // Usage count limit tag is enforced by hardware. After using the key, the key blob
8046 // must be invalidated from secure storage (such as RPMB partition).
8047 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
8048 } else {
Qi Wubeefae42021-01-28 23:16:37 +08008049 // Usage count limit tag is enforced by keystore, keymint does nothing.
8050 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01008051 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08008052 }
8053}
8054
8055/*
8056 * UsageCountLimitTest.TestLimitUseRsa
8057 *
8058 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
8059 */
8060TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01008061 if (SecLevel() == SecurityLevel::STRONGBOX) {
8062 GTEST_SKIP() << "Test not applicable to StrongBox device";
8063 }
Qi Wubeefae42021-01-28 23:16:37 +08008064
8065 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8066 .Authorization(TAG_NO_AUTH_REQUIRED)
8067 .RsaSigningKey(1024, 65537)
8068 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08008069 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
8070 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08008071
8072 // Check the usage count limit tag appears in the authorizations.
8073 AuthorizationSet auths;
8074 for (auto& entry : key_characteristics_) {
8075 auths.push_back(AuthorizationSet(entry.authorizations));
8076 }
8077 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
8078 << "key usage count limit " << 3U << " missing";
8079
8080 string message = "1234567890123456";
8081 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
8082
8083 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
8084 AuthorizationSet keystore_auths =
8085 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
8086
8087 SignMessage(message, params);
8088 SignMessage(message, params);
8089 SignMessage(message, params);
8090
8091 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
8092 // Usage count limit tag is enforced by hardware. After using the key, the key blob
8093 // must be invalidated from secure storage (such as RPMB partition).
8094 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
8095 } else {
8096 // Usage count limit tag is enforced by keystore, keymint does nothing.
8097 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01008098 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08008099 }
8100}
8101
Qi Wu8e727f72021-02-11 02:49:33 +08008102/*
8103 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
8104 *
8105 * Verifies that when rollback resistance is supported by the KeyMint implementation with
8106 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
8107 * in hardware.
8108 */
8109TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
Qi Wu8e727f72021-02-11 02:49:33 +08008110 auto error = GenerateKey(AuthorizationSetBuilder()
8111 .RsaSigningKey(2048, 65537)
8112 .Digest(Digest::NONE)
8113 .Padding(PaddingMode::NONE)
8114 .Authorization(TAG_NO_AUTH_REQUIRED)
8115 .Authorization(TAG_ROLLBACK_RESISTANCE)
8116 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008117 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8118 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08008119 }
David Drysdale513bf122021-10-06 11:53:13 +01008120
8121 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
8122 ASSERT_EQ(ErrorCode::OK, error);
8123 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8124 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
8125 ASSERT_EQ(ErrorCode::OK, DeleteKey());
8126
8127 // The KeyMint should also enforce single use key in hardware when it supports rollback
8128 // resistance.
8129 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8130 .Authorization(TAG_NO_AUTH_REQUIRED)
8131 .RsaSigningKey(1024, 65537)
8132 .NoDigestOrPadding()
8133 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
8134 .SetDefaultValidity()));
8135
8136 // Check the usage count limit tag appears in the hardware authorizations.
8137 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
8138 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
8139 << "key usage count limit " << 1U << " missing";
8140
8141 string message = "1234567890123456";
8142 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
8143
8144 // First usage of RSA key should work.
8145 SignMessage(message, params);
8146
8147 // Usage count limit tag is enforced by hardware. After using the key, the key blob
8148 // must be invalidated from secure storage (such as RPMB partition).
8149 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08008150}
8151
Qi Wud22ec842020-11-26 13:27:53 +08008152INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
8153
David Drysdale7de9feb2021-03-05 14:56:19 +00008154typedef KeyMintAidlTestBase GetHardwareInfoTest;
8155
8156TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
8157 // Retrieving hardware info should give the same result each time.
8158 KeyMintHardwareInfo info;
8159 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
8160 KeyMintHardwareInfo info2;
8161 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
8162 EXPECT_EQ(info, info2);
8163}
8164
8165INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
8166
Selene Huang31ab4042020-04-29 04:22:39 -07008167typedef KeyMintAidlTestBase AddEntropyTest;
8168
8169/*
8170 * AddEntropyTest.AddEntropy
8171 *
8172 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
8173 * is actually added.
8174 */
8175TEST_P(AddEntropyTest, AddEntropy) {
8176 string data = "foo";
8177 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
8178}
8179
8180/*
8181 * AddEntropyTest.AddEmptyEntropy
8182 *
8183 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
8184 */
8185TEST_P(AddEntropyTest, AddEmptyEntropy) {
8186 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
8187}
8188
8189/*
8190 * AddEntropyTest.AddLargeEntropy
8191 *
8192 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
8193 */
8194TEST_P(AddEntropyTest, AddLargeEntropy) {
8195 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
8196}
8197
David Drysdalebb3d85e2021-04-13 11:15:51 +01008198/*
8199 * AddEntropyTest.AddTooLargeEntropy
8200 *
8201 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
8202 */
8203TEST_P(AddEntropyTest, AddTooLargeEntropy) {
8204 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
8205 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
8206}
8207
Selene Huang31ab4042020-04-29 04:22:39 -07008208INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
8209
Selene Huang31ab4042020-04-29 04:22:39 -07008210typedef KeyMintAidlTestBase KeyDeletionTest;
8211
8212/**
8213 * KeyDeletionTest.DeleteKey
8214 *
8215 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
8216 * valid key blob.
8217 */
8218TEST_P(KeyDeletionTest, DeleteKey) {
8219 auto error = GenerateKey(AuthorizationSetBuilder()
8220 .RsaSigningKey(2048, 65537)
8221 .Digest(Digest::NONE)
8222 .Padding(PaddingMode::NONE)
8223 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008224 .Authorization(TAG_ROLLBACK_RESISTANCE)
8225 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008226 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8227 GTEST_SKIP() << "Rollback resistance not supported";
8228 }
Selene Huang31ab4042020-04-29 04:22:39 -07008229
8230 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008231 ASSERT_EQ(ErrorCode::OK, error);
8232 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8233 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008234
David Drysdale513bf122021-10-06 11:53:13 +01008235 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07008236
David Drysdale513bf122021-10-06 11:53:13 +01008237 string message = "12345678901234567890123456789012";
8238 AuthorizationSet begin_out_params;
8239 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8240 Begin(KeyPurpose::SIGN, key_blob_,
8241 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8242 &begin_out_params));
8243 AbortIfNeeded();
8244 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008245}
8246
8247/**
8248 * KeyDeletionTest.DeleteInvalidKey
8249 *
8250 * This test checks that the HAL excepts invalid key blobs..
8251 */
8252TEST_P(KeyDeletionTest, DeleteInvalidKey) {
8253 // Generate key just to check if rollback protection is implemented
8254 auto error = GenerateKey(AuthorizationSetBuilder()
8255 .RsaSigningKey(2048, 65537)
8256 .Digest(Digest::NONE)
8257 .Padding(PaddingMode::NONE)
8258 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008259 .Authorization(TAG_ROLLBACK_RESISTANCE)
8260 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008261 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8262 GTEST_SKIP() << "Rollback resistance not supported";
8263 }
Selene Huang31ab4042020-04-29 04:22:39 -07008264
8265 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008266 ASSERT_EQ(ErrorCode::OK, error);
8267 AuthorizationSet enforced(SecLevelAuthorizations());
8268 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008269
David Drysdale513bf122021-10-06 11:53:13 +01008270 // Delete the key we don't care about the result at this point.
8271 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07008272
David Drysdale513bf122021-10-06 11:53:13 +01008273 // Now create an invalid key blob and delete it.
8274 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07008275
David Drysdale513bf122021-10-06 11:53:13 +01008276 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07008277}
8278
8279/**
8280 * KeyDeletionTest.DeleteAllKeys
8281 *
8282 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
8283 *
8284 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
8285 * FBE/FDE encryption keys, which means that the device will not even boot until after the
8286 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
8287 * been provisioned. Use this test only on dedicated testing devices that have no valuable
8288 * credentials stored in Keystore/Keymint.
8289 */
8290TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01008291 if (!arm_deleteAllKeys) {
8292 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
8293 return;
8294 }
Selene Huang31ab4042020-04-29 04:22:39 -07008295 auto error = GenerateKey(AuthorizationSetBuilder()
8296 .RsaSigningKey(2048, 65537)
8297 .Digest(Digest::NONE)
8298 .Padding(PaddingMode::NONE)
8299 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06008300 .Authorization(TAG_ROLLBACK_RESISTANCE)
8301 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008302 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8303 GTEST_SKIP() << "Rollback resistance not supported";
8304 }
Selene Huang31ab4042020-04-29 04:22:39 -07008305
8306 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008307 ASSERT_EQ(ErrorCode::OK, error);
8308 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8309 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008310
David Drysdale513bf122021-10-06 11:53:13 +01008311 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07008312
David Drysdale513bf122021-10-06 11:53:13 +01008313 string message = "12345678901234567890123456789012";
8314 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07008315
David Drysdale513bf122021-10-06 11:53:13 +01008316 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8317 Begin(KeyPurpose::SIGN, key_blob_,
8318 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8319 &begin_out_params));
8320 AbortIfNeeded();
8321 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008322}
8323
8324INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8325
David Drysdaled2cc8c22021-04-15 13:29:45 +01008326typedef KeyMintAidlTestBase KeyUpgradeTest;
8327
8328/**
8329 * KeyUpgradeTest.UpgradeInvalidKey
8330 *
8331 * This test checks that the HAL excepts invalid key blobs..
8332 */
8333TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8334 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8335
8336 std::vector<uint8_t> new_blob;
8337 Status result = keymint_->upgradeKey(key_blob,
8338 AuthorizationSetBuilder()
8339 .Authorization(TAG_APPLICATION_ID, "clientid")
8340 .Authorization(TAG_APPLICATION_DATA, "appdata")
8341 .vector_data(),
8342 &new_blob);
8343 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8344}
8345
8346INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8347
Selene Huang31ab4042020-04-29 04:22:39 -07008348using UpgradeKeyTest = KeyMintAidlTestBase;
8349
8350/*
8351 * UpgradeKeyTest.UpgradeKey
8352 *
8353 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8354 */
8355TEST_P(UpgradeKeyTest, UpgradeKey) {
8356 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8357 .AesEncryptionKey(128)
8358 .Padding(PaddingMode::NONE)
8359 .Authorization(TAG_NO_AUTH_REQUIRED)));
8360
8361 auto result = UpgradeKey(key_blob_);
8362
8363 // Key doesn't need upgrading. Should get okay, but no new key blob.
8364 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8365}
8366
8367INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8368
8369using ClearOperationsTest = KeyMintAidlTestBase;
8370
8371/*
8372 * ClearSlotsTest.TooManyOperations
8373 *
8374 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8375 * operations are started without being finished or aborted. Also verifies
8376 * that aborting the operations clears the operations.
8377 *
8378 */
8379TEST_P(ClearOperationsTest, TooManyOperations) {
8380 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8381 .Authorization(TAG_NO_AUTH_REQUIRED)
8382 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008383 .Padding(PaddingMode::NONE)
8384 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008385
8386 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8387 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008388 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008389 AuthorizationSet out_params;
8390 ErrorCode result;
8391 size_t i;
8392
8393 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008394 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008395 if (ErrorCode::OK != result) {
8396 break;
8397 }
8398 }
8399 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8400 // Try again just in case there's a weird overflow bug
8401 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008402 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008403 for (size_t j = 0; j < i; j++) {
8404 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8405 << "Aboort failed for i = " << j << std::endl;
8406 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008407 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008408 AbortIfNeeded();
8409}
8410
8411INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8412
8413typedef KeyMintAidlTestBase TransportLimitTest;
8414
8415/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008416 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008417 *
8418 * Verifies that passing input data to finish succeeds as expected.
8419 */
8420TEST_P(TransportLimitTest, LargeFinishInput) {
8421 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8422 .Authorization(TAG_NO_AUTH_REQUIRED)
8423 .AesEncryptionKey(128)
8424 .BlockMode(BlockMode::ECB)
8425 .Padding(PaddingMode::NONE)));
8426
8427 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008428 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008429 auto cipher_params =
8430 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8431
8432 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008433 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008434
8435 string plain_message = std::string(1 << msg_size, 'x');
8436 string encrypted_message;
8437 auto rc = Finish(plain_message, &encrypted_message);
8438
8439 EXPECT_EQ(ErrorCode::OK, rc);
8440 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8441 << "Encrypt finish returned OK, but did not consume all of the given input";
8442 cipher_params.push_back(out_params);
8443
David Drysdale7fc26b92022-05-13 09:54:24 +01008444 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008445
8446 string decrypted_message;
8447 rc = Finish(encrypted_message, &decrypted_message);
8448 EXPECT_EQ(ErrorCode::OK, rc);
8449 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8450 << "Decrypt finish returned OK, did not consume all of the given input";
8451 }
8452}
8453
8454INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8455
Seth Moored79a0ec2021-12-13 20:03:33 +00008456static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008457 switch (curve) {
8458 case EcCurve::P_224:
8459 return NID_secp224r1;
8460 case EcCurve::P_256:
8461 return NID_X9_62_prime256v1;
8462 case EcCurve::P_384:
8463 return NID_secp384r1;
8464 case EcCurve::P_521:
8465 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008466 case EcCurve::CURVE_25519:
8467 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008468 }
8469}
8470
David Drysdale42fe1892021-10-14 14:43:46 +01008471class KeyAgreementTest : public KeyMintAidlTestBase {
8472 protected:
8473 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8474 std::vector<uint8_t>* localPublicKey) {
8475 // Generate EC key locally (with access to private key material)
8476 if (localCurve == EcCurve::CURVE_25519) {
8477 uint8_t privKeyData[32];
8478 uint8_t pubKeyData[32];
8479 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008480 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8481 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8482 } else {
8483 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8484 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8485 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8486 ASSERT_NE(group, nullptr);
8487 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8488 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8489 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8490 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008491 }
David Drysdalea410b772022-05-09 16:44:13 +01008492
8493 // Get encoded form of the public part of the locally generated key...
8494 unsigned char* p = nullptr;
8495 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8496 ASSERT_GT(localPublicKeySize, 0);
8497 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8498 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8499 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008500 }
8501
8502 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8503 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008504 auto builder = AuthorizationSetBuilder()
8505 .Authorization(TAG_NO_AUTH_REQUIRED)
8506 .Authorization(TAG_EC_CURVE, curve)
8507 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8508 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8509 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8510 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8511 .SetDefaultValidity();
8512 ErrorCode result = GenerateKey(builder);
8513
8514 if (SecLevel() == SecurityLevel::STRONGBOX) {
8515 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8516 result = GenerateKeyWithSelfSignedAttestKey(
8517 AuthorizationSetBuilder()
8518 .EcdsaKey(EcCurve::P_256)
8519 .AttestKey()
8520 .SetDefaultValidity(), /* attest key params */
8521 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8522 }
8523 }
David Drysdale42fe1892021-10-14 14:43:46 +01008524 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8525 ASSERT_GT(cert_chain_.size(), 0);
8526 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8527 ASSERT_NE(kmKeyCert, nullptr);
8528 // Check that keyAgreement (bit 4) is set in KeyUsage
8529 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8530 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8531 ASSERT_NE(*kmPubKey, nullptr);
8532 if (dump_Attestations) {
8533 for (size_t n = 0; n < cert_chain_.size(); n++) {
8534 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8535 }
8536 }
8537 }
8538
8539 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8540 const std::vector<uint8_t>& localPublicKey) {
8541 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8542 string ZabFromKeyMintStr;
8543 ASSERT_EQ(ErrorCode::OK,
8544 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8545 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8546 vector<uint8_t> ZabFromTest;
8547
8548 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8549 size_t kmPubKeySize = 32;
8550 uint8_t kmPubKeyData[32];
8551 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8552 ASSERT_EQ(kmPubKeySize, 32);
8553
8554 uint8_t localPrivKeyData[32];
8555 size_t localPrivKeySize = 32;
8556 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8557 &localPrivKeySize));
8558 ASSERT_EQ(localPrivKeySize, 32);
8559
8560 uint8_t sharedKey[32];
8561 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8562 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8563 } else {
8564 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8565 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8566 ASSERT_NE(ctx, nullptr);
8567 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8568 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8569 size_t ZabFromTestLen = 0;
8570 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8571 ZabFromTest.resize(ZabFromTestLen);
8572 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8573 }
8574 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8575 }
8576};
8577
David Zeuthene0c40892021-01-08 12:54:11 -05008578/*
8579 * KeyAgreementTest.Ecdh
8580 *
David Drysdale42fe1892021-10-14 14:43:46 +01008581 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008582 */
8583TEST_P(KeyAgreementTest, Ecdh) {
8584 // Because it's possible to use this API with keys on different curves, we
8585 // check all N^2 combinations where N is the number of supported
8586 // curves.
8587 //
8588 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8589 // lot more curves we can be smart about things and just pick |otherCurve| so
8590 // it's not |curve| and that way we end up with only 2*N runs
8591 //
8592 for (auto curve : ValidCurves()) {
8593 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008594 SCOPED_TRACE(testing::Message()
8595 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8596
David Zeuthene0c40892021-01-08 12:54:11 -05008597 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008598 EVP_PKEY_Ptr localPrivKey;
8599 vector<uint8_t> localPublicKey;
8600 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008601
8602 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008603 EVP_PKEY_Ptr kmPubKey;
8604 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008605
8606 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8607 if (curve != localCurve) {
8608 // If the keys are using different curves KeyMint should fail with
8609 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008610 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008611 string ZabFromKeyMintStr;
8612 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008613 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008614 &ZabFromKeyMintStr));
8615
8616 } else {
8617 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008618 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008619 }
8620
8621 CheckedDeleteKey();
8622 }
8623 }
8624}
8625
David Drysdale42fe1892021-10-14 14:43:46 +01008626/*
8627 * KeyAgreementTest.EcdhCurve25519
8628 *
8629 * Verifies that ECDH works for curve25519. This is also covered by the general
8630 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8631 * KeyMint 1.0.
8632 */
8633TEST_P(KeyAgreementTest, EcdhCurve25519) {
8634 if (!Curve25519Supported()) {
8635 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8636 }
8637
8638 // Generate EC key in KeyMint (only access to public key material)
8639 EcCurve curve = EcCurve::CURVE_25519;
8640 EVP_PKEY_Ptr kmPubKey = nullptr;
8641 GenerateKeyMintEcKey(curve, &kmPubKey);
8642
8643 // Generate EC key on same curve locally (with access to private key material).
8644 EVP_PKEY_Ptr privKey;
8645 vector<uint8_t> encodedPublicKey;
8646 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8647
8648 // Agree on a key between local and KeyMint and check it.
8649 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8650
8651 CheckedDeleteKey();
8652}
8653
8654/*
8655 * KeyAgreementTest.EcdhCurve25519Imported
8656 *
8657 * Verifies that ECDH works for an imported curve25519 key.
8658 */
8659TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8660 if (!Curve25519Supported()) {
8661 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8662 }
8663
8664 // Import x25519 key into KeyMint.
8665 EcCurve curve = EcCurve::CURVE_25519;
8666 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8667 .Authorization(TAG_NO_AUTH_REQUIRED)
8668 .EcdsaKey(EcCurve::CURVE_25519)
8669 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8670 .SetDefaultValidity(),
8671 KeyFormat::PKCS8, x25519_pkcs8_key));
8672 ASSERT_GT(cert_chain_.size(), 0);
8673 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8674 ASSERT_NE(kmKeyCert, nullptr);
8675 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8676 ASSERT_NE(kmPubKey.get(), nullptr);
8677
8678 // Expect the import to emit corresponding public key data.
8679 size_t kmPubKeySize = 32;
8680 uint8_t kmPubKeyData[32];
8681 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8682 ASSERT_EQ(kmPubKeySize, 32);
8683 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8684 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8685
8686 // Generate EC key on same curve locally (with access to private key material).
8687 EVP_PKEY_Ptr privKey;
8688 vector<uint8_t> encodedPublicKey;
8689 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8690
8691 // Agree on a key between local and KeyMint and check it.
8692 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8693
8694 CheckedDeleteKey();
8695}
8696
8697/*
8698 * KeyAgreementTest.EcdhCurve25519InvalidSize
8699 *
8700 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8701 */
8702TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8703 if (!Curve25519Supported()) {
8704 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8705 }
8706
8707 // Generate EC key in KeyMint (only access to public key material)
8708 EcCurve curve = EcCurve::CURVE_25519;
8709 EVP_PKEY_Ptr kmPubKey = nullptr;
8710 GenerateKeyMintEcKey(curve, &kmPubKey);
8711
8712 // Generate EC key on same curve locally (with access to private key material).
8713 EVP_PKEY_Ptr privKey;
8714 vector<uint8_t> encodedPublicKey;
8715 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8716
8717 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8718 string ZabFromKeyMintStr;
8719 // Send in an incomplete public key.
8720 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8721 &ZabFromKeyMintStr));
8722
8723 CheckedDeleteKey();
8724}
8725
8726/*
8727 * KeyAgreementTest.EcdhCurve25519Mismatch
8728 *
8729 * Verifies that ECDH fails between curve25519 and other curves.
8730 */
8731TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8732 if (!Curve25519Supported()) {
8733 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8734 }
8735
8736 // Generate EC key in KeyMint (only access to public key material)
8737 EcCurve curve = EcCurve::CURVE_25519;
8738 EVP_PKEY_Ptr kmPubKey = nullptr;
8739 GenerateKeyMintEcKey(curve, &kmPubKey);
8740
8741 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008742 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008743 if (localCurve == curve) {
8744 continue;
8745 }
8746 // Generate EC key on a different curve locally (with access to private key material).
8747 EVP_PKEY_Ptr privKey;
8748 vector<uint8_t> encodedPublicKey;
8749 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8750
David Drysdale7fc26b92022-05-13 09:54:24 +01008751 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008752 string ZabFromKeyMintStr;
8753 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8754 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8755 &ZabFromKeyMintStr));
8756 }
8757
8758 CheckedDeleteKey();
8759}
8760
David Zeuthene0c40892021-01-08 12:54:11 -05008761INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8762
David Drysdaled2cc8c22021-04-15 13:29:45 +01008763using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8764
8765// This is a problematic test, as it can render the device under test permanently unusable.
8766// Re-enable and run at your own risk.
8767TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8768 auto result = DestroyAttestationIds();
8769 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8770}
8771
8772INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8773
Shawn Willdend659c7c2021-02-19 14:51:51 -07008774using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008775
David Drysdaledb0dcf52021-05-18 11:43:31 +01008776/*
8777 * EarlyBootKeyTest.CreateEarlyBootKeys
8778 *
8779 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8780 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008781TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008782 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008783 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8784 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008785 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8786 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8787 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8788 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008789
David Drysdaleadfe6112021-05-27 12:00:53 +01008790 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8791 ASSERT_GT(keyData.blob.size(), 0U);
8792 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8793 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8794 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008795}
8796
David Drysdaledb0dcf52021-05-18 11:43:31 +01008797/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008798 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8799 *
8800 * Verifies that creating an early boot key with attestation succeeds.
8801 */
8802TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8803 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8804 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8805 builder->AttestationChallenge("challenge");
8806 builder->AttestationApplicationId("app_id");
8807 });
David Drysdale1b9febc2023-06-07 13:43:24 +01008808 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8809 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8810 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8811 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
David Drysdaleadfe6112021-05-27 12:00:53 +01008812
8813 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008814 // Strongbox may not support factory attestation. Key creation might fail with
8815 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8816 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8817 continue;
8818 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008819 ASSERT_GT(keyData.blob.size(), 0U);
8820 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8821 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8822 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008823}
8824
8825/*
8826 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008827 *
8828 * Verifies that using early boot keys at a later stage fails.
8829 */
8830TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8831 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8832 .Authorization(TAG_NO_AUTH_REQUIRED)
8833 .Authorization(TAG_EARLY_BOOT_ONLY)
8834 .HmacKey(128)
8835 .Digest(Digest::SHA_2_256)
8836 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8837 AuthorizationSet output_params;
8838 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8839 AuthorizationSetBuilder()
8840 .Digest(Digest::SHA_2_256)
8841 .Authorization(TAG_MAC_LENGTH, 256),
8842 &output_params));
8843}
8844
8845/*
8846 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8847 *
8848 * Verifies that importing early boot keys fails.
8849 */
8850TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8851 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8852 .Authorization(TAG_NO_AUTH_REQUIRED)
8853 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008854 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008855 .Digest(Digest::SHA_2_256)
8856 .SetDefaultValidity(),
8857 KeyFormat::PKCS8, ec_256_key));
8858}
8859
David Drysdaled2cc8c22021-04-15 13:29:45 +01008860// 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 +00008861// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8862// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8863// early boot, so you'll have to reboot between runs.
8864TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8865 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8866 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008867 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8868 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8869 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8870 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
8871
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008872 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8873 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8874 EXPECT_TRUE(
8875 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8876 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8877 EXPECT_TRUE(
8878 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8879
8880 // Should be able to use keys, since early boot has not ended
8881 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8882 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8883 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8884 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8885
8886 // End early boot
8887 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8888 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8889
8890 // Should not be able to use already-created keys.
8891 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8892 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8893 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8894 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8895
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008896 // Should not be able to create new keys
David Drysdale1b9febc2023-06-07 13:43:24 +01008897 auto [aesKeyData2, hmacKeyData2, rsaKeyData2, ecdsaKeyData2] =
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008898 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
David Drysdale1b9febc2023-06-07 13:43:24 +01008899 KeyBlobDeleter aes_deleter2(keymint_, aesKeyData2.blob);
8900 KeyBlobDeleter hmac_deleter2(keymint_, hmacKeyData2.blob);
8901 KeyBlobDeleter rsa_deleter2(keymint_, rsaKeyData2.blob);
8902 KeyBlobDeleter ecdsa_deleter2(keymint_, ecdsaKeyData2.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008903}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008904
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008905INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8906
Shawn Willden22fb9c12022-06-02 14:04:33 -06008907using VsrRequirementTest = KeyMintAidlTestBase;
8908
Eran Messeri5fe06ea2023-08-02 22:34:24 +01008909// @VsrTest = VSR-3.10-008
Shawn Willden22fb9c12022-06-02 14:04:33 -06008910TEST_P(VsrRequirementTest, Vsr13Test) {
8911 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008912 if (vsr_api_level < __ANDROID_API_T__) {
Shawn Willden22fb9c12022-06-02 14:04:33 -06008913 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8914 }
8915 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8916}
8917
Eran Messeri5fe06ea2023-08-02 22:34:24 +01008918// @VsrTest = VSR-3.10-013.001
Eran Messerib9346f52022-12-15 14:58:34 +00008919TEST_P(VsrRequirementTest, Vsr14Test) {
8920 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008921 if (vsr_api_level < __ANDROID_API_U__) {
Eran Messerib9346f52022-12-15 14:58:34 +00008922 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8923 }
8924 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8925}
8926
Shawn Willden22fb9c12022-06-02 14:04:33 -06008927INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8928
David Drysdale6c9bdb82024-01-23 09:32:04 +00008929class InstanceTest : public testing::Test {
8930 protected:
8931 static void SetUpTestSuite() {
8932 auto params = ::android::getAidlHalInstanceNames(IKeyMintDevice::descriptor);
8933 for (auto& param : params) {
8934 ASSERT_TRUE(AServiceManager_isDeclared(param.c_str()))
8935 << "IKeyMintDevice instance " << param << " found but not declared.";
8936 ::ndk::SpAIBinder binder(AServiceManager_waitForService(param.c_str()));
8937 auto keymint = IKeyMintDevice::fromBinder(binder);
8938 ASSERT_NE(keymint, nullptr) << "Failed to get IKeyMintDevice instance " << param;
8939
8940 KeyMintHardwareInfo info;
8941 ASSERT_TRUE(keymint->getHardwareInfo(&info).isOk());
8942 ASSERT_EQ(keymints_.count(info.securityLevel), 0)
8943 << "There must be exactly one IKeyMintDevice with security level "
8944 << info.securityLevel;
8945
8946 keymints_[info.securityLevel] = std::move(keymint);
8947 }
8948 }
8949
8950 int32_t AidlVersion(shared_ptr<IKeyMintDevice> keymint) {
8951 int32_t version = 0;
8952 auto status = keymint->getInterfaceVersion(&version);
8953 if (!status.isOk()) {
8954 ADD_FAILURE() << "Failed to determine interface version";
8955 }
8956 return version;
8957 }
8958
8959 static std::map<SecurityLevel, shared_ptr<IKeyMintDevice>> keymints_;
8960};
8961
8962std::map<SecurityLevel, shared_ptr<IKeyMintDevice>> InstanceTest::keymints_;
8963
8964// @VsrTest = VSR-3.10-017
8965// Check that the AIDL version advertised by the HAL service matches
8966// the value in the package manager feature version.
8967TEST_F(InstanceTest, AidlVersionInFeature) {
8968 if (is_gsi_image()) {
8969 GTEST_SKIP() << "Versions not required to match under GSI";
8970 }
8971 if (keymints_.count(SecurityLevel::TRUSTED_ENVIRONMENT) == 1) {
8972 auto tee = keymints_.find(SecurityLevel::TRUSTED_ENVIRONMENT)->second;
8973 int32_t tee_aidl_version = AidlVersion(tee) * 100;
8974 std::optional<int32_t> tee_feature_version = keymint_feature_value(/* strongbox */ false);
8975 ASSERT_TRUE(tee_feature_version.has_value());
8976 EXPECT_EQ(tee_aidl_version, tee_feature_version.value());
8977 }
8978 if (keymints_.count(SecurityLevel::STRONGBOX) == 1) {
8979 auto sb = keymints_.find(SecurityLevel::STRONGBOX)->second;
8980 int32_t sb_aidl_version = AidlVersion(sb) * 100;
8981 std::optional<int32_t> sb_feature_version = keymint_feature_value(/* strongbox */ true);
8982 ASSERT_TRUE(sb_feature_version.has_value());
8983 EXPECT_EQ(sb_aidl_version, sb_feature_version.value());
8984 }
8985}
8986
8987// @VsrTest = VSR-3.10-017
8988// Check that if package manager advertises support for KeyMint of a particular version, that
8989// version is present as a HAL service.
8990TEST_F(InstanceTest, FeatureVersionInAidl) {
8991 if (is_gsi_image()) {
8992 GTEST_SKIP() << "Versions not required to match under GSI";
8993 }
8994 std::optional<int32_t> tee_feature_version = keymint_feature_value(/* strongbox */ false);
8995 if (tee_feature_version.has_value() && tee_feature_version.value() >= 100) {
8996 // Feature flag advertises the existence of KeyMint; check it is present.
8997 ASSERT_EQ(keymints_.count(SecurityLevel::TRUSTED_ENVIRONMENT), 1);
8998 auto tee = keymints_.find(SecurityLevel::TRUSTED_ENVIRONMENT)->second;
8999 int32_t tee_aidl_version = AidlVersion(tee) * 100;
9000 EXPECT_EQ(tee_aidl_version, tee_feature_version.value());
9001 }
9002
9003 std::optional<int32_t> sb_feature_version = keymint_feature_value(/* strongbox */ true);
9004 if (sb_feature_version.has_value() && sb_feature_version.value() >= 100) {
9005 // Feature flag advertises the existence of KeyMint; check it is present.
9006 ASSERT_EQ(keymints_.count(SecurityLevel::STRONGBOX), 1);
9007 auto sb = keymints_.find(SecurityLevel::STRONGBOX)->second;
9008 int32_t sb_aidl_version = AidlVersion(sb) * 100;
9009 EXPECT_EQ(sb_aidl_version, sb_feature_version.value());
9010 }
9011}
9012
Janis Danisevskis24c04702020-12-16 18:28:39 -08009013} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07009014
David Drysdale77a86d82024-01-03 11:22:56 +00009015using aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase;
9016
Selene Huang31ab4042020-04-29 04:22:39 -07009017int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07009018 std::cout << "Testing ";
David Drysdale77a86d82024-01-03 11:22:56 +00009019 auto halInstances = KeyMintAidlTestBase::build_params();
Shawn Willden7c130392020-12-21 09:58:22 -07009020 std::cout << "HAL instances:\n";
9021 for (auto& entry : halInstances) {
9022 std::cout << " " << entry << '\n';
9023 }
9024
Selene Huang31ab4042020-04-29 04:22:39 -07009025 ::testing::InitGoogleTest(&argc, argv);
9026 for (int i = 1; i < argc; ++i) {
9027 if (argv[i][0] == '-') {
9028 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
David Drysdale77a86d82024-01-03 11:22:56 +00009029 KeyMintAidlTestBase::arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07009030 }
9031 if (std::string(argv[i]) == "--dump_attestations") {
David Drysdale77a86d82024-01-03 11:22:56 +00009032 KeyMintAidlTestBase::dump_Attestations = true;
Shawn Willden7c130392020-12-21 09:58:22 -07009033 } else {
9034 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07009035 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00009036 if (std::string(argv[i]) == "--skip_boot_pl_check") {
9037 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
9038 // be run in emulated environments that don't have the normal bootloader
9039 // interactions.
9040 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
9041 }
David Drysdale9f5c0c52022-11-03 15:10:16 +00009042 if (std::string(argv[i]) == "--keyblob_dir") {
9043 if (i + 1 >= argc) {
9044 std::cerr << "Missing argument for --keyblob_dir\n";
9045 return 1;
9046 }
David Drysdale77a86d82024-01-03 11:22:56 +00009047 KeyMintAidlTestBase::keyblob_dir = std::string(argv[i + 1]);
David Drysdale9f5c0c52022-11-03 15:10:16 +00009048 ++i;
9049 }
Tommy Chiu025f3c52023-05-15 06:23:44 +00009050 if (std::string(argv[i]) == "--expect_upgrade") {
9051 if (i + 1 >= argc) {
9052 std::cerr << "Missing argument for --expect_upgrade\n";
9053 return 1;
9054 }
9055 std::string arg = argv[i + 1];
David Drysdale77a86d82024-01-03 11:22:56 +00009056 KeyMintAidlTestBase::expect_upgrade =
9057 arg == "yes" ? true
9058 : (arg == "no" ? false : std::optional<bool>(std::nullopt));
9059 if (KeyMintAidlTestBase::expect_upgrade.has_value()) {
9060 std::cout << "expect_upgrade = "
9061 << (KeyMintAidlTestBase::expect_upgrade.value() ? "true" : "false")
9062 << std::endl;
9063 } else {
9064 std::cerr << "Error! Option --expect_upgrade " << arg << " unrecognized"
9065 << std::endl;
9066 }
Tommy Chiu025f3c52023-05-15 06:23:44 +00009067 ++i;
9068 }
Selene Huang31ab4042020-04-29 04:22:39 -07009069 }
9070 }
Shawn Willden08a7e432020-12-11 13:05:27 +00009071 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07009072}