blob: 416e6c095b79b76cc3040ee55618761a5ab2ce5b [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>
David Drysdaleb4598742024-04-23 13:35:15 +010025#include <set>
Selene Huang31ab4042020-04-29 04:22:39 -070026
David Drysdale42fe1892021-10-14 14:43:46 +010027#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050028#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070029#include <openssl/evp.h>
30#include <openssl/mem.h>
David Drysdalead785f52023-03-27 19:53:01 +010031#include <openssl/x509.h>
David Zeuthene0c40892021-01-08 12:54:11 -050032#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070033
34#include <cutils/properties.h>
35
David Drysdale4dc01072021-04-01 12:17:35 +010036#include <android/binder_manager.h>
37
38#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080039#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070040
Seth Moorec5c52ce2024-04-07 15:26:33 -070041#include <keymint_support/authorization_set.h>
Shawn Willden08a7e432020-12-11 13:05:27 +000042#include <keymint_support/key_param_output.h>
43#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070044
45#include "KeyMintAidlTestBase.h"
46
Janis Danisevskis24c04702020-12-16 18:28:39 -080047using aidl::android::hardware::security::keymint::AuthorizationSet;
48using aidl::android::hardware::security::keymint::KeyCharacteristics;
49using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070050
Selene Huang31ab4042020-04-29 04:22:39 -070051namespace std {
52
Janis Danisevskis24c04702020-12-16 18:28:39 -080053using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070054
55template <>
56struct std::equal_to<KeyCharacteristics> {
57 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070058 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070059
Shawn Willden7f424372021-01-10 18:06:50 -070060 // this isn't very efficient. Oh, well.
61 AuthorizationSet a_auths(a.authorizations);
62 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070063
Shawn Willden7f424372021-01-10 18:06:50 -070064 a_auths.Sort();
65 b_auths.Sort();
66
67 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070068 }
69};
70
71} // namespace std
72
Janis Danisevskis24c04702020-12-16 18:28:39 -080073namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000074
Selene Huang31ab4042020-04-29 04:22:39 -070075namespace {
76
David Drysdalefeab5d92022-01-06 15:46:23 +000077// Maximum supported Ed25519 message size.
78const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
79
David Drysdaledbbbe2e2021-12-02 07:44:23 +000080// Whether to check that BOOT_PATCHLEVEL is populated.
81bool check_boot_pl = true;
82
Seth Moore7a55ae32021-06-23 14:28:11 -070083// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000084// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070085// is a small (roughly 1/256) chance that corrupting ciphertext still results
86// in valid PKCS7 padding.
87constexpr size_t kMaxPaddingCorruptionRetries = 8;
88
Selene Huang31ab4042020-04-29 04:22:39 -070089template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000090bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
91 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070092 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080093 if (auto p = authorizationValue(ttag, param)) {
94 return *p == expected_value;
95 }
96 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070097 });
98 return (it != set.end());
99}
100
101template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000102bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -0700103 auto it = std::find_if(set.begin(), set.end(),
104 [&](const KeyParameter& param) { return param.tag == tag; });
105 return (it != set.end());
106}
107
108constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
111 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
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, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
123 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
124
125string hex2str(string a) {
126 string b;
127 size_t num = a.size() / 2;
128 b.resize(num);
129 for (size_t i = 0; i < num; i++) {
130 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
131 }
132 return b;
133}
134
David Drysdaled2cc8c22021-04-15 13:29:45 +0100135string rsa_key = hex2str(
136 // RFC 5208 s5
137 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
138 "020100" // INTEGER length 1 value 0x00 (version)
139 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
140 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
141 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
142 "0500" // NULL (parameters)
143 // } end SEQUENCE (AlgorithmIdentifier)
144 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
145 // RFC 8017 A.1.2
146 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
147 "020100" // INTEGER length 1 value 0x00 (version)
148 "028181" // INTEGER length 0x81 value (modulus) ...
149 "00c6095409047d8634812d5a218176e4"
150 "5c41d60a75b13901f234226cffe77652"
151 "1c5a77b9e389417b71c0b6a44d13afe4"
152 "e4a2805d46c9da2935adb1ff0c1f24ea"
153 "06e62b20d776430a4d435157233c6f91"
154 "6783c30e310fcbd89b85c2d567711697"
155 "85ac12bca244abda72bfb19fc44d27c8"
156 "1e1d92de284f4061edfd99280745ea6d"
157 "25"
158 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
159 "028180" // INTEGER length 0x80 (privateExponent) value...
160 "1be0f04d9cae3718691f035338308e91"
161 "564b55899ffb5084d2460e6630257e05"
162 "b3ceab02972dfabcd6ce5f6ee2589eb6"
163 "7911ed0fac16e43a444b8c861e544a05"
164 "93365772f8baf6b22fc9e3c5f1024b06"
165 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
166 "ace7240290bef16c0b3f7f3cdd64ce3a"
167 "b5912cf6e32f39ab188358afcccd8081"
168 "0241" // INTEGER length 0x41 (prime1)
169 "00e4b49ef50f765d3b24dde01aceaaf1"
170 "30f2c76670a91a61ae08af497b4a82be"
171 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
172 "8c92bfab137fba2285227b83c342ff7c"
173 "55"
174 "0241" // INTEGER length 0x41 (prime2)
175 "00ddabb5839c4c7f6bf3d4183231f005"
176 "b31aa58affdda5c79e4cce217f6bc930"
177 "dbe563d480706c24e9ebfcab28a6cdef"
178 "d324b77e1bf7251b709092c24ff501fd"
179 "91"
180 "0240" // INTEGER length 0x40 (exponent1)
181 "23d4340eda3445d8cd26c14411da6fdc"
182 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
183 "842c1d280405bc2f6c1bea214a1d742a"
184 "b996b35b63a82a5e470fa88dbf823cdd"
185 "0240" // INTEGER length 0x40 (exponent2)
186 "1b7b57449ad30d1518249a5f56bb9829"
187 "4d4b6ac12ffc86940497a5a5837a6cf9"
188 "46262b494526d328c11e1126380fde04"
189 "c24f916dec250892db09a6d77cdba351"
190 "0240" // INTEGER length 0x40 (coefficient)
191 "7762cd8f4d050da56bd591adb515d24d"
192 "7ccd32cca0d05f866d583514bd7324d5"
193 "f33645e8ed8b4a1cb3cc4a1d67987399"
194 "f2a09f5b3fb68c88d5e5d90ac33492d6"
195 // } end SEQUENCE (PrivateKey)
196 // } end SEQUENCE (PrivateKeyInfo)
197);
Selene Huang31ab4042020-04-29 04:22:39 -0700198
Selene Huange5727e62021-04-13 22:41:20 -0700199/*
200 * DER-encoded PKCS#8 format RSA key. Generated using:
201 *
202 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
203 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100204string rsa_2048_key = hex2str(
205 // RFC 5208 s5
206 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
207 "020100" // INTEGER length 1 value 0x00 (version)
208 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
209 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
210 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
211 "0500" // NULL (parameters)
212 // } end SEQUENCE (AlgorithmIdentifier)
213 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
214 // RFC 8017 A.1.2
215 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
216 "020100" // INTEGER length 1 value 0x00 (version)
217 "02820101" // INTEGER length 0x101 value (modulus) ...
218 "00BEBC342B56D443B1299F9A6A7056E8"
219 "0A897E318476A5A18029E63B2ED739A6"
220 "1791D339F58DC763D9D14911F2EDEC38"
221 "3DEE11F6319B44510E7A3ECD9B79B973"
222 "82E49500ACF8117DC89CAF0E621F7775"
223 "6554A2FD4664BFE7AB8B59AB48340DBF"
224 "A27B93B5A81F6ECDEB02D0759307128D"
225 "F3E3BAD4055C8B840216DFAA5700670E"
226 "6C5126F0962FCB70FF308F25049164CC"
227 "F76CC2DA66A7DD9A81A714C2809D6918"
228 "6133D29D84568E892B6FFBF3199BDB14"
229 "383EE224407F190358F111A949552ABA"
230 "6714227D1BD7F6B20DD0CB88F9467B71"
231 "9339F33BFF35B3870B3F62204E4286B0"
232 "948EA348B524544B5F9838F29EE643B0"
233 "79EEF8A713B220D7806924CDF7295070"
234 "C5"
235 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
236 "02820100" // INTEGER length 0x100 (privateExponent) value...
237 "69F377F35F2F584EF075353CCD1CA997"
238 "38DB3DBC7C7FF35F9366CE176DFD1B13"
239 "5AB10030344ABF5FBECF1D4659FDEF1C"
240 "0FC430834BE1BE3911951377BB3D563A"
241 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
242 "2686C7B4B3C09A7B8354133E6F93F790"
243 "D59EAEB92E84C9A4339302CCE28FDF04"
244 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
245 "6AB706645BF074A4E4090D06FB163124"
246 "365FD5EE7A20D350E9958CC30D91326E"
247 "1B292E9EF5DB408EC42DAF737D201497"
248 "04D0A678A0FB5B5446863B099228A352"
249 "D604BA8091A164D01D5AB05397C71EAD"
250 "20BE2A08FC528FE442817809C787FEE4"
251 "AB97F97B9130D022153EDC6EB6CBE7B0"
252 "F8E3473F2E901209B5DB10F93604DB01"
253 "028181" // INTEGER length 0x81 (prime1)
254 "00E83C0998214941EA4F9293F1B77E2E"
255 "99E6CF305FAF358238E126124FEAF2EB"
256 "9724B2EA7B78E6032343821A80E55D1D"
257 "88FB12D220C3F41A56142FEC85796D19"
258 "17F1E8C774F142B67D3D6E7B7E6B4383"
259 "E94DB5929089DBB346D5BDAB40CC2D96"
260 "EE0409475E175C63BF78CFD744136740"
261 "838127EA723FF3FE7FA368C1311B4A4E"
262 "05"
263 "028181" // INTEGER length 0x81 (prime2)
264 "00D240FCC0F5D7715CDE21CB2DC86EA1"
265 "46132EA3B06F61FF2AF54BF38473F59D"
266 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
267 "B1B58C39F95E4798CCBB43E83D0119AC"
268 "F532F359CA743C85199F0286610E2009"
269 "97D7312917179AC9B67558773212EC96"
270 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
271 "94D94E066A0900B7B70E82A44FB30053"
272 "C1"
273 "028181" // INTEGER length 0x81 (exponent1)
274 "00AD15DA1CBD6A492B66851BA8C316D3"
275 "8AB700E2CFDDD926A658003513C54BAA"
276 "152B30021D667D20078F500F8AD3E7F3"
277 "945D74A891ED1A28EAD0FEEAEC8C14A8"
278 "E834CF46A13D1378C99D18940823CFDD"
279 "27EC5810D59339E0C34198AC638E09C8"
280 "7CBB1B634A9864AE9F4D5EB2D53514F6"
281 "7B4CAEC048C8AB849A02E397618F3271"
282 "35"
283 "028180" // INTEGER length 0x80 (exponent2)
284 "1FA2C1A5331880A92D8F3E281C617108"
285 "BF38244F16E352E69ED417C7153F9EC3"
286 "18F211839C643DCF8B4DD67CE2AC312E"
287 "95178D5D952F06B1BF779F4916924B70"
288 "F582A23F11304E02A5E7565AE22A35E7"
289 "4FECC8B6FDC93F92A1A37703E4CF0E63"
290 "783BD02EB716A7ECBBFA606B10B74D01"
291 "579522E7EF84D91FC522292108D902C1"
292 "028180" // INTEGER length 0x80 (coefficient)
293 "796FE3825F9DCC85DF22D58690065D93"
294 "898ACD65C087BEA8DA3A63BF4549B795"
295 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
296 "0D74F40DED8E1102C52152A31B6165F8"
297 "3A6722AECFCC35A493D7634664B888A0"
298 "8D3EB034F12EA28BFEE346E205D33482"
299 "7F778B16ED40872BD29FCB36536B6E93"
300 "FFB06778696B4A9D81BB0A9423E63DE5"
301 // } end SEQUENCE (PrivateKey)
302 // } end SEQUENCE (PrivateKeyInfo)
303);
Selene Huange5727e62021-04-13 22:41:20 -0700304
David Drysdaled2cc8c22021-04-15 13:29:45 +0100305string ec_256_key = hex2str(
306 // RFC 5208 s5
307 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
308 "020100" // INTEGER length 1 value 0 (version)
309 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
310 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
311 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
312 "0608" // OBJECT IDENTIFIER length 8 (param)
313 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
314 // } end SEQUENCE (AlgorithmIdentifier)
315 "046d" // OCTET STRING length 0x6d (privateKey) holding...
316 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
317 "020101" // INTEGER length 1 value 1 (version)
318 "0420" // OCTET STRING length 0x20 (privateKey)
319 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
320 "941eed09366bc03299986481f3a4d859"
321 "a144" // TAG [1] len 0x44 (publicKey) {
322 "03420004bf85d7720d07c25461683bc6"
323 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
324 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
325 "bcc41c6eb00083cf3376d11fd44949e0"
326 "b2183bfe"
327 // } end SEQUENCE (ECPrivateKey)
328 // } end SEQUENCE (PrivateKeyInfo)
329);
Selene Huang31ab4042020-04-29 04:22:39 -0700330
David Drysdaled2cc8c22021-04-15 13:29:45 +0100331string ec_521_key = hex2str(
332 // RFC 5208 s5
333 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
334 "020100" // INTEGER length 1 value 0 (version)
335 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
336 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
337 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
338 "0605" // OBJECT IDENTIFIER length 5 (param)
339 "2B81040023" // 1.3.132.0.35 (secp521r1)
340 // } end SEQUENCE (AlgorithmIdentifier)
341 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
342 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
343 "020101" // INTEGER length 1 value 1 (version)
344 "0442" // OCTET STRING length 0x42 (privateKey)
345 "0011458C586DB5DAA92AFAB03F4FE46A"
346 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
347 "9D18D7D08B5BCFA0E53C75B064AD51C4"
348 "49BAE0258D54B94B1E885DED08ED4FB2"
349 "5CE9"
350 "A18189" // TAG [1] len 0x89 (publicKey) {
351 "03818600040149EC11C6DF0FA122C6A9"
352 "AFD9754A4FA9513A627CA329E349535A"
353 "5629875A8ADFBE27DCB932C051986377"
354 "108D054C28C6F39B6F2C9AF81802F9F3"
355 "26B842FF2E5F3C00AB7635CFB36157FC"
356 "0882D574A10D839C1A0C049DC5E0D775"
357 "E2EE50671A208431BB45E78E70BEFE93"
358 "0DB34818EE4D5C26259F5C6B8E28A652"
359 "950F9F88D7B4B2C9D9"
360 // } end SEQUENCE (ECPrivateKey)
361 // } end SEQUENCE (PrivateKeyInfo)
362);
Selene Huang31ab4042020-04-29 04:22:39 -0700363
David Drysdaled2cc8c22021-04-15 13:29:45 +0100364string ec_256_key_rfc5915 = hex2str(
365 // RFC 5208 s5
366 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
367 "020100" // INTEGER length 1 value 0 (version)
368 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
369 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
370 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
371 "0608" // OBJECT IDENTIFIER length 8 (param)
372 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
373 // } end SEQUENCE (AlgorithmIdentifier)
374 "0479" // OCTET STRING length 0x79 (privateKey) holding...
375 // RFC 5915 s3
376 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
377 "020101" // INTEGER length 1 value 1 (version)
378 "0420" // OCTET STRING length 0x42 (privateKey)
379 "782370a8c8ce5537baadd04dcff079c8"
380 "158cfa9c67b818b38e8d21c9fa750c1d"
381 "a00a" // TAG [0] length 0xa (parameters)
382 "0608" // OBJECT IDENTIFIER length 8
383 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
384 // } end TAG [0]
385 "a144" // TAG [1] length 0x44 (publicKey) {
386 "0342" // BIT STRING length 0x42
387 "00" // no pad bits
388 "04e2cc561ee701da0ad0ef0d176bb0c9"
389 "19d42e79c393fdc1bd6c4010d85cf2cf"
390 "8e68c905464666f98dad4f01573ba810"
391 "78b3428570a439ba3229fbc026c55068"
392 "2f"
393 // } end SEQUENCE (ECPrivateKey)
394 // } end SEQUENCE (PrivateKeyInfo)
395);
Selene Huang31ab4042020-04-29 04:22:39 -0700396
David Drysdaled2cc8c22021-04-15 13:29:45 +0100397string ec_256_key_sec1 = hex2str(
398 // RFC 5208 s5
399 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
400 "020100" // INTEGER length 1 value 0 (version)
401 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
402 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
403 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
404 "0608" // OBJECT IDENTIFIER length 8 (param)
405 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
406 // } end SEQUENCE (AlgorithmIdentifier)
407 "046d" // OCTET STRING length 0x6d (privateKey) holding...
408 // SEC1-v2 C.4
409 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
410 "020101" // INTEGER length 1 value 0x01 (version)
411 "0420" // OCTET STRING length 0x20 (privateKey)
412 "782370a8c8ce5537baadd04dcff079c8"
413 "158cfa9c67b818b38e8d21c9fa750c1d"
414 "a144" // TAG [1] length 0x44 (publicKey) {
415 "0342" // BIT STRING length 0x42
416 "00" // no pad bits
417 "04e2cc561ee701da0ad0ef0d176bb0c9"
418 "19d42e79c393fdc1bd6c4010d85cf2cf"
419 "8e68c905464666f98dad4f01573ba810"
420 "78b3428570a439ba3229fbc026c55068"
421 "2f"
422 // } end TAG [1] (publicKey)
423 // } end SEQUENCE (PrivateKeyInfo)
424);
Selene Huang31ab4042020-04-29 04:22:39 -0700425
David Drysdale42fe1892021-10-14 14:43:46 +0100426/**
427 * Ed25519 key pair generated as follows:
428 * ```
429 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
430 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
431 * Generating a ED25519 private key writing new private key to
432 * 'ed25519_priv.key'
433 * -----
434 * % cat ed25519_priv.key
435 * -----BEGIN PRIVATE KEY-----
436 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
437 * -----END PRIVATE KEY-----
438 * % der2ascii -pem -i ed25519_priv.key
439 * SEQUENCE {
440 * INTEGER { 0 }
441 * SEQUENCE {
442 * # ed25519
443 * OBJECT_IDENTIFIER { 1.3.101.112 }
444 * }
445 * OCTET_STRING {
446 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
447 * }
448 * }
449 * % cat ed25519.pem
450 * -----BEGIN CERTIFICATE-----
451 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
452 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
453 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
454 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
455 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
456 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
457 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
458 * -----END CERTIFICATE-----
459 * % openssl x509 -in ed25519.pem -text -noout
460 * Certificate:
461 * Data:
462 * Version: 3 (0x2)
463 * Serial Number:
464 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
465 * Signature Algorithm: ED25519
466 * Issuer: CN = fake.ed25519.com
467 * Validity
468 * Not Before: Oct 20 08:27:42 2021 GMT
469 * Not After : Sep 20 08:27:42 2023 GMT
470 * Subject: CN = fake.ed25519.com
471 * Subject Public Key Info:
472 * Public Key Algorithm: ED25519
473 * ED25519 Public-Key:
474 * pub:
475 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
476 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
477 * 56:91
478 * X509v3 extensions:
479 * X509v3 Subject Key Identifier:
480 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
481 * X509v3 Authority Key Identifier:
482 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
483 *
484 * X509v3 Basic Constraints: critical
485 * CA:TRUE
486 * Signature Algorithm: ED25519
487 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
488 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
489 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
490 * e7:07:32:60:32:8d:bb:eb:f6:0f
491 * ```
492 */
493string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
494string ed25519_pkcs8_key = hex2str(
495 // RFC 5208 s5
496 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
497 "0201" // INTEGER length 1 (Version)
498 "00" // version 0
499 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
500 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
501 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
502 // } end SEQUENCE (AlgorithmIdentifier)
503 "0422" // OCTET STRING length 0x22 (PrivateKey)
504 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
505 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
506 // } end SEQUENCE (PrivateKeyInfo)
507);
508string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
509
510/**
511 * X25519 key pair generated as follows:
512 * ```
513 * % openssl genpkey -algorithm X25519 > x25519_priv.key
514 * % cat x25519_priv.key
515 * -----BEGIN PRIVATE KEY-----
516 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
517 * -----END PRIVATE KEY-----
518 * % der2ascii -pem -i x25519_priv.key
519 * SEQUENCE {
520 * INTEGER { 0 }
521 * SEQUENCE {
522 * # x25519
523 * OBJECT_IDENTIFIER { 1.3.101.110 }
524 * }
525 * OCTET_STRING {
526 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
527 * }
528 * }
529 * ```
530 */
531
532string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
533string x25519_pkcs8_key = hex2str(
534 // RFC 5208 s5
535 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
536 "0201" // INTEGER length 1 (Version)
537 "00" // version 0
538 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
539 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
540 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
541 "0422" // OCTET STRING length 0x22 (PrivateKey)
542 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
543 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
544string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
545
Selene Huang31ab4042020-04-29 04:22:39 -0700546struct RSA_Delete {
547 void operator()(RSA* p) { RSA_free(p); }
548};
549
Selene Huang31ab4042020-04-29 04:22:39 -0700550std::string make_string(const uint8_t* data, size_t length) {
551 return std::string(reinterpret_cast<const char*>(data), length);
552}
553
554template <size_t N>
555std::string make_string(const uint8_t (&a)[N]) {
556 return make_string(a, N);
557}
558
559class AidlBuf : public vector<uint8_t> {
560 typedef vector<uint8_t> super;
561
562 public:
563 AidlBuf() {}
564 AidlBuf(const super& other) : super(other) {}
565 AidlBuf(super&& other) : super(std::move(other)) {}
566 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
567
568 AidlBuf& operator=(const super& other) {
569 super::operator=(other);
570 return *this;
571 }
572
573 AidlBuf& operator=(super&& other) {
574 super::operator=(std::move(other));
575 return *this;
576 }
577
578 AidlBuf& operator=(const string& other) {
579 resize(other.size());
580 for (size_t i = 0; i < other.size(); ++i) {
581 (*this)[i] = static_cast<uint8_t>(other[i]);
582 }
583 return *this;
584 }
585
586 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
587};
588
David Drysdale4dc01072021-04-01 12:17:35 +0100589string device_suffix(const string& name) {
590 size_t pos = name.find('/');
591 if (pos == string::npos) {
592 return name;
593 }
594 return name.substr(pos + 1);
595}
596
Seth Moore5a0320f2023-03-24 12:29:08 -0700597std::shared_ptr<IRemotelyProvisionedComponent> matching_rp_instance(const std::string& km_name) {
David Drysdale4dc01072021-04-01 12:17:35 +0100598 string km_suffix = device_suffix(km_name);
599
600 vector<string> rp_names =
601 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
602 for (const string& rp_name : rp_names) {
603 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
604 // KeyMint instance, assume they match.
605 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
606 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
Seth Moore5a0320f2023-03-24 12:29:08 -0700607 return IRemotelyProvisionedComponent::fromBinder(binder);
David Drysdale4dc01072021-04-01 12:17:35 +0100608 }
609 }
Seth Moore5a0320f2023-03-24 12:29:08 -0700610 return nullptr;
David Drysdale4dc01072021-04-01 12:17:35 +0100611}
612
Selene Huang31ab4042020-04-29 04:22:39 -0700613} // namespace
614
615class NewKeyGenerationTest : public KeyMintAidlTestBase {
616 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700617 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000618 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
Selene Huang31ab4042020-04-29 04:22:39 -0700619 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700620
Selene Huang31ab4042020-04-29 04:22:39 -0700621 // Check that some unexpected tags/values are NOT present.
622 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
623 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000624 }
625
626 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000627 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
David Drysdale7de9feb2021-03-05 14:56:19 +0000628 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
629 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
630
631 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000632 }
633
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000634 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics,
635 const KeyOrigin expectedKeyOrigin) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000636 // TODO(swillden): Distinguish which params should be in which auth list.
637 AuthorizationSet auths;
638 for (auto& entry : keyCharacteristics) {
639 auths.push_back(AuthorizationSet(entry.authorizations));
640 }
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000641 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, expectedKeyOrigin));
David Drysdale7de9feb2021-03-05 14:56:19 +0000642
643 // Verify that App data, ROT and auth timeout are NOT included.
644 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
645 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
David Drysdaleda0b04c2024-11-07 13:35:43 +0000646 EXPECT_FALSE(auths.Contains(TAG_MODULE_HASH));
Selene Huang31ab4042020-04-29 04:22:39 -0700647 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
648
David Drysdaled2cc8c22021-04-15 13:29:45 +0100649 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
650 // never adds it.
651 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
652
David Drysdale7de9feb2021-03-05 14:56:19 +0000653 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700654 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000655 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700656 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700657 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000658 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700659 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000660
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000661 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100662 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
663 EXPECT_TRUE(vendor_pl);
664 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000665
666 // Should include boot patchlevel (but there are some test scenarios where this is not
667 // possible).
668 if (check_boot_pl) {
669 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
670 EXPECT_TRUE(boot_pl);
671 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100672
David Drysdale7de9feb2021-03-05 14:56:19 +0000673 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700674 }
675};
676
677/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000678 * NewKeyGenerationTest.Aes
679 *
680 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
681 * have correct characteristics.
682 */
683TEST_P(NewKeyGenerationTest, Aes) {
684 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
685 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
686 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
687 SCOPED_TRACE(testing::Message()
688 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
689 vector<uint8_t> key_blob;
690 vector<KeyCharacteristics> key_characteristics;
691 auto builder = AuthorizationSetBuilder()
692 .AesEncryptionKey(key_size)
693 .BlockMode(block_mode)
694 .Padding(padding_mode)
695 .SetDefaultValidity();
696 if (block_mode == BlockMode::GCM) {
697 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
698 }
699 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100700 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000701
702 EXPECT_GT(key_blob.size(), 0U);
703 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100704 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000705
706 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
707
708 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
709 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
710 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000711 }
712 }
713 }
714}
715
716/*
717 * NewKeyGenerationTest.AesInvalidSize
718 *
719 * Verifies that specifying an invalid key size for AES key generation returns
720 * UNSUPPORTED_KEY_SIZE.
721 */
722TEST_P(NewKeyGenerationTest, AesInvalidSize) {
723 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
724 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
725 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
726 SCOPED_TRACE(testing::Message()
727 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
728 vector<uint8_t> key_blob;
729 vector<KeyCharacteristics> key_characteristics;
730 auto builder = AuthorizationSetBuilder()
731 .AesEncryptionKey(key_size)
732 .BlockMode(block_mode)
733 .Padding(padding_mode)
734 .SetDefaultValidity();
735 if (block_mode == BlockMode::GCM) {
736 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
737 }
738 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
739 GenerateKey(builder, &key_blob, &key_characteristics));
740 }
741 }
742 }
743
744 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
745 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100746 SCOPED_TRACE(testing::Message() << "AES-unknown-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000747 vector<uint8_t> key_blob;
748 vector<KeyCharacteristics> key_characteristics;
749 // No key size specified
750 auto builder = AuthorizationSetBuilder()
751 .Authorization(TAG_ALGORITHM, Algorithm::AES)
752 .BlockMode(block_mode)
753 .Padding(padding_mode)
754 .SetDefaultValidity();
755 if (block_mode == BlockMode::GCM) {
756 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
757 }
758 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
759 GenerateKey(builder, &key_blob, &key_characteristics));
760 }
761 }
762}
763
764/*
765 * NewKeyGenerationTest.AesInvalidPadding
766 *
767 * Verifies that specifying an invalid padding on AES keys gives a failure
768 * somewhere along the way.
769 */
770TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
771 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
772 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
773 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
774 SCOPED_TRACE(testing::Message()
775 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000776 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800777 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000778 .AesEncryptionKey(key_size)
779 .BlockMode(block_mode)
780 .Padding(padding_mode)
781 .SetDefaultValidity();
782 if (block_mode == BlockMode::GCM) {
783 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
784 }
785
Tommy Chiu3950b452021-05-03 22:01:46 +0800786 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000787 if (result == ErrorCode::OK) {
788 // Key creation was OK but has generated a key that cannot be used.
789 auto params =
790 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800791 if (block_mode == BlockMode::GCM) {
792 params.Authorization(TAG_MAC_LENGTH, 128);
793 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000794 auto result = Begin(KeyPurpose::ENCRYPT, params);
795 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100796 result == ErrorCode::INVALID_KEY_BLOB)
797 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000798 } else {
799 // The KeyMint implementation detected that the generated key
800 // is unusable.
801 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
802 }
803 }
804 }
805 }
806}
807
808/*
809 * NewKeyGenerationTest.AesGcmMissingMinMac
810 *
811 * Verifies that specifying an invalid key size for AES key generation returns
812 * UNSUPPORTED_KEY_SIZE.
813 */
814TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
815 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
816 BlockMode block_mode = BlockMode::GCM;
817 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
818 SCOPED_TRACE(testing::Message()
819 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
820 vector<uint8_t> key_blob;
821 vector<KeyCharacteristics> key_characteristics;
822 // No MIN_MAC_LENGTH provided.
823 auto builder = AuthorizationSetBuilder()
824 .AesEncryptionKey(key_size)
825 .BlockMode(block_mode)
826 .Padding(padding_mode)
827 .SetDefaultValidity();
828 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
829 GenerateKey(builder, &key_blob, &key_characteristics));
830 }
831 }
832}
833
834/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100835 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
836 *
837 * Verifies that specifying an invalid min MAC size for AES key generation returns
838 * UNSUPPORTED_MIN_MAC_LENGTH.
839 */
840TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
841 for (size_t min_mac_len : {88, 136}) {
842 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
843 BlockMode block_mode = BlockMode::GCM;
844 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
845 SCOPED_TRACE(testing::Message()
846 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
847 vector<uint8_t> key_blob;
848 vector<KeyCharacteristics> key_characteristics;
849 auto builder = AuthorizationSetBuilder()
850 .AesEncryptionKey(key_size)
851 .BlockMode(block_mode)
852 .Padding(padding_mode)
853 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
854 .SetDefaultValidity();
855 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
856 GenerateKey(builder, &key_blob, &key_characteristics));
857 }
858 }
859 }
860}
861
862/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000863 * NewKeyGenerationTest.TripleDes
864 *
865 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
866 * have correct characteristics.
867 */
868TEST_P(NewKeyGenerationTest, TripleDes) {
869 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
870 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
871 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
872 SCOPED_TRACE(testing::Message()
873 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
874 vector<uint8_t> key_blob;
875 vector<KeyCharacteristics> key_characteristics;
876 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
877 .TripleDesEncryptionKey(key_size)
878 .BlockMode(block_mode)
879 .Padding(padding_mode)
880 .Authorization(TAG_NO_AUTH_REQUIRED)
881 .SetDefaultValidity(),
882 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100883 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000884
885 EXPECT_GT(key_blob.size(), 0U);
886 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100887 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000888
889 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
890
891 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
892 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
893 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000894 }
895 }
896 }
897}
898
899/*
900 * NewKeyGenerationTest.TripleDesWithAttestation
901 *
902 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
903 * have correct characteristics.
904 *
905 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
906 * put in a certificate) but which isn't an error.
907 */
908TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
909 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
910 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
911 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
912 SCOPED_TRACE(testing::Message()
913 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
914
915 auto challenge = "hello";
916 auto app_id = "foo";
917
918 vector<uint8_t> key_blob;
919 vector<KeyCharacteristics> key_characteristics;
920 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
921 .TripleDesEncryptionKey(key_size)
922 .BlockMode(block_mode)
923 .Padding(padding_mode)
924 .Authorization(TAG_NO_AUTH_REQUIRED)
925 .AttestationChallenge(challenge)
926 .AttestationApplicationId(app_id)
927 .SetDefaultValidity(),
928 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100929 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000930
931 EXPECT_GT(key_blob.size(), 0U);
932 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100933 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000934
935 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
936
937 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
938 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
939 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000940 }
941 }
942 }
943}
944
945/*
946 * NewKeyGenerationTest.TripleDesInvalidSize
947 *
948 * Verifies that specifying an invalid key size for 3-DES key generation returns
949 * UNSUPPORTED_KEY_SIZE.
950 */
951TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
952 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
953 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
954 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
955 SCOPED_TRACE(testing::Message()
956 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
957 vector<uint8_t> key_blob;
958 vector<KeyCharacteristics> key_characteristics;
959 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
960 GenerateKey(AuthorizationSetBuilder()
961 .TripleDesEncryptionKey(key_size)
962 .BlockMode(block_mode)
963 .Padding(padding_mode)
964 .Authorization(TAG_NO_AUTH_REQUIRED)
965 .SetDefaultValidity(),
966 &key_blob, &key_characteristics));
967 }
968 }
969 }
970
971 // Omitting the key size fails.
972 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
973 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
974 SCOPED_TRACE(testing::Message()
975 << "3DES-default-" << block_mode << "-" << padding_mode);
976 vector<uint8_t> key_blob;
977 vector<KeyCharacteristics> key_characteristics;
978 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
979 GenerateKey(AuthorizationSetBuilder()
980 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
981 .BlockMode(block_mode)
982 .Padding(padding_mode)
983 .Authorization(TAG_NO_AUTH_REQUIRED)
984 .SetDefaultValidity(),
985 &key_blob, &key_characteristics));
986 }
987 }
988}
989
990/*
Selene Huang31ab4042020-04-29 04:22:39 -0700991 * NewKeyGenerationTest.Rsa
992 *
993 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
994 * have correct characteristics.
995 */
996TEST_P(NewKeyGenerationTest, Rsa) {
997 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100998 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -0700999 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001000 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1002 .RsaSigningKey(key_size, 65537)
1003 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001004 .Padding(PaddingMode::NONE)
1005 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001006 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001007 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07001008
1009 ASSERT_GT(key_blob.size(), 0U);
1010 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001011 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001012
Shawn Willden7f424372021-01-10 18:06:50 -07001013 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001014
1015 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1016 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1017 << "Key size " << key_size << "missing";
1018 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
Selene Huang31ab4042020-04-29 04:22:39 -07001019 }
1020}
1021
1022/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001023 * NewKeyGenerationTest.RsaWithMissingValidity
1024 *
1025 * Verifies that keymint returns an error while generating asymmetric key
1026 * without providing NOT_BEFORE and NOT_AFTER parameters.
1027 */
1028TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
Seth Moore7dc1fda2022-12-12 16:56:20 -08001029 if (AidlVersion() < 3) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001030 /*
1031 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1032 * specified for asymmetric key generation. However, this was not
1033 * checked at the time so we can only be strict about checking this for
Seth Mooreec10c482024-01-23 20:37:24 +00001034 * implementations of KeyMint version 3 and above.
Tommy Chiu7d22f602022-11-14 21:03:34 +08001035 */
Seth Mooreec10c482024-01-23 20:37:24 +00001036 GTEST_SKIP() << "Validity strict since KeyMint v3";
Tommy Chiu7d22f602022-11-14 21:03:34 +08001037 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001038 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1039 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1040 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1041
1042 vector<uint8_t> key_blob;
1043 vector<KeyCharacteristics> key_characteristics;
1044 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1045 GenerateKey(AuthorizationSetBuilder()
1046 .RsaSigningKey(2048, 65537)
1047 .Digest(Digest::NONE)
1048 .Padding(PaddingMode::NONE)
1049 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1050 kUndefinedExpirationDateTime),
1051 &key_blob, &key_characteristics));
1052
1053 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1054 GenerateKey(AuthorizationSetBuilder()
1055 .RsaSigningKey(2048, 65537)
1056 .Digest(Digest::NONE)
1057 .Padding(PaddingMode::NONE)
1058 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1059 &key_blob, &key_characteristics));
1060}
1061
1062/*
David Drysdalead785f52023-03-27 19:53:01 +01001063 * NewKeyGenerationTest.RsaWithSpecifiedValidity
1064 *
1065 * Verifies that KeyMint respects specified NOT_BEFORE and NOT_AFTER certificate dates.
1066 */
1067TEST_P(NewKeyGenerationTest, RsaWithSpecifiedValidity) {
1068 vector<uint8_t> key_blob;
1069 vector<KeyCharacteristics> key_characteristics;
Subrahmanyamane1560212023-05-09 04:40:33 +00001070 vector<uint64_t> test_vector_not_before_millis = {
1071 458046000000, /* 1984-07-07T11:00:00Z */
1072 1183806000000, /* 2007-07-07T11:00:00Z */
1073 1924991999000, /* 2030-12-31T23:59:59Z */
1074 3723753599000, /* 2087-12-31T23:59:59Z */
1075 26223868799000, /* 2800-12-31T23:59:59Z */
1076 45157996799000, /* 3400-12-31T23:59:59Z */
1077 60719587199000, /* 3894-02-15T23:59:59Z */
1078 95302051199000, /* 4989-12-31T23:59:59Z */
1079 86182012799000, /* 4700-12-31T23:59:59Z */
1080 111427574399000, /* 5500-12-31T23:59:59Z */
1081 136988668799000, /* 6310-12-31T23:59:59Z */
1082 139828895999000, /* 6400-12-31T23:59:59Z */
1083 169839503999000, /* 7351-12-31T23:59:59Z */
1084 171385804799000, /* 7400-12-31T23:59:59Z */
1085 190320019199000, /* 8000-12-31T23:59:59Z */
1086 193475692799000, /* 8100-12-31T23:59:59Z */
1087 242515209599000, /* 9654-12-31T23:59:59Z */
1088 250219065599000, /* 9899-02-15T23:59:59Z */
1089 };
1090 for (auto notBefore : test_vector_not_before_millis) {
1091 uint64_t notAfter = notBefore + 378691200000 /* 12 years milliseconds*/;
Subrahmanya Manikanta Venkateswarlu Bhamidipati Kameswara Srib66a37a2024-02-26 19:23:44 +00001092 SCOPED_TRACE(testing::Message() << "notBefore: " << notBefore << " notAfter: " << notAfter);
Subrahmanyamane1560212023-05-09 04:40:33 +00001093 ASSERT_EQ(ErrorCode::OK,
1094 GenerateKey(AuthorizationSetBuilder()
1095 .RsaSigningKey(2048, 65537)
1096 .Digest(Digest::NONE)
1097 .Padding(PaddingMode::NONE)
1098 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, notBefore)
1099 .Authorization(TAG_CERTIFICATE_NOT_AFTER, notAfter),
1100 &key_blob, &key_characteristics));
1101 ASSERT_GT(cert_chain_.size(), 0);
David Drysdalead785f52023-03-27 19:53:01 +01001102
Subrahmanyamane1560212023-05-09 04:40:33 +00001103 X509_Ptr cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1104 ASSERT_TRUE(!!cert.get());
David Drysdalead785f52023-03-27 19:53:01 +01001105
Subrahmanyamane1560212023-05-09 04:40:33 +00001106 const ASN1_TIME* not_before = X509_get0_notBefore(cert.get());
1107 ASSERT_NE(not_before, nullptr);
Subrahmanya Manikanta Venkateswarlu Bhamidipati Kameswara Srib66a37a2024-02-26 19:23:44 +00001108 int64_t not_before_time;
1109 ASSERT_EQ(ASN1_TIME_to_posix(not_before, &not_before_time), 1);
Subrahmanyamane1560212023-05-09 04:40:33 +00001110 EXPECT_EQ(not_before_time, (notBefore / 1000));
David Drysdalead785f52023-03-27 19:53:01 +01001111
Subrahmanyamane1560212023-05-09 04:40:33 +00001112 const ASN1_TIME* not_after = X509_get0_notAfter(cert.get());
1113 ASSERT_NE(not_after, nullptr);
Subrahmanya Manikanta Venkateswarlu Bhamidipati Kameswara Srib66a37a2024-02-26 19:23:44 +00001114 int64_t not_after_time;
1115 ASSERT_EQ(ASN1_TIME_to_posix(not_after, &not_after_time), 1);
Subrahmanyamane1560212023-05-09 04:40:33 +00001116 EXPECT_EQ(not_after_time, (notAfter / 1000));
1117 }
David Drysdalead785f52023-03-27 19:53:01 +01001118}
1119
1120/*
Qi Wud22ec842020-11-26 13:27:53 +08001121 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001122 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001123 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1124 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001125 */
1126TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001127 auto challenge = "hello";
1128 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001129
Selene Huang6e46f142021-04-20 19:20:11 -07001130 auto subject = "cert subj 2";
1131 vector<uint8_t> subject_der(make_name_from_str(subject));
1132
1133 uint64_t serial_int = 66;
1134 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1135
Selene Huang4f64c222021-04-13 19:54:36 -07001136 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001137 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001138 vector<uint8_t> key_blob;
1139 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001140 auto builder = AuthorizationSetBuilder()
1141 .RsaSigningKey(key_size, 65537)
1142 .Digest(Digest::NONE)
1143 .Padding(PaddingMode::NONE)
1144 .AttestationChallenge(challenge)
1145 .AttestationApplicationId(app_id)
1146 .Authorization(TAG_NO_AUTH_REQUIRED)
1147 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1148 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1149 .SetDefaultValidity();
1150
1151 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001152 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001153 KeyBlobDeleter deleter(keymint_, key_blob);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001154 ASSERT_GT(key_blob.size(), 0U);
1155 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001156 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001157
1158 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1159
1160 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1161 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1162 << "Key size " << key_size << "missing";
1163 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1164
David Drysdalea8a888e2022-06-08 12:43:56 +01001165 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001166 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001167 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001168
1169 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1170 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001171 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001172 sw_enforced, hw_enforced, SecLevel(),
1173 cert_chain_[0].encodedCertificate));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001174 }
1175}
1176
1177/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001178 * NewKeyGenerationTest.RsaWithRkpAttestation
David Drysdale4dc01072021-04-01 12:17:35 +01001179 *
Seth Moore7dc1fda2022-12-12 16:56:20 -08001180 * Verifies that keymint can generate all required RSA key sizes using an attestation key
David Drysdale4dc01072021-04-01 12:17:35 +01001181 * that has been generated using an associate IRemotelyProvisionedComponent.
1182 */
Seth Moore7dc1fda2022-12-12 16:56:20 -08001183TEST_P(NewKeyGenerationTest, RsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001184 if (!IsRkpSupportRequired()) {
1185 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001186 }
1187
Seth Moore5a0320f2023-03-24 12:29:08 -07001188 // Check for an IRemotelyProvisionedComponent instance associated with the
1189 // KeyMint instance.
1190 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1191 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1192 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1193 }
1194 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1195 << GetParam();
David Drysdale4dc01072021-04-01 12:17:35 +01001196
1197 // Generate a P-256 keypair to use as an attestation key.
1198 MacedPublicKey macedPubKey;
1199 std::vector<uint8_t> privateKeyBlob;
1200 auto status =
1201 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1202 ASSERT_TRUE(status.isOk());
1203 vector<uint8_t> coseKeyData;
1204 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1205
1206 AttestationKey attestation_key;
1207 attestation_key.keyBlob = std::move(privateKeyBlob);
1208 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1209
1210 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001211 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdale4dc01072021-04-01 12:17:35 +01001212 auto challenge = "hello";
1213 auto app_id = "foo";
1214
1215 vector<uint8_t> key_blob;
1216 vector<KeyCharacteristics> key_characteristics;
1217 ASSERT_EQ(ErrorCode::OK,
1218 GenerateKey(AuthorizationSetBuilder()
1219 .RsaSigningKey(key_size, 65537)
1220 .Digest(Digest::NONE)
1221 .Padding(PaddingMode::NONE)
1222 .AttestationChallenge(challenge)
1223 .AttestationApplicationId(app_id)
1224 .Authorization(TAG_NO_AUTH_REQUIRED)
1225 .SetDefaultValidity(),
1226 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
David Drysdale1b9febc2023-06-07 13:43:24 +01001227 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale4dc01072021-04-01 12:17:35 +01001228
1229 ASSERT_GT(key_blob.size(), 0U);
1230 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001231 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001232
1233 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1234
1235 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1236 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1237 << "Key size " << key_size << "missing";
1238 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1239
1240 // Attestation by itself is not valid (last entry is not self-signed).
1241 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1242
1243 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001244 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001245 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1246 ASSERT_TRUE(key_cert.get());
1247 EVP_PKEY_Ptr signing_pubkey;
1248 p256_pub_key(coseKeyData, &signing_pubkey);
1249 ASSERT_TRUE(signing_pubkey.get());
1250
1251 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1252 << "Verification of attested certificate failed "
1253 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
David Drysdale4dc01072021-04-01 12:17:35 +01001254 }
1255}
1256
1257/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001258 * NewKeyGenerationTest.EcdsaWithRkpAttestation
1259 *
1260 * Verifies that keymint can generate all required ECDSA key sizes using an attestation key
1261 * that has been generated using an associate IRemotelyProvisionedComponent.
1262 */
1263TEST_P(NewKeyGenerationTest, EcdsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001264 if (!IsRkpSupportRequired()) {
1265 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001266 }
1267
Seth Moore5a0320f2023-03-24 12:29:08 -07001268 // Check for an IRemotelyProvisionedComponent instance associated with the
1269 // KeyMint instance.
1270 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1271 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1272 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1273 }
1274 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1275 << GetParam();
Seth Moore7dc1fda2022-12-12 16:56:20 -08001276
1277 // Generate a P-256 keypair to use as an attestation key.
1278 MacedPublicKey macedPubKey;
1279 std::vector<uint8_t> privateKeyBlob;
1280 auto status =
1281 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1282 ASSERT_TRUE(status.isOk());
1283 vector<uint8_t> coseKeyData;
1284 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1285
1286 AttestationKey attestation_key;
1287 attestation_key.keyBlob = std::move(privateKeyBlob);
1288 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1289
1290 for (auto curve : ValidCurves()) {
1291 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
1292 auto challenge = "hello";
1293 auto app_id = "foo";
1294
1295 vector<uint8_t> key_blob;
1296 vector<KeyCharacteristics> key_characteristics;
1297 ASSERT_EQ(ErrorCode::OK,
1298 GenerateKey(AuthorizationSetBuilder()
1299 .EcdsaSigningKey(curve)
1300 .Digest(Digest::NONE)
1301 .AttestationChallenge(challenge)
1302 .AttestationApplicationId(app_id)
1303 .Authorization(TAG_NO_AUTH_REQUIRED)
1304 .SetDefaultValidity(),
1305 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
David Drysdale1b9febc2023-06-07 13:43:24 +01001306 KeyBlobDeleter deleter(keymint_, key_blob);
Seth Moore7dc1fda2022-12-12 16:56:20 -08001307
1308 ASSERT_GT(key_blob.size(), 0U);
1309 CheckBaseParams(key_characteristics);
1310 CheckCharacteristics(key_blob, key_characteristics);
1311
1312 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1313
1314 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1315 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1316
1317 // Attestation by itself is not valid (last entry is not self-signed).
1318 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1319
1320 // The signature over the attested key should correspond to the P256 public key.
1321 ASSERT_GT(cert_chain_.size(), 0);
1322 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1323 ASSERT_TRUE(key_cert.get());
1324 EVP_PKEY_Ptr signing_pubkey;
1325 p256_pub_key(coseKeyData, &signing_pubkey);
1326 ASSERT_TRUE(signing_pubkey.get());
1327
1328 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1329 << "Verification of attested certificate failed "
1330 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Seth Moore7dc1fda2022-12-12 16:56:20 -08001331 }
1332}
1333
1334/*
Selene Huang4f64c222021-04-13 19:54:36 -07001335 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1336 *
1337 * Verifies that keymint attestation for RSA encryption keys with challenge and
1338 * app id is also successful.
1339 */
1340TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1341 auto key_size = 2048;
1342 auto challenge = "hello";
1343 auto app_id = "foo";
1344
Selene Huang6e46f142021-04-20 19:20:11 -07001345 auto subject = "subj 2";
1346 vector<uint8_t> subject_der(make_name_from_str(subject));
1347
1348 uint64_t serial_int = 111166;
1349 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1350
Selene Huang4f64c222021-04-13 19:54:36 -07001351 vector<uint8_t> key_blob;
1352 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001353 auto builder = AuthorizationSetBuilder()
1354 .RsaEncryptionKey(key_size, 65537)
1355 .Padding(PaddingMode::NONE)
1356 .AttestationChallenge(challenge)
1357 .AttestationApplicationId(app_id)
1358 .Authorization(TAG_NO_AUTH_REQUIRED)
1359 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1360 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1361 .SetDefaultValidity();
1362
1363 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001364 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001365 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001366
1367 ASSERT_GT(key_blob.size(), 0U);
1368 AuthorizationSet auths;
1369 for (auto& entry : key_characteristics) {
1370 auths.push_back(AuthorizationSet(entry.authorizations));
1371 }
1372
1373 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1374 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1375
1376 // Verify that App data and ROT are NOT included.
1377 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1378 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1379
1380 // Check that some unexpected tags/values are NOT present.
1381 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1382 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1383
1384 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1385
1386 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1387 ASSERT_TRUE(os_ver);
1388 EXPECT_EQ(*os_ver, os_version());
1389
1390 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1391
1392 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1393 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1394 << "Key size " << key_size << "missing";
1395 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1396
David Drysdalea8a888e2022-06-08 12:43:56 +01001397 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001398 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001399 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001400
1401 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1402 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001403 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001404 sw_enforced, hw_enforced, SecLevel(),
1405 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07001406}
1407
1408/*
1409 * NewKeyGenerationTest.RsaWithSelfSign
1410 *
1411 * Verifies that attesting to RSA key generation is successful, and returns
1412 * self signed certificate if no challenge is provided. And signing etc
1413 * works as expected.
1414 */
1415TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001416 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1417 vector<uint8_t> subject_der(make_name_from_str(subject));
1418
1419 uint64_t serial_int = 0;
1420 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1421
Selene Huang4f64c222021-04-13 19:54:36 -07001422 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001423 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang4f64c222021-04-13 19:54:36 -07001424 vector<uint8_t> key_blob;
1425 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001426 ASSERT_EQ(ErrorCode::OK,
1427 GenerateKey(AuthorizationSetBuilder()
1428 .RsaSigningKey(key_size, 65537)
1429 .Digest(Digest::NONE)
1430 .Padding(PaddingMode::NONE)
1431 .Authorization(TAG_NO_AUTH_REQUIRED)
1432 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1433 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1434 .SetDefaultValidity(),
1435 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001436 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001437
1438 ASSERT_GT(key_blob.size(), 0U);
1439 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001440 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001441
1442 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1443
1444 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1445 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1446 << "Key size " << key_size << "missing";
1447 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1448
David Drysdalea8a888e2022-06-08 12:43:56 +01001449 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001450 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001451 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001452 }
1453}
1454
1455/*
1456 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1457 *
1458 * Verifies that attesting to RSA checks for missing app ID.
1459 */
1460TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1461 auto challenge = "hello";
1462 vector<uint8_t> key_blob;
1463 vector<KeyCharacteristics> key_characteristics;
1464
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001465 auto builder = AuthorizationSetBuilder()
1466 .RsaSigningKey(2048, 65537)
1467 .Digest(Digest::NONE)
1468 .Padding(PaddingMode::NONE)
1469 .AttestationChallenge(challenge)
1470 .Authorization(TAG_NO_AUTH_REQUIRED)
1471 .SetDefaultValidity();
1472
1473 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001474 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001475}
1476
1477/*
1478 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1479 *
1480 * Verifies that attesting to RSA ignores app id if challenge is missing.
1481 */
1482TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1483 auto key_size = 2048;
1484 auto app_id = "foo";
1485
Selene Huang6e46f142021-04-20 19:20:11 -07001486 auto subject = "cert subj 2";
1487 vector<uint8_t> subject_der(make_name_from_str(subject));
1488
1489 uint64_t serial_int = 1;
1490 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1491
Selene Huang4f64c222021-04-13 19:54:36 -07001492 vector<uint8_t> key_blob;
1493 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001494 ASSERT_EQ(ErrorCode::OK,
1495 GenerateKey(AuthorizationSetBuilder()
1496 .RsaSigningKey(key_size, 65537)
1497 .Digest(Digest::NONE)
1498 .Padding(PaddingMode::NONE)
1499 .AttestationApplicationId(app_id)
1500 .Authorization(TAG_NO_AUTH_REQUIRED)
1501 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1502 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1503 .SetDefaultValidity(),
1504 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001505 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001506
1507 ASSERT_GT(key_blob.size(), 0U);
1508 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001509 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001510
1511 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1512
1513 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1514 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1515 << "Key size " << key_size << "missing";
1516 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1517
David Drysdalea8a888e2022-06-08 12:43:56 +01001518 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001519 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001520 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1521 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang4f64c222021-04-13 19:54:36 -07001522}
1523
1524/*
Qi Wud22ec842020-11-26 13:27:53 +08001525 * NewKeyGenerationTest.LimitedUsageRsa
1526 *
1527 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1528 * resulting keys have correct characteristics.
1529 */
1530TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1531 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001532 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wud22ec842020-11-26 13:27:53 +08001533 vector<uint8_t> key_blob;
1534 vector<KeyCharacteristics> key_characteristics;
1535 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1536 .RsaSigningKey(key_size, 65537)
1537 .Digest(Digest::NONE)
1538 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001539 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1540 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001541 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001542 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08001543
1544 ASSERT_GT(key_blob.size(), 0U);
1545 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001546 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001547
1548 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1549
1550 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1551 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1552 << "Key size " << key_size << "missing";
1553 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1554
1555 // Check the usage count limit tag appears in the authorizations.
1556 AuthorizationSet auths;
1557 for (auto& entry : key_characteristics) {
1558 auths.push_back(AuthorizationSet(entry.authorizations));
1559 }
1560 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1561 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08001562 }
1563}
1564
1565/*
Qi Wubeefae42021-01-28 23:16:37 +08001566 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1567 *
1568 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1569 * resulting keys have correct characteristics and attestation.
1570 */
1571TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001572 auto challenge = "hello";
1573 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001574
Selene Huang6e46f142021-04-20 19:20:11 -07001575 auto subject = "cert subj 2";
1576 vector<uint8_t> subject_der(make_name_from_str(subject));
1577
1578 uint64_t serial_int = 66;
1579 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1580
Selene Huang4f64c222021-04-13 19:54:36 -07001581 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001582 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wubeefae42021-01-28 23:16:37 +08001583 vector<uint8_t> key_blob;
1584 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001585 auto builder = AuthorizationSetBuilder()
1586 .RsaSigningKey(key_size, 65537)
1587 .Digest(Digest::NONE)
1588 .Padding(PaddingMode::NONE)
1589 .AttestationChallenge(challenge)
1590 .AttestationApplicationId(app_id)
1591 .Authorization(TAG_NO_AUTH_REQUIRED)
1592 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1593 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1594 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1595 .SetDefaultValidity();
1596
1597 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001598 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001599 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wubeefae42021-01-28 23:16:37 +08001600
1601 ASSERT_GT(key_blob.size(), 0U);
1602 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001603 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001604
1605 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1606
1607 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1608 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1609 << "Key size " << key_size << "missing";
1610 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1611
1612 // Check the usage count limit tag appears in the authorizations.
1613 AuthorizationSet auths;
1614 for (auto& entry : key_characteristics) {
1615 auths.push_back(AuthorizationSet(entry.authorizations));
1616 }
1617 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1618 << "key usage count limit " << 1U << " missing";
1619
1620 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001621 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001622 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001623 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001624
1625 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1626 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001627 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001628 sw_enforced, hw_enforced, SecLevel(),
1629 cert_chain_[0].encodedCertificate));
Qi Wubeefae42021-01-28 23:16:37 +08001630 }
1631}
1632
1633/*
Selene Huang31ab4042020-04-29 04:22:39 -07001634 * NewKeyGenerationTest.NoInvalidRsaSizes
1635 *
1636 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1637 */
1638TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1639 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001640 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07001641 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001642 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001643 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1644 GenerateKey(AuthorizationSetBuilder()
1645 .RsaSigningKey(key_size, 65537)
1646 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001647 .Padding(PaddingMode::NONE)
1648 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001649 &key_blob, &key_characteristics));
1650 }
1651}
1652
1653/*
1654 * NewKeyGenerationTest.RsaNoDefaultSize
1655 *
1656 * Verifies that failing to specify a key size for RSA key generation returns
1657 * UNSUPPORTED_KEY_SIZE.
1658 */
1659TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1660 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1661 GenerateKey(AuthorizationSetBuilder()
1662 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1663 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001664 .SigningKey()
1665 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001666}
1667
1668/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001669 * NewKeyGenerationTest.RsaMissingParams
1670 *
1671 * Verifies that omitting optional tags works.
1672 */
1673TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1674 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001675 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdaled2cc8c22021-04-15 13:29:45 +01001676 ASSERT_EQ(ErrorCode::OK,
1677 GenerateKey(
1678 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1679 CheckedDeleteKey();
1680 }
1681}
1682
1683/*
Selene Huang31ab4042020-04-29 04:22:39 -07001684 * NewKeyGenerationTest.Ecdsa
1685 *
David Drysdale42fe1892021-10-14 14:43:46 +01001686 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001687 * have correct characteristics.
1688 */
1689TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001690 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001691 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07001692 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001693 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001694 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001695 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001696 .Digest(Digest::NONE)
1697 .SetDefaultValidity(),
1698 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001699 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07001700 ASSERT_GT(key_blob.size(), 0U);
1701 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001702 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001703
Shawn Willden7f424372021-01-10 18:06:50 -07001704 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001705
1706 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001707 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001708 }
1709}
1710
1711/*
David Drysdale42fe1892021-10-14 14:43:46 +01001712 * NewKeyGenerationTest.EcdsaCurve25519
1713 *
1714 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1715 * has correct characteristics.
1716 */
1717TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1718 if (!Curve25519Supported()) {
1719 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1720 }
1721
1722 EcCurve curve = EcCurve::CURVE_25519;
1723 vector<uint8_t> key_blob;
1724 vector<KeyCharacteristics> key_characteristics;
1725 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1726 .EcdsaSigningKey(curve)
1727 .Digest(Digest::NONE)
1728 .SetDefaultValidity(),
1729 &key_blob, &key_characteristics);
1730 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01001731 KeyBlobDeleter deleter(keymint_, key_blob);
1732
David Drysdale42fe1892021-10-14 14:43:46 +01001733 ASSERT_GT(key_blob.size(), 0U);
1734
1735 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1736 ASSERT_GT(cert_chain_.size(), 0);
1737
1738 CheckBaseParams(key_characteristics);
1739 CheckCharacteristics(key_blob, key_characteristics);
1740
1741 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1742
1743 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1744 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
David Drysdale42fe1892021-10-14 14:43:46 +01001745}
1746
1747/*
1748 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1749 *
1750 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1751 * SIGN and AGREE_KEY.
1752 */
1753TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1754 if (!Curve25519Supported()) {
1755 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1756 }
1757
1758 EcCurve curve = EcCurve::CURVE_25519;
1759 vector<uint8_t> key_blob;
1760 vector<KeyCharacteristics> key_characteristics;
1761 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1762 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1763 .EcdsaSigningKey(curve)
1764 .Digest(Digest::NONE)
1765 .SetDefaultValidity(),
1766 &key_blob, &key_characteristics);
1767 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1768}
1769
1770/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001771 * NewKeyGenerationTest.EcdsaWithMissingValidity
1772 *
1773 * Verifies that keymint returns an error while generating asymmetric key
1774 * without providing NOT_BEFORE and NOT_AFTER parameters.
1775 */
1776TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001777 if (AidlVersion() < 2) {
1778 /*
1779 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1780 * specified for asymmetric key generation. However, this was not
1781 * checked at the time so we can only be strict about checking this for
1782 * implementations of KeyMint version 2 and above.
1783 */
1784 GTEST_SKIP() << "Validity strict since KeyMint v2";
1785 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001786 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1787 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1788 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1789
1790 vector<uint8_t> key_blob;
1791 vector<KeyCharacteristics> key_characteristics;
1792 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1793 GenerateKey(AuthorizationSetBuilder()
1794 .EcdsaSigningKey(EcCurve::P_256)
1795 .Digest(Digest::NONE)
1796 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1797 kUndefinedExpirationDateTime),
1798 &key_blob, &key_characteristics));
1799
1800 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1801 GenerateKey(AuthorizationSetBuilder()
1802 .EcdsaSigningKey(EcCurve::P_256)
1803 .Digest(Digest::NONE)
1804 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1805 &key_blob, &key_characteristics));
1806}
1807
1808/*
Selene Huang4f64c222021-04-13 19:54:36 -07001809 * NewKeyGenerationTest.EcdsaAttestation
1810 *
1811 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1812 * an attestation will be generated.
1813 */
1814TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1815 auto challenge = "hello";
1816 auto app_id = "foo";
1817
Selene Huang6e46f142021-04-20 19:20:11 -07001818 auto subject = "cert subj 2";
1819 vector<uint8_t> subject_der(make_name_from_str(subject));
1820
1821 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1822 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1823
David Drysdaledf09e542021-06-08 15:46:11 +01001824 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001825 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07001826 vector<uint8_t> key_blob;
1827 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001828 auto builder = AuthorizationSetBuilder()
1829 .Authorization(TAG_NO_AUTH_REQUIRED)
1830 .EcdsaSigningKey(curve)
1831 .Digest(Digest::NONE)
1832 .AttestationChallenge(challenge)
1833 .AttestationApplicationId(app_id)
1834 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1835 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1836 .SetDefaultValidity();
1837
1838 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001839 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001840 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001841 ASSERT_GT(key_blob.size(), 0U);
1842 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001843 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001844
1845 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1846
1847 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001848 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001849
1850 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1851 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001852 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001853
1854 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1855 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001856 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001857 sw_enforced, hw_enforced, SecLevel(),
1858 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07001859 }
1860}
1861
1862/*
David Drysdale42fe1892021-10-14 14:43:46 +01001863 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1864 *
1865 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1866 * an attestation will be generated.
1867 */
1868TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1869 if (!Curve25519Supported()) {
1870 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1871 }
1872
1873 EcCurve curve = EcCurve::CURVE_25519;
1874 auto challenge = "hello";
1875 auto app_id = "foo";
1876
1877 auto subject = "cert subj 2";
1878 vector<uint8_t> subject_der(make_name_from_str(subject));
1879
1880 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1881 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1882
1883 vector<uint8_t> key_blob;
1884 vector<KeyCharacteristics> key_characteristics;
1885 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1886 .Authorization(TAG_NO_AUTH_REQUIRED)
1887 .EcdsaSigningKey(curve)
1888 .Digest(Digest::NONE)
1889 .AttestationChallenge(challenge)
1890 .AttestationApplicationId(app_id)
1891 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1892 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1893 .SetDefaultValidity(),
1894 &key_blob, &key_characteristics);
1895 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001896 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale42fe1892021-10-14 14:43:46 +01001897 ASSERT_GT(key_blob.size(), 0U);
1898 CheckBaseParams(key_characteristics);
1899 CheckCharacteristics(key_blob, key_characteristics);
1900
1901 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1902
1903 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1904 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1905
1906 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1907 ASSERT_GT(cert_chain_.size(), 0);
1908 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1909
1910 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1911 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1912 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1913 sw_enforced, hw_enforced, SecLevel(),
1914 cert_chain_[0].encodedCertificate));
David Drysdale42fe1892021-10-14 14:43:46 +01001915}
1916
1917/*
David Drysdale37af4b32021-05-14 16:46:59 +01001918 * NewKeyGenerationTest.EcdsaAttestationTags
1919 *
1920 * Verifies that creation of an attested ECDSA key includes various tags in the
1921 * attestation extension.
1922 */
1923TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1924 auto challenge = "hello";
1925 auto app_id = "foo";
1926 auto subject = "cert subj 2";
1927 vector<uint8_t> subject_der(make_name_from_str(subject));
1928 uint64_t serial_int = 0x1010;
1929 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1930 const AuthorizationSetBuilder base_builder =
1931 AuthorizationSetBuilder()
1932 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001933 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001934 .Digest(Digest::NONE)
1935 .AttestationChallenge(challenge)
1936 .AttestationApplicationId(app_id)
1937 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1938 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1939 .SetDefaultValidity();
1940
1941 // Various tags that map to fields in the attestation extension ASN.1 schema.
1942 auto extra_tags = AuthorizationSetBuilder()
1943 .Authorization(TAG_ROLLBACK_RESISTANCE)
1944 .Authorization(TAG_EARLY_BOOT_ONLY)
1945 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1946 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1947 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1948 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1949 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1950 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1951 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1952 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1953 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1954 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001955
David Drysdale37af4b32021-05-14 16:46:59 +01001956 for (const KeyParameter& tag : extra_tags) {
1957 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1958 vector<uint8_t> key_blob;
1959 vector<KeyCharacteristics> key_characteristics;
1960 AuthorizationSetBuilder builder = base_builder;
1961 builder.push_back(tag);
1962 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1963 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1964 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1965 continue;
1966 }
Seth Mooreb393b082021-07-12 14:18:28 -07001967 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1968 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001969 continue;
1970 }
1971 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01001972 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale37af4b32021-05-14 16:46:59 +01001973 ASSERT_GT(key_blob.size(), 0U);
1974
1975 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1976 ASSERT_GT(cert_chain_.size(), 0);
1977 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1978
1979 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1980 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001981 // Some tags are optional, so don't require them to be in the enforcements.
1982 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001983 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1984 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1985 }
1986
1987 // Verifying the attestation record will check for the specific tag because
1988 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001989 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1990 hw_enforced, SecLevel(),
1991 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001992 }
1993
David Drysdalec53b7d92021-10-11 12:35:58 +01001994 // Collection of invalid attestation ID tags.
1995 auto invalid_tags =
1996 AuthorizationSetBuilder()
1997 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1998 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1999 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
2000 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
2001 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
2002 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
2003 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
2004 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01002005 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01002006 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01002007 vector<uint8_t> key_blob;
2008 vector<KeyCharacteristics> key_characteristics;
2009 AuthorizationSetBuilder builder =
2010 AuthorizationSetBuilder()
2011 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002012 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01002013 .Digest(Digest::NONE)
2014 .AttestationChallenge(challenge)
2015 .AttestationApplicationId(app_id)
2016 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2017 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2018 .SetDefaultValidity();
2019 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002020
2021 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
David Drysdalec68dc932023-07-06 10:05:12 +01002022 device_id_attestation_check_acceptable_error(tag.tag, error);
David Drysdale37af4b32021-05-14 16:46:59 +01002023 }
2024}
2025
2026/*
David Drysdalec53b7d92021-10-11 12:35:58 +01002027 * NewKeyGenerationTest.EcdsaAttestationIdTags
2028 *
2029 * Verifies that creation of an attested ECDSA key includes various ID tags in the
David Drysdaleef1123b2024-05-28 15:23:08 +01002030 * attestation extension one by one.
David Drysdalec53b7d92021-10-11 12:35:58 +01002031 */
2032TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
2033 auto challenge = "hello";
2034 auto app_id = "foo";
2035 auto subject = "cert subj 2";
2036 vector<uint8_t> subject_der(make_name_from_str(subject));
2037 uint64_t serial_int = 0x1010;
2038 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2039 const AuthorizationSetBuilder base_builder =
2040 AuthorizationSetBuilder()
2041 .Authorization(TAG_NO_AUTH_REQUIRED)
2042 .EcdsaSigningKey(EcCurve::P_256)
2043 .Digest(Digest::NONE)
2044 .AttestationChallenge(challenge)
2045 .AttestationApplicationId(app_id)
2046 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2047 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2048 .SetDefaultValidity();
2049
2050 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2051 auto extra_tags = AuthorizationSetBuilder();
Prashant Patil24f75792023-09-07 15:25:14 +00002052 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_BRAND, "brand");
2053 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "device");
2054 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "name");
2055 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer");
2056 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MODEL, "model");
Tri Vo799e4352022-11-07 17:23:50 -08002057 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
David Drysdaleef1123b2024-05-28 15:23:08 +01002058 string imei = get_imei(0);
2059 if (!imei.empty()) {
2060 extra_tags.Authorization(TAG_ATTESTATION_ID_IMEI, imei.data(), imei.size());
2061 }
2062 string second_imei = get_imei(1);
David Drysdalee9dcae52024-06-11 15:36:20 +01002063 if (!second_imei.empty() && isSecondImeiIdAttestationRequired()) {
David Drysdaleef1123b2024-05-28 15:23:08 +01002064 extra_tags.Authorization(TAG_ATTESTATION_ID_SECOND_IMEI, second_imei.data(),
2065 second_imei.size());
2066 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002067
2068 for (const KeyParameter& tag : extra_tags) {
2069 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2070 vector<uint8_t> key_blob;
2071 vector<KeyCharacteristics> key_characteristics;
2072 AuthorizationSetBuilder builder = base_builder;
2073 builder.push_back(tag);
2074 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
Prashant Patil88ad1892022-03-15 16:31:02 +00002075 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2076 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002077 continue;
2078 }
2079 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002080 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdalec53b7d92021-10-11 12:35:58 +01002081 ASSERT_GT(key_blob.size(), 0U);
2082
2083 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2084 ASSERT_GT(cert_chain_.size(), 0);
2085 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2086
2087 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2088 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2089
2090 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2091 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2092 // attestation extension should contain them, so make sure the extra tag is added.
2093 hw_enforced.push_back(tag);
2094
2095 // Verifying the attestation record will check for the specific tag because
2096 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002097 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2098 hw_enforced, SecLevel(),
2099 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002100 }
2101}
2102
2103/*
David Drysdaleef1123b2024-05-28 15:23:08 +01002104 * NewKeyGenerationTest.EcdsaAttestationIdAllTags
2105 *
2106 * Verifies that creation of an attested ECDSA key includes various ID tags in the
2107 * attestation extension all together.
2108 */
2109TEST_P(NewKeyGenerationTest, EcdsaAttestationIdAllTags) {
2110 auto challenge = "hello";
2111 auto app_id = "foo";
2112 auto subject = "cert subj 2";
2113 vector<uint8_t> subject_der(make_name_from_str(subject));
2114 uint64_t serial_int = 0x1010;
2115 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2116 AuthorizationSetBuilder builder = AuthorizationSetBuilder()
2117 .Authorization(TAG_NO_AUTH_REQUIRED)
2118 .EcdsaSigningKey(EcCurve::P_256)
2119 .Digest(Digest::NONE)
2120 .AttestationChallenge(challenge)
2121 .AttestationApplicationId(app_id)
2122 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2123 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2124 .SetDefaultValidity();
2125
2126 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2127 auto extra_tags = AuthorizationSetBuilder();
2128 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_BRAND, "brand");
2129 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "device");
2130 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "name");
2131 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer");
2132 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MODEL, "model");
2133 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
2134 string imei = get_imei(0);
2135 if (!imei.empty()) {
2136 extra_tags.Authorization(TAG_ATTESTATION_ID_IMEI, imei.data(), imei.size());
2137 }
2138 string second_imei = get_imei(1);
David Drysdalee9dcae52024-06-11 15:36:20 +01002139 if (!second_imei.empty() && isSecondImeiIdAttestationRequired()) {
David Drysdaleef1123b2024-05-28 15:23:08 +01002140 extra_tags.Authorization(TAG_ATTESTATION_ID_SECOND_IMEI, second_imei.data(),
2141 second_imei.size());
2142 }
2143 for (const KeyParameter& tag : extra_tags) {
2144 builder.push_back(tag);
2145 }
2146
2147 vector<uint8_t> key_blob;
2148 vector<KeyCharacteristics> key_characteristics;
2149 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
2150 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2151 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
2152 return;
2153 }
2154 ASSERT_EQ(result, ErrorCode::OK);
2155 KeyBlobDeleter deleter(keymint_, key_blob);
2156 ASSERT_GT(key_blob.size(), 0U);
2157
2158 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2159 ASSERT_GT(cert_chain_.size(), 0);
2160 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2161
2162 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2163 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2164
2165 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2166 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2167 // attestation extension should contain them, so make sure the extra tags are added.
2168 for (const KeyParameter& tag : extra_tags) {
2169 hw_enforced.push_back(tag);
2170 }
2171
2172 // Verifying the attestation record will check for the specific tag because
2173 // it's included in the authorizations.
2174 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2175 hw_enforced, SecLevel(),
2176 cert_chain_[0].encodedCertificate))
2177 << "failed to verify " << bin2hex(cert_chain_[0].encodedCertificate);
2178}
2179
2180/*
David Drysdale565ccc72021-10-11 12:49:50 +01002181 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2182 *
2183 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2184 */
2185TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2186 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002187 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002188 auto challenge = "hello";
2189 auto subject = "cert subj 2";
2190 vector<uint8_t> subject_der(make_name_from_str(subject));
2191 uint64_t serial_int = 0x1010;
2192 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002193 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002194 AuthorizationSetBuilder()
2195 .Authorization(TAG_NO_AUTH_REQUIRED)
2196 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2197 .EcdsaSigningKey(EcCurve::P_256)
2198 .Digest(Digest::NONE)
2199 .AttestationChallenge(challenge)
2200 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2201 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2202 .AttestationApplicationId(app_id)
2203 .Authorization(TAG_CREATION_DATETIME, datetime)
2204 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002205 if (reset) {
2206 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2207 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002208 auto result = GenerateKey(builder);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002209 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002210 ASSERT_GT(key_blob_.size(), 0U);
2211
2212 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2213 ASSERT_GT(cert_chain_.size(), 0);
2214 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2215
2216 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2217 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2218
2219 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002220 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2221 hw_enforced, SecLevel(),
2222 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002223 EXPECT_GT(unique_id->size(), 0);
2224 CheckedDeleteKey();
2225 };
2226
2227 // Generate unique ID
2228 auto app_id = "foo";
2229 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2230 vector<uint8_t> unique_id;
2231 get_unique_id(app_id, cert_date, &unique_id);
2232
2233 // Generating a new key with the same parameters should give the same unique ID.
2234 vector<uint8_t> unique_id2;
2235 get_unique_id(app_id, cert_date, &unique_id2);
2236 EXPECT_EQ(unique_id, unique_id2);
2237
2238 // Generating a new key with a slightly different date should give the same unique ID.
2239 uint64_t rounded_date = cert_date / 2592000000LLU;
2240 uint64_t min_date = rounded_date * 2592000000LLU;
2241 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2242
2243 vector<uint8_t> unique_id3;
2244 get_unique_id(app_id, min_date, &unique_id3);
2245 EXPECT_EQ(unique_id, unique_id3);
2246
2247 vector<uint8_t> unique_id4;
2248 get_unique_id(app_id, max_date, &unique_id4);
2249 EXPECT_EQ(unique_id, unique_id4);
2250
2251 // A different attestation application ID should yield a different unique ID.
2252 auto app_id2 = "different_foo";
2253 vector<uint8_t> unique_id5;
2254 get_unique_id(app_id2, cert_date, &unique_id5);
2255 EXPECT_NE(unique_id, unique_id5);
2256
2257 // A radically different date should yield a different unique ID.
2258 vector<uint8_t> unique_id6;
2259 get_unique_id(app_id, 1611621648000, &unique_id6);
2260 EXPECT_NE(unique_id, unique_id6);
2261
2262 vector<uint8_t> unique_id7;
2263 get_unique_id(app_id, max_date + 1, &unique_id7);
2264 EXPECT_NE(unique_id, unique_id7);
2265
2266 vector<uint8_t> unique_id8;
2267 get_unique_id(app_id, min_date - 1, &unique_id8);
2268 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002269
2270 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2271 vector<uint8_t> unique_id9;
2272 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2273 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002274}
2275
2276/*
David Drysdale37af4b32021-05-14 16:46:59 +01002277 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2278 *
2279 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2280 */
2281TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2282 auto challenge = "hello";
2283 auto attest_app_id = "foo";
2284 auto subject = "cert subj 2";
2285 vector<uint8_t> subject_der(make_name_from_str(subject));
2286 uint64_t serial_int = 0x1010;
2287 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2288
2289 // Earlier versions of the attestation extension schema included a slot:
2290 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2291 // This should never have been included, and should never be filled in.
2292 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2293 // to confirm that this field never makes it into the attestation extension.
2294 vector<uint8_t> key_blob;
2295 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002296 auto builder = AuthorizationSetBuilder()
2297 .Authorization(TAG_NO_AUTH_REQUIRED)
2298 .EcdsaSigningKey(EcCurve::P_256)
2299 .Digest(Digest::NONE)
2300 .AttestationChallenge(challenge)
2301 .AttestationApplicationId(attest_app_id)
2302 .Authorization(TAG_APPLICATION_ID, "client_id")
2303 .Authorization(TAG_APPLICATION_DATA, "appdata")
2304 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2305 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2306 .SetDefaultValidity();
2307
2308 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
David Drysdale37af4b32021-05-14 16:46:59 +01002309 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002310 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale37af4b32021-05-14 16:46:59 +01002311 ASSERT_GT(key_blob.size(), 0U);
2312
2313 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2314 ASSERT_GT(cert_chain_.size(), 0);
2315 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2316
2317 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2318 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002319 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2320 hw_enforced, SecLevel(),
2321 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002322
2323 // Check that the app id is not in the cert.
2324 string app_id = "clientid";
2325 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2326 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2327 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2328 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2329 cert_chain_[0].encodedCertificate.end());
David Drysdale37af4b32021-05-14 16:46:59 +01002330}
2331
2332/*
Selene Huang4f64c222021-04-13 19:54:36 -07002333 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2334 *
2335 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2336 * the key will generate a self signed attestation.
2337 */
2338TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002339 auto subject = "cert subj 2";
2340 vector<uint8_t> subject_der(make_name_from_str(subject));
2341
2342 uint64_t serial_int = 0x123456FFF1234;
2343 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2344
David Drysdaledf09e542021-06-08 15:46:11 +01002345 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002346 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002347 vector<uint8_t> key_blob;
2348 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002349 ASSERT_EQ(ErrorCode::OK,
2350 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002351 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002352 .Digest(Digest::NONE)
2353 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2354 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2355 .SetDefaultValidity(),
2356 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002357 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002358 ASSERT_GT(key_blob.size(), 0U);
2359 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002360 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002361
2362 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2363
2364 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002365 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002366
2367 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2368 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002369 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002370
2371 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2372 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002373 }
2374}
2375
2376/*
2377 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2378 *
2379 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2380 * app id must also be provided or else it will fail.
2381 */
2382TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2383 auto challenge = "hello";
2384 vector<uint8_t> key_blob;
2385 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002386 auto builder = AuthorizationSetBuilder()
2387 .EcdsaSigningKey(EcCurve::P_256)
2388 .Digest(Digest::NONE)
2389 .AttestationChallenge(challenge)
2390 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002391
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002392 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002393 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002394}
2395
2396/*
2397 * NewKeyGenerationTest.EcdsaIgnoreAppId
2398 *
2399 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2400 * any appid will be ignored, and keymint will generate a self sign certificate.
2401 */
2402TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2403 auto app_id = "foo";
2404
David Drysdaledf09e542021-06-08 15:46:11 +01002405 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002406 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002407 vector<uint8_t> key_blob;
2408 vector<KeyCharacteristics> key_characteristics;
2409 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002410 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002411 .Digest(Digest::NONE)
2412 .AttestationApplicationId(app_id)
2413 .SetDefaultValidity(),
2414 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002415 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002416
2417 ASSERT_GT(key_blob.size(), 0U);
2418 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002419 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002420
2421 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2422
2423 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002424 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002425
2426 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2427 ASSERT_EQ(cert_chain_.size(), 1);
2428
2429 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2430 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002431 }
2432}
2433
2434/*
2435 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2436 *
2437 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2438 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2439 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2440 * to specify how many following bytes will be used to encode the length.
2441 */
2442TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2443 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002444 std::vector<uint32_t> app_id_lengths{143, 258};
2445
2446 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002447 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002448 const string app_id(length, 'a');
2449 vector<uint8_t> key_blob;
2450 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002451 auto builder = AuthorizationSetBuilder()
2452 .Authorization(TAG_NO_AUTH_REQUIRED)
2453 .EcdsaSigningKey(EcCurve::P_256)
2454 .Digest(Digest::NONE)
2455 .AttestationChallenge(challenge)
2456 .AttestationApplicationId(app_id)
2457 .SetDefaultValidity();
2458
2459 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002460 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01002461 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002462 ASSERT_GT(key_blob.size(), 0U);
2463 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002464 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002465
2466 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2467
2468 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002469 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002470
2471 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2472 ASSERT_GT(cert_chain_.size(), 0);
2473
2474 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2475 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002476 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002477 sw_enforced, hw_enforced, SecLevel(),
2478 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07002479 }
2480}
2481
2482/*
Qi Wud22ec842020-11-26 13:27:53 +08002483 * NewKeyGenerationTest.LimitedUsageEcdsa
2484 *
2485 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2486 * resulting keys have correct characteristics.
2487 */
2488TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002489 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002490 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002491 vector<uint8_t> key_blob;
2492 vector<KeyCharacteristics> key_characteristics;
2493 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002494 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002495 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002496 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2497 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002498 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002499 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002500
2501 ASSERT_GT(key_blob.size(), 0U);
2502 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002503 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002504
2505 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2506
2507 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002508 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002509
2510 // Check the usage count limit tag appears in the authorizations.
2511 AuthorizationSet auths;
2512 for (auto& entry : key_characteristics) {
2513 auths.push_back(AuthorizationSet(entry.authorizations));
2514 }
2515 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2516 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002517 }
2518}
2519
2520/*
Selene Huang31ab4042020-04-29 04:22:39 -07002521 * NewKeyGenerationTest.EcdsaDefaultSize
2522 *
David Drysdaledf09e542021-06-08 15:46:11 +01002523 * Verifies that failing to specify a curve for EC key generation returns
David Drysdale84b685a2023-08-09 07:00:34 +01002524 * UNSUPPORTED_KEY_SIZE or UNSUPPORTED_EC_CURVE.
Selene Huang31ab4042020-04-29 04:22:39 -07002525 */
2526TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
David Drysdale84b685a2023-08-09 07:00:34 +01002527 auto result = GenerateKey(AuthorizationSetBuilder()
2528 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2529 .SigningKey()
2530 .Digest(Digest::NONE)
2531 .SetDefaultValidity());
2532 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2533 result == ErrorCode::UNSUPPORTED_EC_CURVE)
2534 << "unexpected result " << result;
Selene Huang31ab4042020-04-29 04:22:39 -07002535}
2536
2537/*
David Drysdale42fe1892021-10-14 14:43:46 +01002538 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002539 *
David Drysdale42fe1892021-10-14 14:43:46 +01002540 * Verifies that specifying an invalid curve for EC key generation returns
David Drysdale84b685a2023-08-09 07:00:34 +01002541 * UNSUPPORTED_KEY_SIZE or UNSUPPORTED_EC_CURVE.
Selene Huang31ab4042020-04-29 04:22:39 -07002542 */
David Drysdale42fe1892021-10-14 14:43:46 +01002543TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002544 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002545 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002546 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002547 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002548 auto result = GenerateKey(AuthorizationSetBuilder()
2549 .EcdsaSigningKey(curve)
2550 .Digest(Digest::NONE)
2551 .SetDefaultValidity(),
2552 &key_blob, &key_characteristics);
2553 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
David Drysdale84b685a2023-08-09 07:00:34 +01002554 result == ErrorCode::UNSUPPORTED_EC_CURVE)
2555 << "unexpected result " << result;
Selene Huang31ab4042020-04-29 04:22:39 -07002556 }
2557
David Drysdaledf09e542021-06-08 15:46:11 +01002558 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2559 GenerateKey(AuthorizationSetBuilder()
2560 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2561 .Authorization(TAG_KEY_SIZE, 190)
2562 .SigningKey()
2563 .Digest(Digest::NONE)
2564 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002565}
2566
2567/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002568 * NewKeyGenerationTest.EcdsaMissingCurve
2569 *
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002570 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V3.
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002571 */
2572TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002573 if (AidlVersion() < 3) {
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002574 /*
2575 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2576 * However, this was not checked at the time so we can only be strict about checking this
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002577 * for implementations of KeyMint version 3 and above.
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002578 */
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002579 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v3";
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002580 }
2581 /* If EC_CURVE not provided, generateKey
2582 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2583 */
2584 auto result = GenerateKey(
2585 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2586 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
David Drysdale0269d492024-11-14 16:51:58 +00002587 result == ErrorCode::UNSUPPORTED_EC_CURVE)
2588 << "unexpected result " << result;
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002589}
2590
2591/*
Selene Huang31ab4042020-04-29 04:22:39 -07002592 * NewKeyGenerationTest.EcdsaMismatchKeySize
2593 *
2594 * Verifies that specifying mismatched key size and curve for EC key generation returns
2595 * INVALID_ARGUMENT.
2596 */
2597TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002598 if (SecLevel() == SecurityLevel::STRONGBOX) {
2599 GTEST_SKIP() << "Test not applicable to StrongBox device";
2600 }
Selene Huang31ab4042020-04-29 04:22:39 -07002601
David Drysdaledf09e542021-06-08 15:46:11 +01002602 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002603 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002604 .Authorization(TAG_KEY_SIZE, 224)
2605 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002606 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002607 .Digest(Digest::NONE)
2608 .SetDefaultValidity());
David Drysdale0269d492024-11-14 16:51:58 +00002609 ASSERT_EQ(result, ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002610}
2611
2612/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002613 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002614 *
2615 * Verifies that keymint does not support any curve designated as unsupported.
2616 */
2617TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2618 Digest digest;
2619 if (SecLevel() == SecurityLevel::STRONGBOX) {
2620 digest = Digest::SHA_2_256;
2621 } else {
2622 digest = Digest::SHA_2_512;
2623 }
2624 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002625 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002626 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2627 .EcdsaSigningKey(curve)
2628 .Digest(digest)
2629 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002630 << "Failed to generate key on curve: " << curve;
2631 CheckedDeleteKey();
2632 }
2633}
2634
2635/*
2636 * NewKeyGenerationTest.Hmac
2637 *
2638 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2639 * characteristics.
2640 */
2641TEST_P(NewKeyGenerationTest, Hmac) {
2642 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002643 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002644 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002645 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002646 constexpr size_t key_size = 128;
2647 ASSERT_EQ(ErrorCode::OK,
2648 GenerateKey(
2649 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2650 TAG_MIN_MAC_LENGTH, 128),
2651 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002652 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07002653
2654 ASSERT_GT(key_blob.size(), 0U);
2655 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002656 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002657
Shawn Willden7f424372021-01-10 18:06:50 -07002658 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2659 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2660 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2661 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002662 }
2663}
2664
2665/*
Selene Huang4f64c222021-04-13 19:54:36 -07002666 * NewKeyGenerationTest.HmacNoAttestation
2667 *
2668 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2669 * and app id are provided.
2670 */
2671TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2672 auto challenge = "hello";
2673 auto app_id = "foo";
2674
2675 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002676 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002677 vector<uint8_t> key_blob;
2678 vector<KeyCharacteristics> key_characteristics;
2679 constexpr size_t key_size = 128;
2680 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2681 .HmacKey(key_size)
2682 .Digest(digest)
2683 .AttestationChallenge(challenge)
2684 .AttestationApplicationId(app_id)
2685 .Authorization(TAG_MIN_MAC_LENGTH, 128),
Seth Moorec5c52ce2024-04-07 15:26:33 -07002686 /*attest_key=*/std::nullopt, &key_blob,
2687 &key_characteristics, &cert_chain_));
David Drysdale1b9febc2023-06-07 13:43:24 +01002688 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002689
2690 ASSERT_GT(key_blob.size(), 0U);
2691 ASSERT_EQ(cert_chain_.size(), 0);
2692 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002693 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002694
2695 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2696 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2697 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2698 << "Key size " << key_size << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002699 }
2700}
2701
2702/*
Qi Wud22ec842020-11-26 13:27:53 +08002703 * NewKeyGenerationTest.LimitedUsageHmac
2704 *
2705 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2706 * resulting keys have correct characteristics.
2707 */
2708TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2709 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002710 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002711 vector<uint8_t> key_blob;
2712 vector<KeyCharacteristics> key_characteristics;
2713 constexpr size_t key_size = 128;
2714 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2715 .HmacKey(key_size)
2716 .Digest(digest)
2717 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2718 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2719 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002720 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002721
2722 ASSERT_GT(key_blob.size(), 0U);
2723 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002724 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002725
2726 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2727 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2728 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2729 << "Key size " << key_size << "missing";
2730
2731 // Check the usage count limit tag appears in the authorizations.
2732 AuthorizationSet auths;
2733 for (auto& entry : key_characteristics) {
2734 auths.push_back(AuthorizationSet(entry.authorizations));
2735 }
2736 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2737 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002738 }
2739}
2740
2741/*
Selene Huang31ab4042020-04-29 04:22:39 -07002742 * NewKeyGenerationTest.HmacCheckKeySizes
2743 *
2744 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2745 */
2746TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2747 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002748 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002749 if (key_size < 64 || key_size % 8 != 0) {
2750 // To keep this test from being very slow, we only test a random fraction of
2751 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2752 // them, we expect to run ~40 of them in each run.
2753 if (key_size % 8 == 0 || random() % 10 == 0) {
2754 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2755 GenerateKey(AuthorizationSetBuilder()
2756 .HmacKey(key_size)
2757 .Digest(Digest::SHA_2_256)
2758 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2759 << "HMAC key size " << key_size << " invalid";
2760 }
2761 } else {
2762 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2763 .HmacKey(key_size)
2764 .Digest(Digest::SHA_2_256)
2765 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2766 << "Failed to generate HMAC key of size " << key_size;
2767 CheckedDeleteKey();
2768 }
2769 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002770 if (SecLevel() == SecurityLevel::STRONGBOX) {
2771 // STRONGBOX devices must not support keys larger than 512 bits.
2772 size_t key_size = 520;
2773 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2774 GenerateKey(AuthorizationSetBuilder()
2775 .HmacKey(key_size)
2776 .Digest(Digest::SHA_2_256)
2777 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2778 << "HMAC key size " << key_size << " unexpectedly valid";
2779 }
Selene Huang31ab4042020-04-29 04:22:39 -07002780}
2781
2782/*
2783 * NewKeyGenerationTest.HmacCheckMinMacLengths
2784 *
2785 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2786 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2787 * specific MAC length that failed, so reproducing a failed run will be easy.
2788 */
2789TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2790 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002791 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002792 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2793 // To keep this test from being very long, we only test a random fraction of
2794 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2795 // we expect to run ~17 of them in each run.
2796 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2797 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2798 GenerateKey(AuthorizationSetBuilder()
2799 .HmacKey(128)
2800 .Digest(Digest::SHA_2_256)
2801 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2802 << "HMAC min mac length " << min_mac_length << " invalid.";
2803 }
2804 } else {
2805 EXPECT_EQ(ErrorCode::OK,
2806 GenerateKey(AuthorizationSetBuilder()
2807 .HmacKey(128)
2808 .Digest(Digest::SHA_2_256)
2809 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2810 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2811 CheckedDeleteKey();
2812 }
2813 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002814
2815 // Minimum MAC length must be no more than 512 bits.
2816 size_t min_mac_length = 520;
2817 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2818 GenerateKey(AuthorizationSetBuilder()
2819 .HmacKey(128)
2820 .Digest(Digest::SHA_2_256)
2821 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2822 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002823}
2824
2825/*
2826 * NewKeyGenerationTest.HmacMultipleDigests
2827 *
2828 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2829 */
2830TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002831 if (SecLevel() == SecurityLevel::STRONGBOX) {
2832 GTEST_SKIP() << "Test not applicable to StrongBox device";
2833 }
Selene Huang31ab4042020-04-29 04:22:39 -07002834
2835 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2836 GenerateKey(AuthorizationSetBuilder()
2837 .HmacKey(128)
2838 .Digest(Digest::SHA1)
2839 .Digest(Digest::SHA_2_256)
2840 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2841}
2842
2843/*
2844 * NewKeyGenerationTest.HmacDigestNone
2845 *
2846 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2847 */
2848TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2849 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2850 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2851 128)));
2852
2853 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2854 GenerateKey(AuthorizationSetBuilder()
2855 .HmacKey(128)
2856 .Digest(Digest::NONE)
2857 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2858}
2859
Selene Huang4f64c222021-04-13 19:54:36 -07002860/*
2861 * NewKeyGenerationTest.AesNoAttestation
2862 *
2863 * Verifies that attestation parameters to AES keys are ignored and generateKey
2864 * will succeed.
2865 */
2866TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2867 auto challenge = "hello";
2868 auto app_id = "foo";
2869
2870 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2871 .Authorization(TAG_NO_AUTH_REQUIRED)
2872 .AesEncryptionKey(128)
2873 .EcbMode()
2874 .Padding(PaddingMode::PKCS7)
2875 .AttestationChallenge(challenge)
Seth Moorec5c52ce2024-04-07 15:26:33 -07002876 .AttestationApplicationId(app_id),
2877 /*attest_key=*/std::nullopt, &key_blob_,
2878 &key_characteristics_, &cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07002879
2880 ASSERT_EQ(cert_chain_.size(), 0);
2881}
2882
2883/*
2884 * NewKeyGenerationTest.TripleDesNoAttestation
2885 *
2886 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2887 * will be successful. No attestation should be generated.
2888 */
2889TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2890 auto challenge = "hello";
2891 auto app_id = "foo";
2892
2893 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2894 .TripleDesEncryptionKey(168)
2895 .BlockMode(BlockMode::ECB)
2896 .Authorization(TAG_NO_AUTH_REQUIRED)
2897 .Padding(PaddingMode::NONE)
2898 .AttestationChallenge(challenge)
Seth Moorec5c52ce2024-04-07 15:26:33 -07002899 .AttestationApplicationId(app_id),
2900 /*attest_key=*/std::nullopt, &key_blob_,
2901 &key_characteristics_, &cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07002902 ASSERT_EQ(cert_chain_.size(), 0);
2903}
2904
Selene Huang31ab4042020-04-29 04:22:39 -07002905INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2906
2907typedef KeyMintAidlTestBase SigningOperationsTest;
2908
2909/*
2910 * SigningOperationsTest.RsaSuccess
2911 *
2912 * Verifies that raw RSA signature operations succeed.
2913 */
2914TEST_P(SigningOperationsTest, RsaSuccess) {
2915 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2916 .RsaSigningKey(2048, 65537)
2917 .Digest(Digest::NONE)
2918 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002919 .Authorization(TAG_NO_AUTH_REQUIRED)
2920 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002921 string message = "12345678901234567890123456789012";
2922 string signature = SignMessage(
2923 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002924 LocalVerifyMessage(message, signature,
2925 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2926}
2927
2928/*
2929 * SigningOperationsTest.RsaAllPaddingsAndDigests
2930 *
2931 * Verifies RSA signature/verification for all padding modes and digests.
2932 */
2933TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2934 auto authorizations = AuthorizationSetBuilder()
2935 .Authorization(TAG_NO_AUTH_REQUIRED)
2936 .RsaSigningKey(2048, 65537)
2937 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2938 .Padding(PaddingMode::NONE)
2939 .Padding(PaddingMode::RSA_PSS)
2940 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2941 .SetDefaultValidity();
2942
2943 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2944
2945 string message(128, 'a');
2946 string corrupt_message(message);
2947 ++corrupt_message[corrupt_message.size() / 2];
2948
2949 for (auto padding :
2950 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2951 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002952 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002953 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2954 // Digesting only makes sense with padding.
2955 continue;
2956 }
2957
2958 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2959 // PSS requires digesting.
2960 continue;
2961 }
2962
2963 string signature =
2964 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2965 LocalVerifyMessage(message, signature,
2966 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2967 }
2968 }
Selene Huang31ab4042020-04-29 04:22:39 -07002969}
2970
2971/*
2972 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2973 *
Shawn Willden7f424372021-01-10 18:06:50 -07002974 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002975 */
2976TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2977 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2978 .Authorization(TAG_NO_AUTH_REQUIRED)
2979 .RsaSigningKey(2048, 65537)
2980 .Digest(Digest::NONE)
2981 .Padding(PaddingMode::NONE)
2982 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002983 .Authorization(TAG_APPLICATION_DATA, "appdata")
2984 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002985
2986 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2987
Selene Huang31ab4042020-04-29 04:22:39 -07002988 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2989 Begin(KeyPurpose::SIGN,
2990 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2991 AbortIfNeeded();
2992 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2993 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2994 .Digest(Digest::NONE)
2995 .Padding(PaddingMode::NONE)
2996 .Authorization(TAG_APPLICATION_ID, "clientid")));
2997 AbortIfNeeded();
2998 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2999 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3000 .Digest(Digest::NONE)
3001 .Padding(PaddingMode::NONE)
3002 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3003 AbortIfNeeded();
3004 EXPECT_EQ(ErrorCode::OK,
3005 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3006 .Digest(Digest::NONE)
3007 .Padding(PaddingMode::NONE)
3008 .Authorization(TAG_APPLICATION_DATA, "appdata")
3009 .Authorization(TAG_APPLICATION_ID, "clientid")));
3010 AbortIfNeeded();
3011}
3012
3013/*
3014 * SigningOperationsTest.RsaPssSha256Success
3015 *
3016 * Verifies that RSA-PSS signature operations succeed.
3017 */
3018TEST_P(SigningOperationsTest, RsaPssSha256Success) {
3019 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3020 .RsaSigningKey(2048, 65537)
3021 .Digest(Digest::SHA_2_256)
3022 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003023 .Authorization(TAG_NO_AUTH_REQUIRED)
3024 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003025 // Use large message, which won't work without digesting.
3026 string message(1024, 'a');
3027 string signature = SignMessage(
3028 message,
3029 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
3030}
3031
3032/*
3033 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
3034 *
3035 * Verifies that keymint rejects signature operations that specify a padding mode when the key
3036 * supports only unpadded operations.
3037 */
3038TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
3039 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3040 .RsaSigningKey(2048, 65537)
3041 .Digest(Digest::NONE)
3042 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003043 .Padding(PaddingMode::NONE)
3044 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003045 string message = "12345678901234567890123456789012";
3046 string signature;
3047
3048 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3049 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3050 .Digest(Digest::NONE)
3051 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3052}
3053
3054/*
3055 * SigningOperationsTest.NoUserConfirmation
3056 *
3057 * Verifies that keymint rejects signing operations for keys with
3058 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
3059 * presented.
3060 */
3061TEST_P(SigningOperationsTest, NoUserConfirmation) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08003062 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Subrahmanyamance2bebd2023-04-28 23:37:02 +00003063 .RsaSigningKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003064 .Digest(Digest::NONE)
3065 .Padding(PaddingMode::NONE)
3066 .Authorization(TAG_NO_AUTH_REQUIRED)
3067 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3068 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003069
3070 const string message = "12345678901234567890123456789012";
3071 EXPECT_EQ(ErrorCode::OK,
3072 Begin(KeyPurpose::SIGN,
3073 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3074 string signature;
3075 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3076}
3077
3078/*
3079 * SigningOperationsTest.RsaPkcs1Sha256Success
3080 *
3081 * Verifies that digested RSA-PKCS1 signature operations succeed.
3082 */
3083TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3084 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3085 .RsaSigningKey(2048, 65537)
3086 .Digest(Digest::SHA_2_256)
3087 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003088 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3089 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003090 string message(1024, 'a');
3091 string signature = SignMessage(message, AuthorizationSetBuilder()
3092 .Digest(Digest::SHA_2_256)
3093 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3094}
3095
3096/*
3097 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3098 *
3099 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3100 */
3101TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3102 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3103 .RsaSigningKey(2048, 65537)
3104 .Digest(Digest::NONE)
3105 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003106 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3107 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003108 string message(53, 'a');
3109 string signature = SignMessage(message, AuthorizationSetBuilder()
3110 .Digest(Digest::NONE)
3111 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3112}
3113
3114/*
3115 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3116 *
3117 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3118 * given a too-long message.
3119 */
3120TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3121 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3122 .RsaSigningKey(2048, 65537)
3123 .Digest(Digest::NONE)
3124 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003125 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3126 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003127 string message(257, 'a');
3128
3129 EXPECT_EQ(ErrorCode::OK,
3130 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3131 .Digest(Digest::NONE)
3132 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3133 string signature;
3134 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3135}
3136
3137/*
3138 * SigningOperationsTest.RsaPssSha512TooSmallKey
3139 *
3140 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3141 * used with a key that is too small for the message.
3142 *
3143 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3144 * keymint specification requires that salt_size == digest_size, so the message will be
3145 * digest_size * 2 +
3146 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3147 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3148 * for a 1024-bit key.
3149 */
3150TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003151 if (SecLevel() == SecurityLevel::STRONGBOX) {
3152 GTEST_SKIP() << "Test not applicable to StrongBox device";
3153 }
Selene Huang31ab4042020-04-29 04:22:39 -07003154 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3155 .RsaSigningKey(1024, 65537)
3156 .Digest(Digest::SHA_2_512)
3157 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003158 .Padding(PaddingMode::RSA_PSS)
3159 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003160 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3161 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3162 .Digest(Digest::SHA_2_512)
3163 .Padding(PaddingMode::RSA_PSS)));
3164}
3165
3166/*
3167 * SigningOperationsTest.RsaNoPaddingTooLong
3168 *
3169 * Verifies that raw RSA signature operations fail with the correct error code when
3170 * given a too-long message.
3171 */
3172TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3173 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3174 .RsaSigningKey(2048, 65537)
3175 .Digest(Digest::NONE)
3176 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003177 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3178 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003179 // One byte too long
3180 string message(2048 / 8 + 1, 'a');
3181 ASSERT_EQ(ErrorCode::OK,
3182 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3183 .Digest(Digest::NONE)
3184 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3185 string result;
3186 ErrorCode finish_error_code = Finish(message, &result);
3187 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
David Drysdale0269d492024-11-14 16:51:58 +00003188 finish_error_code == ErrorCode::INVALID_ARGUMENT)
3189 << "unexpected error code " << finish_error_code;
Selene Huang31ab4042020-04-29 04:22:39 -07003190
3191 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3192 message = string(128 * 1024, 'a');
3193 ASSERT_EQ(ErrorCode::OK,
3194 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3195 .Digest(Digest::NONE)
3196 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3197 finish_error_code = Finish(message, &result);
3198 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
David Drysdale0269d492024-11-14 16:51:58 +00003199 finish_error_code == ErrorCode::INVALID_ARGUMENT)
3200 << "unexpected error code " << finish_error_code;
Selene Huang31ab4042020-04-29 04:22:39 -07003201}
3202
3203/*
3204 * SigningOperationsTest.RsaAbort
3205 *
3206 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3207 * test, but the behavior should be algorithm and purpose-independent.
3208 */
3209TEST_P(SigningOperationsTest, RsaAbort) {
3210 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3211 .RsaSigningKey(2048, 65537)
3212 .Digest(Digest::NONE)
3213 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003214 .Padding(PaddingMode::NONE)
3215 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003216
3217 ASSERT_EQ(ErrorCode::OK,
3218 Begin(KeyPurpose::SIGN,
3219 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3220 EXPECT_EQ(ErrorCode::OK, Abort());
3221
3222 // Another abort should fail
3223 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3224
3225 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003226 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003227}
3228
3229/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003230 * SigningOperationsTest.RsaNonUniqueParams
3231 *
3232 * Verifies that an operation with multiple padding modes is rejected.
3233 */
3234TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3235 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3236 .RsaSigningKey(2048, 65537)
3237 .Digest(Digest::NONE)
3238 .Digest(Digest::SHA1)
3239 .Authorization(TAG_NO_AUTH_REQUIRED)
3240 .Padding(PaddingMode::NONE)
3241 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3242 .SetDefaultValidity()));
3243
3244 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3245 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3246 .Digest(Digest::NONE)
3247 .Padding(PaddingMode::NONE)
3248 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3249
Tommy Chiuc93c4392021-05-11 18:36:50 +08003250 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3251 .Digest(Digest::NONE)
3252 .Digest(Digest::SHA1)
3253 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
David Drysdale0269d492024-11-14 16:51:58 +00003254 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT)
3255 << "unexpected result " << result;
David Drysdaled2cc8c22021-04-15 13:29:45 +01003256
3257 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3258 Begin(KeyPurpose::SIGN,
3259 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3260}
3261
3262/*
Selene Huang31ab4042020-04-29 04:22:39 -07003263 * SigningOperationsTest.RsaUnsupportedPadding
3264 *
3265 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3266 * with a padding mode inappropriate for RSA.
3267 */
3268TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3269 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3270 .RsaSigningKey(2048, 65537)
3271 .Authorization(TAG_NO_AUTH_REQUIRED)
3272 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003273 .Padding(PaddingMode::PKCS7)
3274 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003275 ASSERT_EQ(
3276 ErrorCode::UNSUPPORTED_PADDING_MODE,
3277 Begin(KeyPurpose::SIGN,
3278 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003279 CheckedDeleteKey();
3280
3281 ASSERT_EQ(ErrorCode::OK,
3282 GenerateKey(
3283 AuthorizationSetBuilder()
3284 .RsaSigningKey(2048, 65537)
3285 .Authorization(TAG_NO_AUTH_REQUIRED)
3286 .Digest(Digest::SHA_2_256 /* supported digest */)
3287 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3288 .SetDefaultValidity()));
3289 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3290 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3291 .Digest(Digest::SHA_2_256)
3292 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003293}
3294
3295/*
3296 * SigningOperationsTest.RsaPssNoDigest
3297 *
3298 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3299 */
3300TEST_P(SigningOperationsTest, RsaNoDigest) {
3301 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3302 .RsaSigningKey(2048, 65537)
3303 .Authorization(TAG_NO_AUTH_REQUIRED)
3304 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003305 .Padding(PaddingMode::RSA_PSS)
3306 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003307 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3308 Begin(KeyPurpose::SIGN,
3309 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3310
3311 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3312 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3313}
3314
3315/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003316 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003317 *
3318 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3319 * supported in some cases (as validated in other tests), but a mode must be specified.
3320 */
3321TEST_P(SigningOperationsTest, RsaNoPadding) {
3322 // Padding must be specified
3323 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3324 .RsaKey(2048, 65537)
3325 .Authorization(TAG_NO_AUTH_REQUIRED)
3326 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003327 .Digest(Digest::NONE)
3328 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003329 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3330 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3331}
3332
3333/*
3334 * SigningOperationsTest.RsaShortMessage
3335 *
3336 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3337 */
3338TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3339 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3340 .Authorization(TAG_NO_AUTH_REQUIRED)
3341 .RsaSigningKey(2048, 65537)
3342 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003343 .Padding(PaddingMode::NONE)
3344 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003345
3346 // Barely shorter
3347 string message(2048 / 8 - 1, 'a');
3348 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3349
3350 // Much shorter
3351 message = "a";
3352 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3353}
3354
3355/*
3356 * SigningOperationsTest.RsaSignWithEncryptionKey
3357 *
3358 * Verifies that RSA encryption keys cannot be used to sign.
3359 */
3360TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3361 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3362 .Authorization(TAG_NO_AUTH_REQUIRED)
3363 .RsaEncryptionKey(2048, 65537)
3364 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003365 .Padding(PaddingMode::NONE)
3366 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003367 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3368 Begin(KeyPurpose::SIGN,
3369 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3370}
3371
3372/*
3373 * SigningOperationsTest.RsaSignTooLargeMessage
3374 *
3375 * Verifies that attempting a raw signature of a message which is the same length as the key,
3376 * but numerically larger than the public modulus, fails with the correct error.
3377 */
3378TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3379 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3380 .Authorization(TAG_NO_AUTH_REQUIRED)
3381 .RsaSigningKey(2048, 65537)
3382 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003383 .Padding(PaddingMode::NONE)
3384 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003385
3386 // Largest possible message will always be larger than the public modulus.
3387 string message(2048 / 8, static_cast<char>(0xff));
3388 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3389 .Authorization(TAG_NO_AUTH_REQUIRED)
3390 .Digest(Digest::NONE)
3391 .Padding(PaddingMode::NONE)));
3392 string signature;
3393 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3394}
3395
3396/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003397 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3398 *
David Drysdale42fe1892021-10-14 14:43:46 +01003399 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003400 */
3401TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003402 string message = "1234567890";
3403 string corrupt_message = "2234567890";
3404 for (auto curve : ValidCurves()) {
3405 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003406 // Ed25519 only allows Digest::NONE.
3407 auto digests = (curve == EcCurve::CURVE_25519)
3408 ? std::vector<Digest>(1, Digest::NONE)
3409 : ValidDigests(true /* withNone */, false /* withMD5 */);
3410
David Drysdaledf8f52e2021-05-06 08:10:58 +01003411 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3412 .Authorization(TAG_NO_AUTH_REQUIRED)
3413 .EcdsaSigningKey(curve)
3414 .Digest(digests)
3415 .SetDefaultValidity());
3416 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3417 if (error != ErrorCode::OK) {
3418 continue;
3419 }
3420
3421 for (auto digest : digests) {
3422 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3423 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3424 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3425 }
3426
3427 auto rc = DeleteKey();
David Drysdale0269d492024-11-14 16:51:58 +00003428 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED)
3429 << "unexpected result " << rc;
David Drysdaledf8f52e2021-05-06 08:10:58 +01003430 }
3431}
3432
3433/*
Selene Huang31ab4042020-04-29 04:22:39 -07003434 * SigningOperationsTest.EcdsaAllCurves
3435 *
David Drysdale42fe1892021-10-14 14:43:46 +01003436 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003437 */
3438TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3439 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003440 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3441 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003442 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3443 .Authorization(TAG_NO_AUTH_REQUIRED)
3444 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003445 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003446 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003447 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3448 if (error != ErrorCode::OK) continue;
3449
3450 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003451 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003452 CheckedDeleteKey();
3453 }
3454}
3455
3456/*
David Drysdale42fe1892021-10-14 14:43:46 +01003457 * SigningOperationsTest.EcdsaCurve25519
3458 *
3459 * Verifies that ECDSA operations succeed with curve25519.
3460 */
3461TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3462 if (!Curve25519Supported()) {
3463 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3464 }
3465
3466 EcCurve curve = EcCurve::CURVE_25519;
3467 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3468 .Authorization(TAG_NO_AUTH_REQUIRED)
3469 .EcdsaSigningKey(curve)
3470 .Digest(Digest::NONE)
3471 .SetDefaultValidity());
3472 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3473
3474 string message(1024, 'a');
3475 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3476 CheckedDeleteKey();
3477}
3478
3479/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003480 * SigningOperationsTest.EcdsaCurve25519MaxSize
3481 *
3482 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3483 */
3484TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3485 if (!Curve25519Supported()) {
3486 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3487 }
3488
3489 EcCurve curve = EcCurve::CURVE_25519;
3490 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3491 .Authorization(TAG_NO_AUTH_REQUIRED)
3492 .EcdsaSigningKey(curve)
3493 .Digest(Digest::NONE)
3494 .SetDefaultValidity());
3495 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3496
3497 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3498
3499 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3500 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3501 string message(msg_size, 'a');
3502
3503 // Attempt to sign via Begin+Finish.
3504 AuthorizationSet out_params;
3505 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3506 EXPECT_TRUE(out_params.empty());
3507 string signature;
3508 auto result = Finish(message, &signature);
3509 EXPECT_EQ(result, ErrorCode::OK);
3510 LocalVerifyMessage(message, signature, params);
3511
3512 // Attempt to sign via Begin+Update+Finish
3513 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3514 EXPECT_TRUE(out_params.empty());
3515 string output;
3516 result = Update(message, &output);
3517 EXPECT_EQ(result, ErrorCode::OK);
3518 EXPECT_EQ(output.size(), 0);
3519 string signature2;
3520 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3521 LocalVerifyMessage(message, signature2, params);
3522 }
3523
3524 CheckedDeleteKey();
3525}
3526
3527/*
3528 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3529 *
3530 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3531 */
3532TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3533 if (!Curve25519Supported()) {
3534 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3535 }
3536
3537 EcCurve curve = EcCurve::CURVE_25519;
3538 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3539 .Authorization(TAG_NO_AUTH_REQUIRED)
3540 .EcdsaSigningKey(curve)
3541 .Digest(Digest::NONE)
3542 .SetDefaultValidity());
3543 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3544
3545 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3546
3547 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3548 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3549 string message(msg_size, 'a');
3550
3551 // Attempt to sign via Begin+Finish.
3552 AuthorizationSet out_params;
3553 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3554 EXPECT_TRUE(out_params.empty());
3555 string signature;
3556 auto result = Finish(message, &signature);
3557 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3558
3559 // Attempt to sign via Begin+Update (but never get to Finish)
3560 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3561 EXPECT_TRUE(out_params.empty());
3562 string output;
3563 result = Update(message, &output);
3564 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3565 }
3566
3567 CheckedDeleteKey();
3568}
3569
3570/*
Selene Huang31ab4042020-04-29 04:22:39 -07003571 * SigningOperationsTest.EcdsaNoDigestHugeData
3572 *
3573 * Verifies that ECDSA operations support very large messages, even without digesting. This
3574 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3575 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3576 * the framework.
3577 */
3578TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3579 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3580 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003581 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003582 .Digest(Digest::NONE)
3583 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003584 string message(1 * 1024, 'a');
3585 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3586}
3587
3588/*
3589 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3590 *
3591 * Verifies that using an EC key requires the correct app ID/data.
3592 */
3593TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3594 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3595 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003596 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003597 .Digest(Digest::NONE)
3598 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003599 .Authorization(TAG_APPLICATION_DATA, "appdata")
3600 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003601
3602 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3603
Selene Huang31ab4042020-04-29 04:22:39 -07003604 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3605 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3606 AbortIfNeeded();
3607 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3608 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3609 .Digest(Digest::NONE)
3610 .Authorization(TAG_APPLICATION_ID, "clientid")));
3611 AbortIfNeeded();
3612 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3613 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3614 .Digest(Digest::NONE)
3615 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3616 AbortIfNeeded();
3617 EXPECT_EQ(ErrorCode::OK,
3618 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3619 .Digest(Digest::NONE)
3620 .Authorization(TAG_APPLICATION_DATA, "appdata")
3621 .Authorization(TAG_APPLICATION_ID, "clientid")));
3622 AbortIfNeeded();
3623}
3624
3625/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003626 * SigningOperationsTest.EcdsaIncompatibleDigest
3627 *
3628 * Verifies that using an EC key requires compatible digest.
3629 */
3630TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3631 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3632 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003633 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003634 .Digest(Digest::NONE)
3635 .Digest(Digest::SHA1)
3636 .SetDefaultValidity()));
3637 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3638 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3639 AbortIfNeeded();
3640}
3641
3642/*
Selene Huang31ab4042020-04-29 04:22:39 -07003643 * SigningOperationsTest.AesEcbSign
3644 *
3645 * Verifies that attempts to use AES keys to sign fail in the correct way.
3646 */
3647TEST_P(SigningOperationsTest, AesEcbSign) {
3648 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3649 .Authorization(TAG_NO_AUTH_REQUIRED)
3650 .SigningKey()
3651 .AesEncryptionKey(128)
3652 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3653
3654 AuthorizationSet out_params;
3655 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3656 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3657 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3658 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3659}
3660
3661/*
3662 * SigningOperationsTest.HmacAllDigests
3663 *
3664 * Verifies that HMAC works with all digests.
3665 */
3666TEST_P(SigningOperationsTest, HmacAllDigests) {
3667 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003668 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003669 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3670 .Authorization(TAG_NO_AUTH_REQUIRED)
3671 .HmacKey(128)
3672 .Digest(digest)
3673 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3674 << "Failed to create HMAC key with digest " << digest;
3675 string message = "12345678901234567890123456789012";
3676 string signature = MacMessage(message, digest, 160);
3677 EXPECT_EQ(160U / 8U, signature.size())
3678 << "Failed to sign with HMAC key with digest " << digest;
3679 CheckedDeleteKey();
3680 }
3681}
3682
3683/*
David Drysdaleb4598742024-04-23 13:35:15 +01003684 * SigningOperationsTest.HmacMessageDigestUnique
3685 *
3686 * Verifies that HMAC with different keys gives different results.
3687 */
3688TEST_P(SigningOperationsTest, HmacMessageDigestUnique) {
3689 for (int key_len : {64, 128, 192, 256, 512}) {
3690 for (int msg_len = 0; msg_len <= 30; msg_len += 10) {
3691 string message = string(msg_len, 'x');
3692 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
3693 SCOPED_TRACE(testing::Message() << "Digest::" << digest << "::MsgLen::" << msg_len);
3694
3695 int count = 10;
3696 std::set<string> results;
3697 for (int ii = 0; ii < count; ii++) {
3698 ASSERT_EQ(ErrorCode::OK,
3699 GenerateKey(AuthorizationSetBuilder()
3700 .Authorization(TAG_NO_AUTH_REQUIRED)
3701 .HmacKey(key_len)
3702 .Digest(digest)
3703 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3704 << "Failed to create HMAC key with digest " << digest;
3705 string signature = MacMessage(message, digest, 160);
3706 EXPECT_EQ(160U / 8U, signature.size())
3707 << "Failed to sign with HMAC key with digest " << digest;
3708 CheckedDeleteKey();
3709 results.insert(signature);
3710 }
3711 EXPECT_EQ(results.size(), count)
3712 << "HMAC of a message '" << message << "' with " << count
3713 << " fresh keys only gave " << results.size() << " distinct results";
3714 }
3715 }
3716 }
3717}
3718
3719/*
Selene Huang31ab4042020-04-29 04:22:39 -07003720 * SigningOperationsTest.HmacSha256TooLargeMacLength
3721 *
3722 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3723 * digest size.
3724 */
3725TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3726 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3727 .Authorization(TAG_NO_AUTH_REQUIRED)
3728 .HmacKey(128)
3729 .Digest(Digest::SHA_2_256)
3730 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3731 AuthorizationSet output_params;
3732 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3733 AuthorizationSetBuilder()
3734 .Digest(Digest::SHA_2_256)
3735 .Authorization(TAG_MAC_LENGTH, 264),
3736 &output_params));
3737}
3738
3739/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003740 * SigningOperationsTest.HmacSha256InvalidMacLength
3741 *
3742 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3743 * not a multiple of 8.
3744 */
3745TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3746 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3747 .Authorization(TAG_NO_AUTH_REQUIRED)
3748 .HmacKey(128)
3749 .Digest(Digest::SHA_2_256)
3750 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3751 AuthorizationSet output_params;
3752 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3753 AuthorizationSetBuilder()
3754 .Digest(Digest::SHA_2_256)
3755 .Authorization(TAG_MAC_LENGTH, 161),
3756 &output_params));
3757}
3758
3759/*
Selene Huang31ab4042020-04-29 04:22:39 -07003760 * SigningOperationsTest.HmacSha256TooSmallMacLength
3761 *
3762 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3763 * specified minimum MAC length.
3764 */
3765TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3766 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3767 .Authorization(TAG_NO_AUTH_REQUIRED)
3768 .HmacKey(128)
3769 .Digest(Digest::SHA_2_256)
3770 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3771 AuthorizationSet output_params;
3772 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3773 AuthorizationSetBuilder()
3774 .Digest(Digest::SHA_2_256)
3775 .Authorization(TAG_MAC_LENGTH, 120),
3776 &output_params));
3777}
3778
3779/*
3780 * SigningOperationsTest.HmacRfc4231TestCase3
3781 *
3782 * Validates against the test vectors from RFC 4231 test case 3.
3783 */
3784TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3785 string key(20, 0xaa);
3786 string message(50, 0xdd);
3787 uint8_t sha_224_expected[] = {
3788 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3789 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3790 };
3791 uint8_t sha_256_expected[] = {
3792 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3793 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3794 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3795 };
3796 uint8_t sha_384_expected[] = {
3797 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3798 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3799 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3800 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3801 };
3802 uint8_t sha_512_expected[] = {
3803 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3804 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3805 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3806 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3807 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3808 };
3809
3810 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3811 if (SecLevel() != SecurityLevel::STRONGBOX) {
3812 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3813 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3814 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3815 }
3816}
3817
3818/*
3819 * SigningOperationsTest.HmacRfc4231TestCase5
3820 *
3821 * Validates against the test vectors from RFC 4231 test case 5.
3822 */
3823TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3824 string key(20, 0x0c);
3825 string message = "Test With Truncation";
3826
3827 uint8_t sha_224_expected[] = {
3828 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3829 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3830 };
3831 uint8_t sha_256_expected[] = {
3832 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3833 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3834 };
3835 uint8_t sha_384_expected[] = {
3836 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3837 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3838 };
3839 uint8_t sha_512_expected[] = {
3840 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3841 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3842 };
3843
3844 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3845 if (SecLevel() != SecurityLevel::STRONGBOX) {
3846 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3847 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3848 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3849 }
3850}
3851
3852INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3853
3854typedef KeyMintAidlTestBase VerificationOperationsTest;
3855
3856/*
Selene Huang31ab4042020-04-29 04:22:39 -07003857 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3858 *
3859 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3860 */
3861TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3862 string key_material = "HelloThisIsAKey";
3863
3864 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003865 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003866 EXPECT_EQ(ErrorCode::OK,
3867 ImportKey(AuthorizationSetBuilder()
3868 .Authorization(TAG_NO_AUTH_REQUIRED)
3869 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3870 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3871 .Digest(Digest::SHA_2_256)
3872 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3873 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003874 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003875 EXPECT_EQ(ErrorCode::OK,
3876 ImportKey(AuthorizationSetBuilder()
3877 .Authorization(TAG_NO_AUTH_REQUIRED)
3878 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3879 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3880 .Digest(Digest::SHA_2_256)
3881 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3882 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003883 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003884
3885 string message = "This is a message.";
3886 string signature = SignMessage(
3887 signing_key, message,
3888 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3889
3890 // Signing key should not work.
3891 AuthorizationSet out_params;
3892 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3893 Begin(KeyPurpose::VERIFY, signing_key,
3894 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3895
3896 // Verification key should work.
3897 VerifyMessage(verification_key, message, signature,
3898 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Selene Huang31ab4042020-04-29 04:22:39 -07003899}
3900
Prashant Patildec9fdc2021-12-08 15:25:47 +00003901/*
3902 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3903 *
3904 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3905 */
3906TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3907 string key_material = "HelloThisIsAKey";
3908
3909 vector<uint8_t> signing_key, verification_key;
3910 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3911 EXPECT_EQ(ErrorCode::OK,
3912 ImportKey(AuthorizationSetBuilder()
3913 .Authorization(TAG_NO_AUTH_REQUIRED)
3914 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3915 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3916 .Digest(Digest::SHA_2_256)
3917 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3918 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003919 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003920 EXPECT_EQ(ErrorCode::OK,
3921 ImportKey(AuthorizationSetBuilder()
3922 .Authorization(TAG_NO_AUTH_REQUIRED)
3923 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3924 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3925 .Digest(Digest::SHA_2_256)
3926 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3927 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003928 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003929
3930 string message = "This is a message.";
3931 string signature = SignMessage(
3932 signing_key, message,
3933 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3934
3935 AuthorizationSet begin_out_params;
3936 ASSERT_EQ(ErrorCode::OK,
3937 Begin(KeyPurpose::VERIFY, verification_key,
3938 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3939
3940 string corruptMessage = "This is b message."; // Corrupted message
3941 string output;
3942 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3943
3944 ASSERT_EQ(ErrorCode::OK,
3945 Begin(KeyPurpose::VERIFY, verification_key,
3946 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3947
3948 signature[0] += 1; // Corrupt a signature
3949 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
Prashant Patildec9fdc2021-12-08 15:25:47 +00003950}
3951
Selene Huang31ab4042020-04-29 04:22:39 -07003952INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3953
3954typedef KeyMintAidlTestBase ExportKeyTest;
3955
3956/*
3957 * ExportKeyTest.RsaUnsupportedKeyFormat
3958 *
3959 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3960 */
3961// TODO(seleneh) add ExportKey to GenerateKey
3962// check result
3963
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003964class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003965 public:
3966 template <TagType tag_type, Tag tag, typename ValueT>
3967 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3968 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003969 for (auto& entry : key_characteristics_) {
3970 if (entry.securityLevel == SecLevel()) {
3971 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3972 << "Tag " << tag << " with value " << expected
3973 << " not found at security level" << entry.securityLevel;
3974 } else {
3975 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3976 << "Tag " << tag << " found at security level " << entry.securityLevel;
3977 }
Selene Huang31ab4042020-04-29 04:22:39 -07003978 }
3979 }
3980
3981 void CheckOrigin() {
3982 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003983 // Origin isn't a crypto param, but it always lives with them.
3984 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003985 }
3986};
3987
3988/*
3989 * ImportKeyTest.RsaSuccess
3990 *
3991 * Verifies that importing and using an RSA key pair works correctly.
3992 */
3993TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003994 uint32_t key_size;
3995 string key;
3996
3997 if (SecLevel() == SecurityLevel::STRONGBOX) {
3998 key_size = 2048;
3999 key = rsa_2048_key;
4000 } else {
4001 key_size = 1024;
4002 key = rsa_key;
4003 }
4004
Selene Huang31ab4042020-04-29 04:22:39 -07004005 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4006 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07004007 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07004008 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004009 .Padding(PaddingMode::RSA_PSS)
4010 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07004011 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07004012
4013 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07004014 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07004015 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4016 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4017 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4018 CheckOrigin();
4019
4020 string message(1024 / 8, 'a');
4021 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4022 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004023 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004024}
4025
4026/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004027 * ImportKeyTest.RsaSuccessWithoutParams
4028 *
4029 * Verifies that importing and using an RSA key pair without specifying parameters
4030 * works correctly.
4031 */
4032TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
4033 uint32_t key_size;
4034 string key;
4035
4036 if (SecLevel() == SecurityLevel::STRONGBOX) {
4037 key_size = 2048;
4038 key = rsa_2048_key;
4039 } else {
4040 key_size = 1024;
4041 key = rsa_key;
4042 }
4043
4044 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4045 .Authorization(TAG_NO_AUTH_REQUIRED)
4046 .SigningKey()
4047 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4048 .Digest(Digest::SHA_2_256)
4049 .Padding(PaddingMode::RSA_PSS)
4050 .SetDefaultValidity(),
4051 KeyFormat::PKCS8, key));
4052
4053 // Key size and public exponent are determined from the imported key material.
4054 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4055 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4056
4057 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4058 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4059 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4060 CheckOrigin();
4061
4062 string message(1024 / 8, 'a');
4063 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4064 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004065 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004066}
4067
4068/*
Selene Huang31ab4042020-04-29 04:22:39 -07004069 * ImportKeyTest.RsaKeySizeMismatch
4070 *
4071 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4072 * correct way.
4073 */
4074TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4075 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4076 ImportKey(AuthorizationSetBuilder()
4077 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4078 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004079 .Padding(PaddingMode::NONE)
4080 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004081 KeyFormat::PKCS8, rsa_key));
4082}
4083
4084/*
4085 * ImportKeyTest.RsaPublicExponentMismatch
4086 *
4087 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4088 * fails in the correct way.
4089 */
4090TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4091 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4092 ImportKey(AuthorizationSetBuilder()
4093 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4094 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004095 .Padding(PaddingMode::NONE)
4096 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004097 KeyFormat::PKCS8, rsa_key));
4098}
4099
4100/*
David Drysdalee60248c2021-10-04 12:54:13 +01004101 * ImportKeyTest.RsaAttestMultiPurposeFail
4102 *
4103 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4104 */
4105TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004106 if (AidlVersion() < 2) {
4107 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4108 // with other key purposes. However, this was not checked at the time
4109 // so we can only be strict about checking this for implementations of KeyMint
4110 // version 2 and above.
4111 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4112 }
David Drysdalee60248c2021-10-04 12:54:13 +01004113 uint32_t key_size = 2048;
4114 string key = rsa_2048_key;
4115
4116 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4117 ImportKey(AuthorizationSetBuilder()
4118 .Authorization(TAG_NO_AUTH_REQUIRED)
4119 .RsaSigningKey(key_size, 65537)
4120 .AttestKey()
4121 .Digest(Digest::SHA_2_256)
4122 .Padding(PaddingMode::RSA_PSS)
4123 .SetDefaultValidity(),
4124 KeyFormat::PKCS8, key));
4125}
4126
4127/*
Selene Huang31ab4042020-04-29 04:22:39 -07004128 * ImportKeyTest.EcdsaSuccess
4129 *
4130 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4131 */
4132TEST_P(ImportKeyTest, EcdsaSuccess) {
4133 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4134 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004135 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004136 .Digest(Digest::SHA_2_256)
4137 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004138 KeyFormat::PKCS8, ec_256_key));
4139
4140 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004141 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4142 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4143
4144 CheckOrigin();
4145
4146 string message(32, 'a');
4147 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4148 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004149 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004150}
4151
4152/*
David Drysdale9b8d75e2023-09-05 15:16:47 +01004153 * ImportKeyTest.EcdsaSuccessCurveNotSpecified
4154 *
4155 * Verifies that importing and using an ECDSA P-256 key pair works correctly
4156 * when the EC_CURVE is not explicitly specified.
4157 */
4158TEST_P(ImportKeyTest, EcdsaSuccessCurveNotSpecified) {
David Drysdale1405dbc2023-11-02 09:26:44 +00004159 if (get_vsr_api_level() < __ANDROID_API_V__) {
David Drysdale9b8d75e2023-09-05 15:16:47 +01004160 /*
David Drysdale1405dbc2023-11-02 09:26:44 +00004161 * The KeyMint spec was previously not clear as to whether EC_CURVE was optional on import
4162 * of EC keys. However, this was not checked at the time so we can only be strict about
4163 * checking this for implementations at VSR-V or later.
David Drysdale9b8d75e2023-09-05 15:16:47 +01004164 */
David Drysdale1405dbc2023-11-02 09:26:44 +00004165 GTEST_SKIP() << "Skipping EC_CURVE on import only strict >= VSR-V";
David Drysdale9b8d75e2023-09-05 15:16:47 +01004166 }
4167
4168 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4169 .Authorization(TAG_NO_AUTH_REQUIRED)
4170 .Authorization(TAG_ALGORITHM, Algorithm::EC)
4171 .SigningKey()
4172 .Digest(Digest::SHA_2_256)
4173 .SetDefaultValidity(),
4174 KeyFormat::PKCS8, ec_256_key));
4175
4176 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4177 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4178 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4179
4180 CheckOrigin();
4181
4182 string message(32, 'a');
4183 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4184 string signature = SignMessage(message, params);
4185 LocalVerifyMessage(message, signature, params);
4186}
4187
4188/*
Selene Huang31ab4042020-04-29 04:22:39 -07004189 * ImportKeyTest.EcdsaP256RFC5915Success
4190 *
4191 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4192 * correctly.
4193 */
4194TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4195 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4196 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004197 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004198 .Digest(Digest::SHA_2_256)
4199 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004200 KeyFormat::PKCS8, ec_256_key_rfc5915));
4201
4202 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004203 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4204 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4205
4206 CheckOrigin();
4207
4208 string message(32, 'a');
4209 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4210 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004211 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004212}
4213
4214/*
4215 * ImportKeyTest.EcdsaP256SEC1Success
4216 *
4217 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4218 */
4219TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4220 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4221 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004222 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004223 .Digest(Digest::SHA_2_256)
4224 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004225 KeyFormat::PKCS8, ec_256_key_sec1));
4226
4227 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004228 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4229 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4230
4231 CheckOrigin();
4232
4233 string message(32, 'a');
4234 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4235 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004236 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004237}
4238
4239/*
4240 * ImportKeyTest.Ecdsa521Success
4241 *
4242 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4243 */
4244TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004245 if (SecLevel() == SecurityLevel::STRONGBOX) {
4246 GTEST_SKIP() << "Test not applicable to StrongBox device";
4247 }
Selene Huang31ab4042020-04-29 04:22:39 -07004248 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4249 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004250 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004251 .Digest(Digest::SHA_2_256)
4252 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004253 KeyFormat::PKCS8, ec_521_key));
4254
4255 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004256 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4257 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4258 CheckOrigin();
4259
4260 string message(32, 'a');
4261 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4262 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004263 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004264}
4265
4266/*
Selene Huang31ab4042020-04-29 04:22:39 -07004267 * ImportKeyTest.EcdsaCurveMismatch
4268 *
4269 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4270 * the correct way.
4271 */
4272TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4273 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4274 ImportKey(AuthorizationSetBuilder()
4275 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004276 .Digest(Digest::NONE)
4277 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004278 KeyFormat::PKCS8, ec_256_key));
4279}
4280
4281/*
David Drysdalee60248c2021-10-04 12:54:13 +01004282 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4283 *
4284 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4285 */
4286TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004287 if (AidlVersion() < 2) {
4288 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4289 // with other key purposes. However, this was not checked at the time
4290 // so we can only be strict about checking this for implementations of KeyMint
4291 // version 2 and above.
4292 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4293 }
David Drysdalee60248c2021-10-04 12:54:13 +01004294 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4295 ImportKey(AuthorizationSetBuilder()
4296 .Authorization(TAG_NO_AUTH_REQUIRED)
4297 .EcdsaSigningKey(EcCurve::P_256)
4298 .AttestKey()
4299 .Digest(Digest::SHA_2_256)
4300 .SetDefaultValidity(),
4301 KeyFormat::PKCS8, ec_256_key));
4302}
4303
4304/*
David Drysdale42fe1892021-10-14 14:43:46 +01004305 * ImportKeyTest.Ed25519RawSuccess
4306 *
4307 * Verifies that importing and using a raw Ed25519 private key works correctly.
4308 */
4309TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4310 if (!Curve25519Supported()) {
4311 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4312 }
4313
4314 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4315 .Authorization(TAG_NO_AUTH_REQUIRED)
4316 .EcdsaSigningKey(EcCurve::CURVE_25519)
4317 .Digest(Digest::NONE)
4318 .SetDefaultValidity(),
4319 KeyFormat::RAW, ed25519_key));
4320 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4321 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4322 CheckOrigin();
4323
4324 // The returned cert should hold the correct public key.
4325 ASSERT_GT(cert_chain_.size(), 0);
4326 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4327 ASSERT_NE(kmKeyCert, nullptr);
4328 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4329 ASSERT_NE(kmPubKey.get(), nullptr);
4330 size_t kmPubKeySize = 32;
4331 uint8_t kmPubKeyData[32];
4332 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4333 ASSERT_EQ(kmPubKeySize, 32);
4334 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4335
4336 string message(32, 'a');
4337 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4338 string signature = SignMessage(message, params);
4339 LocalVerifyMessage(message, signature, params);
4340}
4341
4342/*
4343 * ImportKeyTest.Ed25519Pkcs8Success
4344 *
4345 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4346 */
4347TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4348 if (!Curve25519Supported()) {
4349 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4350 }
4351
4352 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4353 .Authorization(TAG_NO_AUTH_REQUIRED)
4354 .EcdsaSigningKey(EcCurve::CURVE_25519)
4355 .Digest(Digest::NONE)
4356 .SetDefaultValidity(),
4357 KeyFormat::PKCS8, ed25519_pkcs8_key));
4358 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4359 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4360 CheckOrigin();
4361
4362 // The returned cert should hold the correct public key.
4363 ASSERT_GT(cert_chain_.size(), 0);
4364 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4365 ASSERT_NE(kmKeyCert, nullptr);
4366 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4367 ASSERT_NE(kmPubKey.get(), nullptr);
4368 size_t kmPubKeySize = 32;
4369 uint8_t kmPubKeyData[32];
4370 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4371 ASSERT_EQ(kmPubKeySize, 32);
4372 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4373
4374 string message(32, 'a');
4375 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4376 string signature = SignMessage(message, params);
4377 LocalVerifyMessage(message, signature, params);
4378}
4379
4380/*
4381 * ImportKeyTest.Ed25519CurveMismatch
4382 *
4383 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4384 * the correct way.
4385 */
4386TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4387 if (!Curve25519Supported()) {
4388 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4389 }
4390
4391 ASSERT_NE(ErrorCode::OK,
4392 ImportKey(AuthorizationSetBuilder()
4393 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4394 .Digest(Digest::NONE)
4395 .SetDefaultValidity(),
4396 KeyFormat::RAW, ed25519_key));
4397}
4398
4399/*
4400 * ImportKeyTest.Ed25519FormatMismatch
4401 *
4402 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4403 */
4404TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4405 if (!Curve25519Supported()) {
4406 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4407 }
4408
4409 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4410 .EcdsaSigningKey(EcCurve::CURVE_25519)
4411 .Digest(Digest::NONE)
4412 .SetDefaultValidity(),
4413 KeyFormat::PKCS8, ed25519_key));
4414 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4415 .EcdsaSigningKey(EcCurve::CURVE_25519)
4416 .Digest(Digest::NONE)
4417 .SetDefaultValidity(),
4418 KeyFormat::RAW, ed25519_pkcs8_key));
4419}
4420
4421/*
4422 * ImportKeyTest.Ed25519PurposeMismatch
4423 *
4424 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4425 */
4426TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4427 if (!Curve25519Supported()) {
4428 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4429 }
4430
4431 // Can't have both SIGN and ATTEST_KEY
4432 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4433 .EcdsaSigningKey(EcCurve::CURVE_25519)
4434 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4435 .Digest(Digest::NONE)
4436 .SetDefaultValidity(),
4437 KeyFormat::RAW, ed25519_key));
4438 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4439 // PKCS#8 format and so includes an OID).
4440 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4441 .EcdsaKey(EcCurve::CURVE_25519)
4442 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4443 .Digest(Digest::NONE)
4444 .SetDefaultValidity(),
4445 KeyFormat::PKCS8, ed25519_pkcs8_key));
4446}
4447
4448/*
4449 * ImportKeyTest.X25519RawSuccess
4450 *
4451 * Verifies that importing and using a raw X25519 private key works correctly.
4452 */
4453TEST_P(ImportKeyTest, X25519RawSuccess) {
4454 if (!Curve25519Supported()) {
4455 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4456 }
4457
4458 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4459 .Authorization(TAG_NO_AUTH_REQUIRED)
4460 .EcdsaKey(EcCurve::CURVE_25519)
4461 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4462 .SetDefaultValidity(),
4463 KeyFormat::RAW, x25519_key));
4464
4465 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4466 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4467 CheckOrigin();
4468}
4469
4470/*
4471 * ImportKeyTest.X25519Pkcs8Success
4472 *
4473 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4474 */
4475TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4476 if (!Curve25519Supported()) {
4477 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4478 }
4479
4480 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4481 .Authorization(TAG_NO_AUTH_REQUIRED)
4482 .EcdsaKey(EcCurve::CURVE_25519)
4483 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4484 .SetDefaultValidity(),
4485 KeyFormat::PKCS8, x25519_pkcs8_key));
4486
4487 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4488 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4489 CheckOrigin();
4490}
4491
4492/*
4493 * ImportKeyTest.X25519CurveMismatch
4494 *
4495 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4496 * the correct way.
4497 */
4498TEST_P(ImportKeyTest, X25519CurveMismatch) {
4499 if (!Curve25519Supported()) {
4500 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4501 }
4502
4503 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4504 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4505 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4506 .SetDefaultValidity(),
4507 KeyFormat::RAW, x25519_key));
4508}
4509
4510/*
4511 * ImportKeyTest.X25519FormatMismatch
4512 *
4513 * Verifies that importing an X25519 key with an invalid format fails.
4514 */
4515TEST_P(ImportKeyTest, X25519FormatMismatch) {
4516 if (!Curve25519Supported()) {
4517 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4518 }
4519
4520 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4521 .EcdsaKey(EcCurve::CURVE_25519)
4522 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4523 .SetDefaultValidity(),
4524 KeyFormat::PKCS8, x25519_key));
4525 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4526 .EcdsaKey(EcCurve::CURVE_25519)
4527 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4528 .SetDefaultValidity(),
4529 KeyFormat::RAW, x25519_pkcs8_key));
4530}
4531
4532/*
4533 * ImportKeyTest.X25519PurposeMismatch
4534 *
4535 * Verifies that importing an X25519 key pair with an invalid format fails.
4536 */
4537TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4538 if (!Curve25519Supported()) {
4539 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4540 }
4541
4542 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4543 .EcdsaKey(EcCurve::CURVE_25519)
4544 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4545 .SetDefaultValidity(),
4546 KeyFormat::PKCS8, x25519_pkcs8_key));
4547 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4548 .EcdsaSigningKey(EcCurve::CURVE_25519)
4549 .SetDefaultValidity(),
4550 KeyFormat::PKCS8, x25519_pkcs8_key));
4551}
4552
4553/*
Selene Huang31ab4042020-04-29 04:22:39 -07004554 * ImportKeyTest.AesSuccess
4555 *
4556 * Verifies that importing and using an AES key works.
4557 */
4558TEST_P(ImportKeyTest, AesSuccess) {
4559 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4560 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4561 .Authorization(TAG_NO_AUTH_REQUIRED)
4562 .AesEncryptionKey(key.size() * 8)
4563 .EcbMode()
4564 .Padding(PaddingMode::PKCS7),
4565 KeyFormat::RAW, key));
4566
4567 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4568 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4569 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4570 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4571 CheckOrigin();
4572
4573 string message = "Hello World!";
4574 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4575 string ciphertext = EncryptMessage(message, params);
4576 string plaintext = DecryptMessage(ciphertext, params);
4577 EXPECT_EQ(message, plaintext);
4578}
4579
4580/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004581 * ImportKeyTest.AesFailure
4582 *
4583 * Verifies that importing an invalid AES key fails.
4584 */
4585TEST_P(ImportKeyTest, AesFailure) {
4586 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4587 uint32_t bitlen = key.size() * 8;
4588 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004589 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004590 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004591 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004592 .Authorization(TAG_NO_AUTH_REQUIRED)
4593 .AesEncryptionKey(key_size)
4594 .EcbMode()
4595 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004596 KeyFormat::RAW, key);
4597 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004598 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4599 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004600 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004601
4602 // Explicit key size matches that of the provided key, but it's not a valid size.
4603 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4604 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4605 ImportKey(AuthorizationSetBuilder()
4606 .Authorization(TAG_NO_AUTH_REQUIRED)
4607 .AesEncryptionKey(long_key.size() * 8)
4608 .EcbMode()
4609 .Padding(PaddingMode::PKCS7),
4610 KeyFormat::RAW, long_key));
4611 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4612 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4613 ImportKey(AuthorizationSetBuilder()
4614 .Authorization(TAG_NO_AUTH_REQUIRED)
4615 .AesEncryptionKey(short_key.size() * 8)
4616 .EcbMode()
4617 .Padding(PaddingMode::PKCS7),
4618 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004619}
4620
4621/*
4622 * ImportKeyTest.TripleDesSuccess
4623 *
4624 * Verifies that importing and using a 3DES key works.
4625 */
4626TEST_P(ImportKeyTest, TripleDesSuccess) {
4627 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4628 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4629 .Authorization(TAG_NO_AUTH_REQUIRED)
4630 .TripleDesEncryptionKey(168)
4631 .EcbMode()
4632 .Padding(PaddingMode::PKCS7),
4633 KeyFormat::RAW, key));
4634
4635 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4636 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4637 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4638 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4639 CheckOrigin();
4640
4641 string message = "Hello World!";
4642 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4643 string ciphertext = EncryptMessage(message, params);
4644 string plaintext = DecryptMessage(ciphertext, params);
4645 EXPECT_EQ(message, plaintext);
4646}
4647
4648/*
4649 * ImportKeyTest.TripleDesFailure
4650 *
4651 * Verifies that importing an invalid 3DES key fails.
4652 */
4653TEST_P(ImportKeyTest, TripleDesFailure) {
4654 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004655 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004656 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004657 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004658 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004659 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004660 .Authorization(TAG_NO_AUTH_REQUIRED)
4661 .TripleDesEncryptionKey(key_size)
4662 .EcbMode()
4663 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004664 KeyFormat::RAW, key);
4665 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004666 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4667 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004668 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004669 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004670 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004671 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4672 ImportKey(AuthorizationSetBuilder()
4673 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004674 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004675 .EcbMode()
4676 .Padding(PaddingMode::PKCS7),
4677 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004678 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004679 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4680 ImportKey(AuthorizationSetBuilder()
4681 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004682 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004683 .EcbMode()
4684 .Padding(PaddingMode::PKCS7),
4685 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004686}
4687
4688/*
4689 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004690 *
4691 * Verifies that importing and using an HMAC key works.
4692 */
4693TEST_P(ImportKeyTest, HmacKeySuccess) {
4694 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4695 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4696 .Authorization(TAG_NO_AUTH_REQUIRED)
4697 .HmacKey(key.size() * 8)
4698 .Digest(Digest::SHA_2_256)
4699 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4700 KeyFormat::RAW, key));
4701
4702 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4703 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4704 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4705 CheckOrigin();
4706
4707 string message = "Hello World!";
4708 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4709 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4710}
4711
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004712/*
4713 * ImportKeyTest.GetKeyCharacteristics
4714 *
4715 * Verifies that imported keys have the correct characteristics.
4716 */
4717TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4718 vector<uint8_t> key_blob;
4719 vector<KeyCharacteristics> key_characteristics;
4720 auto base_builder = AuthorizationSetBuilder()
4721 .Padding(PaddingMode::NONE)
4722 .Authorization(TAG_NO_AUTH_REQUIRED)
4723 .SetDefaultValidity();
4724 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4725 Algorithm::TRIPLE_DES};
4726 ErrorCode result;
4727 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4728 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4729 for (auto alg : algorithms) {
4730 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4731 AuthorizationSetBuilder builder(base_builder);
4732 switch (alg) {
4733 case Algorithm::RSA:
4734 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4735
4736 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4737 &key_characteristics);
4738 break;
4739 case Algorithm::EC:
4740 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4741 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4742 &key_characteristics);
4743 break;
4744 case Algorithm::HMAC:
4745 builder.HmacKey(128)
4746 .Digest(Digest::SHA_2_256)
4747 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4748 result =
4749 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4750 break;
4751 case Algorithm::AES:
4752 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4753 result =
4754 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4755 break;
4756 case Algorithm::TRIPLE_DES:
4757 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4758 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4759 &key_characteristics);
4760 break;
4761 default:
4762 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4763 continue;
4764 }
4765 ASSERT_EQ(ErrorCode::OK, result);
4766 CheckCharacteristics(key_blob, key_characteristics);
4767 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4768 }
4769}
4770
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004771/*
4772 * ImportKeyTest.RsaOaepMGFDigestSuccess
4773 *
4774 * Include MGF-Digest explicitly in import key authorization list.
4775 * Test should import RSA key with OAEP padding and mgf-digests and verify that imported key
4776 * should have the correct characteristics.
4777 */
4778TEST_P(ImportKeyTest, RsaOaepMGFDigestSuccess) {
Prashant Patil2114dca2023-09-21 14:57:10 +00004779 // There was no test to assert that MGF1 digest was present in generated/imported key
4780 // characteristics before Keymint V3, so there are some Keymint implementations where
4781 // this test case fails(b/297306437), hence this test is skipped for Keymint < 3.
4782 if (AidlVersion() < 3) {
4783 GTEST_SKIP() << "Test not applicable to Keymint < V3";
4784 }
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004785 auto mgf_digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4786 size_t key_size = 2048;
4787
4788 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4789 .OaepMGFDigest(mgf_digests)
4790 .Authorization(TAG_NO_AUTH_REQUIRED)
4791 .RsaEncryptionKey(key_size, 65537)
4792 .Digest(Digest::SHA_2_256)
4793 .Padding(PaddingMode::RSA_OAEP)
4794 .SetDefaultValidity(),
4795 KeyFormat::PKCS8, rsa_2048_key));
4796
4797 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4798 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4799 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4800 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4801 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4802 CheckOrigin();
4803
4804 // Make sure explicitly specified mgf-digests exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00004805 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digests, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004806
4807 string message = "Hello";
4808
4809 for (auto digest : mgf_digests) {
4810 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4811 auto params = AuthorizationSetBuilder()
4812 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4813 .Digest(Digest::SHA_2_256)
4814 .Padding(PaddingMode::RSA_OAEP);
4815 string ciphertext1 = LocalRsaEncryptMessage(message, params);
4816 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4817 EXPECT_EQ(key_size / 8, ciphertext1.size());
4818
4819 string ciphertext2 = LocalRsaEncryptMessage(message, params);
4820 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4821 EXPECT_EQ(key_size / 8, ciphertext2.size());
4822
4823 // OAEP randomizes padding so every result should be different (with astronomically high
4824 // probability).
4825 EXPECT_NE(ciphertext1, ciphertext2);
4826
4827 string plaintext1 = DecryptMessage(ciphertext1, params);
4828 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4829 string plaintext2 = DecryptMessage(ciphertext2, params);
4830 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4831
4832 // Decrypting corrupted ciphertext should fail.
4833 size_t offset_to_corrupt = ciphertext1.size() - 1;
4834 char corrupt_byte = ~ciphertext1[offset_to_corrupt];
4835 ciphertext1[offset_to_corrupt] = corrupt_byte;
4836
4837 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4838 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04004839 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004840 EXPECT_EQ(0U, result.size());
4841 }
4842}
4843
4844/*
4845 * ImportKeyTest.RsaOaepMGFDigestDefaultSuccess
4846 *
4847 * Don't specify MGF-Digest explicitly in import key authorization list.
4848 * Test should import RSA key with OAEP padding and default mgf-digest (SHA1) and
4849 * verify that imported key should have the correct characteristics. Default
4850 * mgf-digest shouldn't be included in key charecteristics.
4851 */
4852TEST_P(ImportKeyTest, RsaOaepMGFDigestDefaultSuccess) {
4853 size_t key_size = 2048;
4854 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4855 .Authorization(TAG_NO_AUTH_REQUIRED)
4856 .RsaEncryptionKey(key_size, 65537)
4857 .Digest(Digest::SHA_2_256)
4858 .Padding(PaddingMode::RSA_OAEP)
4859 .SetDefaultValidity(),
4860 KeyFormat::PKCS8, rsa_2048_key));
4861
4862 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4863 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4864 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4865 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4866 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4867 CheckOrigin();
4868
Prashant Patil2114dca2023-09-21 14:57:10 +00004869 vector defaultDigest = {Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004870 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00004871 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004872}
4873
Selene Huang31ab4042020-04-29 04:22:39 -07004874INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4875
4876auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004877 // IKeyMintDevice.aidl
4878 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4879 "020100" // INTEGER length 1 value 0x00 (version)
4880 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4881 "934bf94e2aa28a3f83c9f79297250262"
4882 "fbe3276b5a1c91159bbfa3ef8957aac8"
4883 "4b59b30b455a79c2973480823d8b3863"
4884 "c3deef4a8e243590268d80e18751a0e1"
4885 "30f67ce6a1ace9f79b95e097474febc9"
4886 "81195b1d13a69086c0863f66a7b7fdb4"
4887 "8792227b1ac5e2489febdf087ab54864"
4888 "83033a6f001ca5d1ec1e27f5c30f4cec"
4889 "2642074a39ae68aee552e196627a8e3d"
4890 "867e67a8c01b11e75f13cca0a97ab668"
4891 "b50cda07a8ecb7cd8e3dd7009c963653"
4892 "4f6f239cffe1fc8daa466f78b676c711"
4893 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4894 "99b801597d5220e307eaa5bee507fb94"
4895 "d1fa69f9e519b2de315bac92c36f2ea1"
4896 "fa1df4478c0ddedeae8c70e0233cd098"
4897 "040c" // OCTET STRING length 0x0c (initializationVector)
4898 "d796b02c370f1fa4cc0124f1"
4899 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4900 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4901 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4902 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4903 "3106" // SET length 0x06
4904 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4905 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4906 // } end SET
4907 // } end [1]
4908 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4909 "020120" // INTEGER length 1 value 0x20 (AES)
4910 // } end [2]
4911 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4912 "02020100" // INTEGER length 2 value 0x100
4913 // } end [3]
4914 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4915 "3103" // SET length 0x03 {
4916 "020101" // INTEGER length 1 value 0x01 (ECB)
4917 // } end SET
4918 // } end [4]
4919 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4920 "3103" // SET length 0x03 {
4921 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4922 // } end SET
4923 // } end [5]
4924 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4925 // (noAuthRequired)
4926 "0500" // NULL
4927 // } end [503]
4928 // } end SEQUENCE (AuthorizationList)
4929 // } end SEQUENCE (KeyDescription)
4930 "0420" // OCTET STRING length 0x20 (encryptedKey)
4931 "ccd540855f833a5e1480bfd2d36faf3a"
4932 "eee15df5beabe2691bc82dde2a7aa910"
4933 "0410" // OCTET STRING length 0x10 (tag)
4934 "64c9f689c60ff6223ab6e6999e0eb6e5"
4935 // } SEQUENCE (SecureKeyWrapper)
4936);
Selene Huang31ab4042020-04-29 04:22:39 -07004937
4938auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004939 // IKeyMintDevice.aidl
4940 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4941 "020100" // INTEGER length 1 value 0x00 (version)
4942 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4943 "aad93ed5924f283b4bb5526fbe7a1412"
4944 "f9d9749ec30db9062b29e574a8546f33"
4945 "c88732452f5b8e6a391ee76c39ed1712"
4946 "c61d8df6213dec1cffbc17a8c6d04c7b"
4947 "30893d8daa9b2015213e219468215532"
4948 "07f8f9931c4caba23ed3bee28b36947e"
4949 "47f10e0a5c3dc51c988a628daad3e5e1"
4950 "f4005e79c2d5a96c284b4b8d7e4948f3"
4951 "31e5b85dd5a236f85579f3ea1d1b8484"
4952 "87470bdb0ab4f81a12bee42c99fe0df4"
4953 "bee3759453e69ad1d68a809ce06b949f"
4954 "7694a990429b2fe81e066ff43e56a216"
4955 "02db70757922a4bcc23ab89f1e35da77"
4956 "586775f423e519c2ea394caf48a28d0c"
4957 "8020f1dcf6b3a68ec246f615ae96dae9"
4958 "a079b1f6eb959033c1af5c125fd94168"
4959 "040c" // OCTET STRING length 0x0c (initializationVector)
4960 "6d9721d08589581ab49204a3"
4961 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4962 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4963 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4964 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4965 "3106" // SET length 0x06
4966 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4967 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4968 // } end SET
4969 // } end [1]
4970 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4971 "020120" // INTEGER length 1 value 0x20 (AES)
4972 // } end [2]
4973 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4974 "02020100" // INTEGER length 2 value 0x100
4975 // } end [3]
4976 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4977 "3103" // SET length 0x03 {
4978 "020101" // INTEGER length 1 value 0x01 (ECB)
4979 // } end SET
4980 // } end [4]
4981 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4982 "3103" // SET length 0x03 {
4983 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4984 // } end SET
4985 // } end [5]
4986 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4987 // (noAuthRequired)
4988 "0500" // NULL
4989 // } end [503]
4990 // } end SEQUENCE (AuthorizationList)
4991 // } end SEQUENCE (KeyDescription)
4992 "0420" // OCTET STRING length 0x20 (encryptedKey)
4993 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4994 "c20d1f99a9a024a76f35c8e2cab9b68d"
4995 "0410" // OCTET STRING length 0x10 (tag)
4996 "2560c70109ae67c030f00b98b512a670"
4997 // } SEQUENCE (SecureKeyWrapper)
4998);
Selene Huang31ab4042020-04-29 04:22:39 -07004999
5000auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01005001 // RFC 5208 s5
5002 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
5003 "020100" // INTEGER length 1 value 0x00 (version)
5004 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
5005 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
5006 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
5007 "0500" // NULL (parameters)
5008 // } SEQUENCE (AlgorithmIdentifier)
5009 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
5010 // RFC 8017 A.1.2
5011 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
5012 "020100" // INTEGER length 1 value 0x00 (version)
5013 "02820101" // INTEGER length 0x0101 (modulus) value...
5014 "00aec367931d8900ce56b0067f7d70e1" // 0x10
5015 "fc653f3f34d194c1fed50018fb43db93" // 0x20
5016 "7b06e673a837313d56b1c725150a3fef" // 0x30
5017 "86acbddc41bb759c2854eae32d35841e" // 0x40
5018 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
5019 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
5020 "312d7bd5921ffaea1347c157406fef71" // 0x70
5021 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
5022 "f4645c11f5c1374c3886427411c44979" // 0x90
5023 "6792e0bef75dec858a2123c36753e02a" // 0xa0
5024 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
5025 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
5026 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
5027 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
5028 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
5029 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
5030 "55" // 0x101
5031 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
5032 "02820100" // INTEGER length 0x100 (privateExponent) value...
5033 "431447b6251908112b1ee76f99f3711a" // 0x10
5034 "52b6630960046c2de70de188d833f8b8" // 0x20
5035 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
5036 "641f7fe24f14c67a88959bdb27766df9" // 0x40
5037 "e710b630a03adc683b5d2c43080e52be" // 0x50
5038 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
5039 "822bccff087d63c940ba8a45f670feb2" // 0x70
5040 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
5041 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
5042 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
5043 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
5044 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
5045 "52659d5a5ba05b663737a8696281865b" // 0xd0
5046 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
5047 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
5048 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
5049 "028181" // INTEGER length 0x81 (prime1) value...
5050 "00de392e18d682c829266cc3454e1d61" // 0x10
5051 "66242f32d9a1d10577753e904ea7d08b" // 0x20
5052 "ff841be5bac82a164c5970007047b8c5" // 0x30
5053 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
5054 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
5055 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
5056 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
5057 "9e91346130748a6e3c124f9149d71c74" // 0x80
5058 "35"
5059 "028181" // INTEGER length 0x81 (prime2) value...
5060 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
5061 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
5062 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
5063 "7349db6c4a95affdae0dae612e1afac9" // 0x40
5064 "9ed39a2d934c880440aed8832f984316" // 0x50
5065 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
5066 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
5067 "b880677c068e1be936e81288815252a8" // 0x80
5068 "a1"
5069 "028180" // INTEGER length 0x80 (exponent1) value...
5070 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
5071 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
5072 "5a063212a4f105a3764743e53281988a" // 0x30
5073 "ba073f6e0027298e1c4378556e0efca0" // 0x40
5074 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
5075 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
5076 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
5077 "4719d6e2b9439823719cd08bcd031781" // 0x80
5078 "028181" // INTEGER length 0x81 (exponent2) value...
5079 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
5080 "1241acc607976c4ddccc90e65b6556ca" // 0x20
5081 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
5082 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
5083 "1254186af30b22c10582a8a43e34fe94" // 0x50
5084 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
5085 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
5086 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
5087 "61"
5088 "028181" // INTEGER length 0x81 (coefficient) value...
5089 "00c931617c77829dfb1270502be9195c" // 0x10
5090 "8f2830885f57dba869536811e6864236" // 0x20
5091 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
5092 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
5093 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
5094 "959356210723287b0affcc9f727044d4" // 0x60
5095 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
5096 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
5097 "22"
5098 // } SEQUENCE
5099 // } SEQUENCE ()
5100);
Selene Huang31ab4042020-04-29 04:22:39 -07005101
5102string zero_masking_key =
5103 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
5104string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
5105
5106class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
5107
5108TEST_P(ImportWrappedKeyTest, Success) {
5109 auto wrapping_key_desc = AuthorizationSetBuilder()
5110 .RsaEncryptionKey(2048, 65537)
5111 .Digest(Digest::SHA_2_256)
5112 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005113 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5114 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005115
5116 ASSERT_EQ(ErrorCode::OK,
5117 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5118 AuthorizationSetBuilder()
5119 .Digest(Digest::SHA_2_256)
5120 .Padding(PaddingMode::RSA_OAEP)));
5121
5122 string message = "Hello World!";
5123 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5124 string ciphertext = EncryptMessage(message, params);
5125 string plaintext = DecryptMessage(ciphertext, params);
5126 EXPECT_EQ(message, plaintext);
5127}
5128
David Drysdaled2cc8c22021-04-15 13:29:45 +01005129/*
5130 * ImportWrappedKeyTest.SuccessSidsIgnored
5131 *
5132 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
5133 * include Tag:USER_SECURE_ID.
5134 */
5135TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
5136 auto wrapping_key_desc = AuthorizationSetBuilder()
5137 .RsaEncryptionKey(2048, 65537)
5138 .Digest(Digest::SHA_2_256)
5139 .Padding(PaddingMode::RSA_OAEP)
5140 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5141 .SetDefaultValidity();
5142
5143 int64_t password_sid = 42;
5144 int64_t biometric_sid = 24;
5145 ASSERT_EQ(ErrorCode::OK,
5146 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5147 AuthorizationSetBuilder()
5148 .Digest(Digest::SHA_2_256)
5149 .Padding(PaddingMode::RSA_OAEP),
5150 password_sid, biometric_sid));
5151
5152 string message = "Hello World!";
5153 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5154 string ciphertext = EncryptMessage(message, params);
5155 string plaintext = DecryptMessage(ciphertext, params);
5156 EXPECT_EQ(message, plaintext);
5157}
5158
Selene Huang31ab4042020-04-29 04:22:39 -07005159TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5160 auto wrapping_key_desc = AuthorizationSetBuilder()
5161 .RsaEncryptionKey(2048, 65537)
5162 .Digest(Digest::SHA_2_256)
5163 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005164 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5165 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005166
5167 ASSERT_EQ(ErrorCode::OK,
5168 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5169 AuthorizationSetBuilder()
5170 .Digest(Digest::SHA_2_256)
5171 .Padding(PaddingMode::RSA_OAEP)));
5172}
5173
5174TEST_P(ImportWrappedKeyTest, WrongMask) {
5175 auto wrapping_key_desc = AuthorizationSetBuilder()
5176 .RsaEncryptionKey(2048, 65537)
5177 .Digest(Digest::SHA_2_256)
5178 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005179 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5180 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005181
5182 ASSERT_EQ(
5183 ErrorCode::VERIFICATION_FAILED,
5184 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5185 AuthorizationSetBuilder()
5186 .Digest(Digest::SHA_2_256)
5187 .Padding(PaddingMode::RSA_OAEP)));
5188}
5189
5190TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5191 auto wrapping_key_desc = AuthorizationSetBuilder()
5192 .RsaEncryptionKey(2048, 65537)
5193 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005194 .Padding(PaddingMode::RSA_OAEP)
5195 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005196
5197 ASSERT_EQ(
5198 ErrorCode::INCOMPATIBLE_PURPOSE,
5199 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5200 AuthorizationSetBuilder()
5201 .Digest(Digest::SHA_2_256)
5202 .Padding(PaddingMode::RSA_OAEP)));
5203}
5204
David Drysdaled2cc8c22021-04-15 13:29:45 +01005205TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5206 auto wrapping_key_desc = AuthorizationSetBuilder()
5207 .RsaEncryptionKey(2048, 65537)
5208 .Digest(Digest::SHA_2_256)
5209 .Padding(PaddingMode::RSA_PSS)
5210 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5211 .SetDefaultValidity();
5212
5213 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5214 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5215 AuthorizationSetBuilder()
5216 .Digest(Digest::SHA_2_256)
5217 .Padding(PaddingMode::RSA_OAEP)));
5218}
5219
5220TEST_P(ImportWrappedKeyTest, WrongDigest) {
5221 auto wrapping_key_desc = AuthorizationSetBuilder()
5222 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005223 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005224 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005225 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5226 .SetDefaultValidity();
5227
5228 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5229 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5230 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005231 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005232 .Padding(PaddingMode::RSA_OAEP)));
5233}
5234
Tri Vob02ff882023-09-29 14:49:20 -04005235auto wrapped_rsa_key = hex2str(
5236 "308206230201000482010060f81b63ae53aa4be2e91b0b7cbdabd108125836139e5b991f3e3c9a98eca6cb7188"
5237 "fba1c1232605747ed118975870c886e583a0ff766fc32b789a17029955caaff39a9c6c439be168e24b51046683"
5238 "ce16110e0df115ccabbadcbe7ea9118b9589e4cccf240b6f0a506dfee57e19738c3cabb7dbf63b43e1b9ab058b"
5239 "41b9480f2797210ef2bfbecb82526ac60ac006ebe0a053e825ad996d0ce8a98dc1ebf6ad889e491e03e9ddcc05"
5240 "63f31921b55a54c61aa7f846d814dfe548f2c7939940bc6cf20489733203732df924b2b2a5aa9b54d31e7e42b9"
5241 "e6cf107182edd33cb8e41db88167a79a264bbf883e69300ac82aac8de9dca0a13900150111efead81b74040c78"
5242 "01d20b1547cfef40de45da30350201013030a1083106020102020103a203020101a30402020800a40531030201"
5243 "01a5053103020104a6053103020103bf8377020500048204c126cd1642e83dea941151d872de12b8aaa835446e"
5244 "94d2c1ea99c030225c5cad125dabe2341d9aba63e4df7fefc51e8e6f623ffae2aab9927113562b674b3cc2d7fc"
5245 "fc34f199151a56ab114e792e6a21bd3b31fbf0d93050b9f90fb8e6cad3a067a4033848c4380184990f19a141d9"
5246 "527177fdc13d802c33d222206c36404518285fe7e631aaeb6072c22c351c8c9db06e0b24e11aecef305f6abefb"
5247 "4f31111534f7c55da8cf0d33882edbb43765304d1d45545c5207a858ea8d4369393bf1c54624df03da86c0ed47"
5248 "b9ce1297149622069d51d2512f656ad0d421e6ff746ce8f79920df6a204c31732414a2f7eb24f8c2950348187a"
5249 "4ba20b88a72355a4ec2b383be9f9b5b9ad564aa4c81de47dd95d77a8156ed0901d005a26f523b2a82c2d25d64d"
5250 "f7660a6d3a720a6ba1eafe71da9fed0265d37a475193525620e705a543a928827accad93aba90556da859808be"
5251 "dc2a8105af252e883892f41679d0600ddefb84415145bc28a2d9b0c60cea1ed3876486950ae0532cc1e953b0b5"
5252 "81314c74250550741b24e4221ebb2804428caa2f08356a7de853ccfc5b18c2179147a883fa5763dd54f0d45388"
5253 "c72f1bea19675d14014a725e125cdfac98d1701d9562be9d75362ea238b93244f46306cee4d77cbb8cbe7bf22d"
5254 "fe677bbb103c00a204e49a0731660a2b23ee73ec7297a17822d4c4468e271029f8f1e8995f1a37cdc38324ead3"
5255 "2474e6ee3ff671803d8a98a870324364d408c4d966d3cf0b9bbcbdbdff34a3e9666705362bc78beb96df4b8964"
5256 "d141022250f62d1433cba5d1f510859eff688e46ce65dea00f5ebcfe7a79081ef1f0f5584dba14b79bc5a5f309"
5257 "a1e48fe2bd9e94fcd9793d9b3632ccc51f18f7453e897e33b729abd2d34be324acbc22dfbf1d089aa93a178f79"
5258 "23344140a468ac120b2f0055c284576b968e1d5148c6879b207b6cdb4eb513bccca619ae12ef156a9df03d6d8c"
5259 "2c1c2ea7109dbcb61e5a74b36d0a7529f38b9ea742a956376da823251a6126693e2e1dab55b643c4e9783db835"
5260 "f64d91069a2de1cda55539da52cadeeba2d3278da9005d89b4de4c5571600823f53d9cab1b55f65a560479d9ee"
5261 "edeb361ab80ccedd0a067ddf5de639d115ffb3acf07fbba1cba6daa524b99db0b785273f7b6c15c4237ce1dce8"
5262 "1b81622f35f116b638c75f0e0b26ba6bd9c5caee60c8b4f9198052b25e8c101638598946cb02c14db0a21b46c6"
5263 "61ea123b2a2b5a51eb059715ce26940c977715a32e288b713013d66d0dae398d546abcd8c80966190b77732a7c"
5264 "e2b8fc83e0cd83f69adef2b24b69fba19c546362087c08c8dab941a8573a084be3407d45a318c9a299f69d79f6"
5265 "fae0859d6f08ee7708cf6041cccd815c3515f792aefc23a624e8e58bd9c6fe2f8f1ca6dcf04c6fdfa23eb3ff74"
5266 "c5e5c7388f9faa32c86b6cd7438774e6cf06cb23a32cddb04c30f7d11e221db306c7937796e70a4dcfb7415c04"
5267 "7823b965bedeaea196dc30fe648c52f3c1bcee62b19d4cccdb740ca35c3f3daad998c99dc117fffb7d150d500f"
5268 "812b60ebec8b2067b13938250d078768e77f898fcdfc5f3554b6eda9df3b42bef38bb4d67cb63b7ede01e93b4d"
5269 "c7768b52aa8ad8fb7fb288a529b84671f1ff9e44bb7c8f05d99806b65eb8e90b530fef3817f9fc4c921d0d46af"
5270 "11aee8252407adc6c54589e9f6e6c1e25fc7510cfe499ea20465610410bf575efdbeb5af763920c3b4cdc8401"
5271 "2");
5272
5273auto wrapped_ec_key = hex2str(
5274 "308201dd020100048201000bb910602f88b1419ada400c8ab7602cf2fdbb4ef5e36881255fd5f85d49c4110c52"
5275 "c75eab5e27a1732c1afa17bfe2cd393dea0a78a77ee08759e984411d1c7f0dbdcb6b77e05556694534be4434d8"
5276 "596a7152aec71481522c85f0cc4635df2875d58dc29a78317b2aedd3586055e6e2227616f6a8ac4b9db5a2ad0e"
5277 "10f5c4b43374bd6c9f57f79a103e64084414cfab3d3e0b7c2f26eb00a62105b7d1c7f41b7292fd6fce9395f39c"
5278 "e0b6da0b5bf0d29d8952b958bd29b47c5ebd20d53ade370f463e35a166c04af71e3d5ce550019d3d20a5544896"
5279 "65d169875d0e6a52348b7ec39b674f818e9b60dfa284d7ae4188471d05b9b2d9a5f750f5a00af999c568040c31"
5280 "4144bde8ada6279d32e61530270201013022a1083106020102020103a203020103a30402020100a50531030201"
5281 "04bf837702050004818a96e0f8be5a263616b506371d3c2ff3a3c2bcffc3ce067b242af66e30d5cd975b9546eb"
5282 "32216d4f083f08fde246ab05fd7e930a0f05701067b44840c01a6722e1b2408be5b6acd0b39a0329cb2f357515"
5283 "876433b193382c0b18aed9ed244dcbef5d61d98ca480f99a6cf2a00efda22eb8750db1725e30f64770ac6862ac"
5284 "44cfd08a2c55812b512a0b92f704105c80b6a23cf339b2b10c677613510b1b");
5285
5286auto wrapping_key_for_asym_keys = hex2str(
5287 "308204bd020100300d06092a864886f70d0101010500048204a7308204a30201000282010100a7f521fe024ebc"
5288 "659db8e7a32b41dba27c5d446cb3d064d594b811d4856c3a583d155b0ff9300df3745738c32c4c4cd15adb6090"
5289 "72ca870364bb7f3485784fde12e598b486c91950b9c45016bcb73c3842747c871be02dfc5f0e4b96d1ff5c8a09"
5290 "7ae77b27e46dc60f1f574d1bb5e97487c1c3f9b493509e07318e1a0f0e9fdae401f4a62a5dd54daa09bf88ef42"
5291 "9923f6f6f55d239908f227676d0f0b618238728dc4babd2a1f7d15fa9827346a1a160ab9427461533006fdf34d"
5292 "4efec9aeefcea80b3a7d4ee4a4550055f0030700c5d20abcc32ce74d90ffabf83e02a759ce9074809936564f3d"
5293 "3039af9c5e8a6afd9aa5459ab35c3eb851f10b3ae88ba91f0203010001028201001885515124451a7c3b6aa366"
5294 "cf09ee66ea81335c2b6461544d42125854a258624988b4a2c05ea3aac77174780a1f9997770c502cc6958ae093"
5295 "f44bbdff3e716a9a97aa93b099eb783da6cb8a8642ba27fc8bc522748f66275239640fc0d8e749bfd891b3093f"
5296 "f046da2e593088bb263a3d17ace4e7d81a0cf83fe3df2a139882bff509523a3f886922200168ddd8fb7b4c9f26"
5297 "62ff941c37937cebbbfeba24dd78d5ccd42025cb0276fa5661965f529274520bbb9faf36c501cafb48e5e47ae0"
5298 "6980334fa36b6c62e2da733a8c7f01067de17e38d32d4a0721a6d184405bceaebb39ed3838633e6fbe43ac8b23"
5299 "337bfe33cdf0b67ac3938ddccc37d775ad150102818100d538885135037730fad28e987d7562c1ef8ca58f95f7"
5300 "ed81cb165ca63e15e810552eb9d487c9b9cde563fb29d1de22a60d54a856385719a4028cf386bcdc88e858d963"
5301 "6d644cea25e0ee54ad1237983d9a06a66ea2f764eb540a4992ba2291ea96d20dfbd98bf5b313322cda4eb6710d"
5302 "020139e085beb8e52a3e69bd05c71c7b02818100c9a7c89b11fcf8d99eb41995b5641472ef972e5aaa1f1446d7"
5303 "ea57a9979e8e64f72ef1cde358649b71be7f21dc19dab52814f9a521d8620bd994a9bb621a8182a250066a0728"
5304 "f0b16ab93a106ed79bc19cd519e83196157a8c6f82b5144a285b9384415394905fe18863b0988b27e77c969a81"
5305 "c34a074e8fef5908fdf3c51ead02818019d5e8c6963ade45640f01523ed96b66fe64b766e7900c0a4f165d9193"
5306 "324a55384d1a1d437ad0f5bed6d78720b3ded4ea069903217e844fd833460acc75986d36ded86a57ddedfd3afd"
5307 "05eb96aa7fdaeeffe148c49c5f711854cac769a068b7d92088ab3c97f5e485eded7b62503ef0898ea679ab1b0a"
5308 "0252950f70e4f35463028181008ff4c027bb8aad17a5cd0a2aaea83854e8a73347340525d38115e0e8c7bd4007"
5309 "e1d1d87ad35e69cbf2423cbdae43a2b70a5b16f0849dd53882663758f6aad763ab7d97669f9fe15bb6456ea706"
5310 "89d2be3fb87d5b1df2f77859c2cd3b79b58ae3fd0640206b813981667d4c3749b7fdf01a0f48ad622e9f2def7e"
5311 "cf0583bd67ad0281805bd8f20cc82cb5e08dc2e7eea977d4180a5ef4c558e01255b8475feb9084475e20328c93"
5312 "5a2247a775c941d64372d01abb27c95ee7d4336b6cbce190808b2f7a8d314d785336397dd6edc0c778f563d37e"
5313 "0057b13695600b92fececc3edb067f69b374f9b9c343220a8b927deb6104768edc72b87751e0a3fb1585e679c9"
5314 "8564");
5315
5316TEST_P(ImportWrappedKeyTest, RsaKey) {
5317 int vsr_api_level = get_vsr_api_level();
5318 if (vsr_api_level < __ANDROID_API_V__) {
5319 /*
5320 * The Keymaster v4 spec introduced `importWrappedKey()` and did not restrict it to
5321 * just symmetric keys. However, the import of asymmetric wrapped keys was not tested
5322 * at the time, so we can only be strict about checking this for implementations claiming
5323 * support for VSR API level 35 and above.
5324 */
5325 GTEST_SKIP() << "Applies only to VSR API level 35, this device is: " << vsr_api_level;
5326 }
5327
5328 auto wrapping_key_desc = AuthorizationSetBuilder()
5329 .RsaEncryptionKey(2048, 65537)
5330 .Digest(Digest::SHA_2_256)
5331 .Padding(PaddingMode::RSA_OAEP)
5332 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5333 .SetDefaultValidity();
5334
5335 ASSERT_EQ(ErrorCode::OK, ImportWrappedKey(wrapped_rsa_key, wrapping_key_for_asym_keys,
5336 wrapping_key_desc, zero_masking_key,
5337 AuthorizationSetBuilder()
5338 .Digest(Digest::SHA_2_256)
5339 .Padding(PaddingMode::RSA_OAEP)));
5340
5341 string message = "Hello World!";
5342 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
5343 string signature = SignMessage(message, params);
5344 LocalVerifyMessage(message, signature, params);
5345}
5346
5347TEST_P(ImportWrappedKeyTest, EcKey) {
5348 int vsr_api_level = get_vsr_api_level();
5349 if (vsr_api_level < __ANDROID_API_V__) {
5350 /*
5351 * The Keymaster v4 spec introduced `importWrappedKey()` and did not restrict it to
5352 * just symmetric keys. However, the import of asymmetric wrapped keys was not tested
5353 * at the time, so we can only be strict about checking this for implementations claiming
5354 * support for VSR API level 35 and above.
5355 */
5356 GTEST_SKIP() << "Applies only to VSR API level 35, this device is: " << vsr_api_level;
5357 }
5358
5359 auto wrapping_key_desc = AuthorizationSetBuilder()
5360 .RsaEncryptionKey(2048, 65537)
5361 .Digest(Digest::SHA_2_256)
5362 .Padding(PaddingMode::RSA_OAEP)
5363 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5364 .SetDefaultValidity();
5365
5366 ASSERT_EQ(ErrorCode::OK, ImportWrappedKey(wrapped_ec_key, wrapping_key_for_asym_keys,
5367 wrapping_key_desc, zero_masking_key,
5368 AuthorizationSetBuilder()
5369 .Digest(Digest::SHA_2_256)
5370 .Padding(PaddingMode::RSA_OAEP)));
5371
5372 string message = "Hello World!";
5373 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
5374 string signature = SignMessage(message, params);
5375 LocalVerifyMessage(message, signature, params);
5376}
5377
Selene Huang31ab4042020-04-29 04:22:39 -07005378INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5379
5380typedef KeyMintAidlTestBase EncryptionOperationsTest;
5381
5382/*
5383 * EncryptionOperationsTest.RsaNoPaddingSuccess
5384 *
David Drysdale59cae642021-05-12 13:52:03 +01005385 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005386 */
5387TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005388 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005389 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005390 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5391 .Authorization(TAG_NO_AUTH_REQUIRED)
5392 .RsaEncryptionKey(2048, exponent)
5393 .Padding(PaddingMode::NONE)
5394 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005395
David Drysdaled2cc8c22021-04-15 13:29:45 +01005396 string message = string(2048 / 8, 'a');
5397 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005398 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005399 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005400
David Drysdale59cae642021-05-12 13:52:03 +01005401 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005402 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005403
David Drysdaled2cc8c22021-04-15 13:29:45 +01005404 // Unpadded RSA is deterministic
5405 EXPECT_EQ(ciphertext1, ciphertext2);
5406
5407 CheckedDeleteKey();
5408 }
Selene Huang31ab4042020-04-29 04:22:39 -07005409}
5410
5411/*
5412 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5413 *
David Drysdale59cae642021-05-12 13:52:03 +01005414 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005415 */
5416TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5417 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5418 .Authorization(TAG_NO_AUTH_REQUIRED)
5419 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005420 .Padding(PaddingMode::NONE)
5421 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005422
5423 string message = "1";
5424 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5425
David Drysdale59cae642021-05-12 13:52:03 +01005426 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005427 EXPECT_EQ(2048U / 8, ciphertext.size());
5428
5429 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5430 string plaintext = DecryptMessage(ciphertext, params);
5431
5432 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005433}
5434
5435/*
Selene Huang31ab4042020-04-29 04:22:39 -07005436 * EncryptionOperationsTest.RsaOaepSuccess
5437 *
David Drysdale59cae642021-05-12 13:52:03 +01005438 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005439 */
5440TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5441 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
Prashant Patil2114dca2023-09-21 14:57:10 +00005442 auto mgf_digest = vector{Digest::SHA1};
Selene Huang31ab4042020-04-29 04:22:39 -07005443
5444 size_t key_size = 2048; // Need largish key for SHA-512 test.
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005445 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5446 .Authorization(TAG_NO_AUTH_REQUIRED)
5447 .RsaEncryptionKey(key_size, 65537)
5448 .Padding(PaddingMode::RSA_OAEP)
5449 .Digest(digests)
Prashant Patil2114dca2023-09-21 14:57:10 +00005450 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005451 .SetDefaultValidity()));
5452
5453 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005454 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Selene Huang31ab4042020-04-29 04:22:39 -07005455
5456 string message = "Hello";
5457
5458 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005459 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5460
5461 auto params = AuthorizationSetBuilder()
5462 .Digest(digest)
5463 .Padding(PaddingMode::RSA_OAEP)
5464 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5465 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005466 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5467 EXPECT_EQ(key_size / 8, ciphertext1.size());
5468
David Drysdale59cae642021-05-12 13:52:03 +01005469 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005470 EXPECT_EQ(key_size / 8, ciphertext2.size());
5471
5472 // OAEP randomizes padding so every result should be different (with astronomically high
5473 // probability).
5474 EXPECT_NE(ciphertext1, ciphertext2);
5475
5476 string plaintext1 = DecryptMessage(ciphertext1, params);
5477 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5478 string plaintext2 = DecryptMessage(ciphertext2, params);
5479 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5480
5481 // Decrypting corrupted ciphertext should fail.
5482 size_t offset_to_corrupt = random() % ciphertext1.size();
5483 char corrupt_byte;
5484 do {
5485 corrupt_byte = static_cast<char>(random() % 256);
5486 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5487 ciphertext1[offset_to_corrupt] = corrupt_byte;
5488
5489 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5490 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005491 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005492 EXPECT_EQ(0U, result.size());
5493 }
5494}
5495
5496/*
5497 * EncryptionOperationsTest.RsaOaepInvalidDigest
5498 *
David Drysdale59cae642021-05-12 13:52:03 +01005499 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005500 * without a digest.
5501 */
5502TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5503 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5504 .Authorization(TAG_NO_AUTH_REQUIRED)
5505 .RsaEncryptionKey(2048, 65537)
5506 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005507 .Digest(Digest::NONE)
5508 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005509
5510 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005511 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005512}
5513
5514/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005515 * EncryptionOperationsTest.RsaOaepInvalidPadding
5516 *
David Drysdale59cae642021-05-12 13:52:03 +01005517 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005518 * with a padding value that is only suitable for signing/verifying.
5519 */
5520TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5521 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5522 .Authorization(TAG_NO_AUTH_REQUIRED)
5523 .RsaEncryptionKey(2048, 65537)
5524 .Padding(PaddingMode::RSA_PSS)
5525 .Digest(Digest::NONE)
5526 .SetDefaultValidity()));
5527
5528 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005529 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005530}
5531
5532/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005533 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005534 *
David Drysdale59cae642021-05-12 13:52:03 +01005535 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005536 * with a different digest than was used to encrypt.
5537 */
5538TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005539 if (SecLevel() == SecurityLevel::STRONGBOX) {
5540 GTEST_SKIP() << "Test not applicable to StrongBox device";
5541 }
Selene Huang31ab4042020-04-29 04:22:39 -07005542
5543 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5544 .Authorization(TAG_NO_AUTH_REQUIRED)
5545 .RsaEncryptionKey(1024, 65537)
5546 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005547 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5548 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005549 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005550 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005551 message,
5552 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5553
5554 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5555 .Digest(Digest::SHA_2_256)
5556 .Padding(PaddingMode::RSA_OAEP)));
5557 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005558 EXPECT_NE(ErrorCode::OK, Finish(ciphertext, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005559 EXPECT_EQ(0U, result.size());
5560}
5561
5562/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005563 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5564 *
David Drysdale59cae642021-05-12 13:52:03 +01005565 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005566 * digests.
5567 */
5568TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5569 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5570
5571 size_t key_size = 2048; // Need largish key for SHA-512 test.
5572 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5573 .OaepMGFDigest(digests)
5574 .Authorization(TAG_NO_AUTH_REQUIRED)
5575 .RsaEncryptionKey(key_size, 65537)
5576 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005577 .Digest(Digest::SHA_2_256)
5578 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005579 if (AidlVersion() >= 3) {
5580 std::vector<Digest> mgf1DigestsInAuths;
5581 mgf1DigestsInAuths.reserve(digests.size());
5582 const auto& hw_auths = SecLevelAuthorizations(key_characteristics_);
5583 std::for_each(hw_auths.begin(), hw_auths.end(), [&](auto& param) {
5584 if (param.tag == Tag::RSA_OAEP_MGF_DIGEST) {
5585 KeyParameterValue value = param.value;
5586 mgf1DigestsInAuths.push_back(param.value.template get<KeyParameterValue::digest>());
5587 }
5588 });
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005589
Prashant Patil2114dca2023-09-21 14:57:10 +00005590 std::sort(digests.begin(), digests.end());
5591 std::sort(mgf1DigestsInAuths.begin(), mgf1DigestsInAuths.end());
5592 EXPECT_EQ(digests, mgf1DigestsInAuths);
5593 }
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005594 string message = "Hello";
5595
5596 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005597 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005598 auto params = AuthorizationSetBuilder()
5599 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5600 .Digest(Digest::SHA_2_256)
5601 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005602 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005603 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5604 EXPECT_EQ(key_size / 8, ciphertext1.size());
5605
David Drysdale59cae642021-05-12 13:52:03 +01005606 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005607 EXPECT_EQ(key_size / 8, ciphertext2.size());
5608
5609 // OAEP randomizes padding so every result should be different (with astronomically high
5610 // probability).
5611 EXPECT_NE(ciphertext1, ciphertext2);
5612
5613 string plaintext1 = DecryptMessage(ciphertext1, params);
5614 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5615 string plaintext2 = DecryptMessage(ciphertext2, params);
5616 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5617
5618 // Decrypting corrupted ciphertext should fail.
5619 size_t offset_to_corrupt = random() % ciphertext1.size();
5620 char corrupt_byte;
5621 do {
5622 corrupt_byte = static_cast<char>(random() % 256);
5623 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5624 ciphertext1[offset_to_corrupt] = corrupt_byte;
5625
5626 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5627 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005628 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005629 EXPECT_EQ(0U, result.size());
5630 }
5631}
5632
5633/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005634 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5635 *
5636 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5637 * specified, defaulting to SHA-1.
5638 */
5639TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5640 size_t key_size = 2048;
5641 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5642 .Authorization(TAG_NO_AUTH_REQUIRED)
5643 .RsaEncryptionKey(key_size, 65537)
5644 .Padding(PaddingMode::RSA_OAEP)
5645 .Digest(Digest::SHA_2_256)
5646 .SetDefaultValidity()));
5647
Prashant Patil2114dca2023-09-21 14:57:10 +00005648 vector defaultDigest = vector{Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005649 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005650 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005651
David Drysdaleae3727b2021-11-11 09:00:14 +00005652 // Do local RSA encryption using the default MGF digest of SHA-1.
5653 string message = "Hello";
5654 auto params =
5655 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5656 string ciphertext = LocalRsaEncryptMessage(message, params);
5657 EXPECT_EQ(key_size / 8, ciphertext.size());
5658
5659 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5660 string plaintext = DecryptMessage(ciphertext, params);
5661 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5662
5663 // Decrypting corrupted ciphertext should fail.
5664 size_t offset_to_corrupt = random() % ciphertext.size();
5665 char corrupt_byte;
5666 do {
5667 corrupt_byte = static_cast<char>(random() % 256);
5668 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5669 ciphertext[offset_to_corrupt] = corrupt_byte;
5670
5671 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5672 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005673 EXPECT_NE(ErrorCode::OK, Finish(ciphertext, &result));
David Drysdaleae3727b2021-11-11 09:00:14 +00005674 EXPECT_EQ(0U, result.size());
5675}
5676
5677/*
5678 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5679 *
5680 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5681 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5682 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5683 */
5684TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5685 size_t key_size = 2048;
Prashant Patil2114dca2023-09-21 14:57:10 +00005686 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005687 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5688 .Authorization(TAG_NO_AUTH_REQUIRED)
Prashant Patil2114dca2023-09-21 14:57:10 +00005689 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005690 .RsaEncryptionKey(key_size, 65537)
5691 .Padding(PaddingMode::RSA_OAEP)
5692 .Digest(Digest::SHA_2_256)
5693 .SetDefaultValidity()));
5694
5695 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005696 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
5697 vector defaultDigest = vector{Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005698 // Make sure default mgf-digest is not included in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005699 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
David Drysdaleae3727b2021-11-11 09:00:14 +00005700
5701 // Do local RSA encryption using the default MGF digest of SHA-1.
5702 string message = "Hello";
5703 auto params =
5704 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5705 string ciphertext = LocalRsaEncryptMessage(message, params);
5706 EXPECT_EQ(key_size / 8, ciphertext.size());
5707
5708 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5709 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5710 // is checked against those values, and found absent.
5711 auto result = Begin(KeyPurpose::DECRYPT, params);
5712 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
David Drysdale0269d492024-11-14 16:51:58 +00005713 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST)
5714 << "unexpected result " << result;
David Drysdaleae3727b2021-11-11 09:00:14 +00005715}
5716
5717/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005718 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5719 *
David Drysdale59cae642021-05-12 13:52:03 +01005720 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005721 * with incompatible MGF digest.
5722 */
5723TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
Prashant Patil2114dca2023-09-21 14:57:10 +00005724 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005725 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Prashant Patil2114dca2023-09-21 14:57:10 +00005726 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005727 .Authorization(TAG_NO_AUTH_REQUIRED)
5728 .RsaEncryptionKey(2048, 65537)
5729 .Padding(PaddingMode::RSA_OAEP)
5730 .Digest(Digest::SHA_2_256)
5731 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005732
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005733 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005734 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005735
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005736 string message = "Hello World!";
5737
5738 auto params = AuthorizationSetBuilder()
5739 .Padding(PaddingMode::RSA_OAEP)
5740 .Digest(Digest::SHA_2_256)
5741 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005742 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005743}
5744
5745/*
5746 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5747 *
5748 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5749 * with unsupported MGF digest.
5750 */
5751TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
Prashant Patil2114dca2023-09-21 14:57:10 +00005752 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005753 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Prashant Patil2114dca2023-09-21 14:57:10 +00005754 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005755 .Authorization(TAG_NO_AUTH_REQUIRED)
5756 .RsaEncryptionKey(2048, 65537)
5757 .Padding(PaddingMode::RSA_OAEP)
5758 .Digest(Digest::SHA_2_256)
5759 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005760
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005761 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005762 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005763
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005764 string message = "Hello World!";
5765
5766 auto params = AuthorizationSetBuilder()
5767 .Padding(PaddingMode::RSA_OAEP)
5768 .Digest(Digest::SHA_2_256)
5769 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005770 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005771}
5772
5773/*
Selene Huang31ab4042020-04-29 04:22:39 -07005774 * EncryptionOperationsTest.RsaPkcs1Success
5775 *
5776 * Verifies that RSA PKCS encryption/decrypts works.
5777 */
5778TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5779 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5780 .Authorization(TAG_NO_AUTH_REQUIRED)
5781 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005782 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5783 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005784
5785 string message = "Hello World!";
5786 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005787 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005788 EXPECT_EQ(2048U / 8, ciphertext1.size());
5789
David Drysdale59cae642021-05-12 13:52:03 +01005790 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005791 EXPECT_EQ(2048U / 8, ciphertext2.size());
5792
5793 // PKCS1 v1.5 randomizes padding so every result should be different.
5794 EXPECT_NE(ciphertext1, ciphertext2);
5795
5796 string plaintext = DecryptMessage(ciphertext1, params);
5797 EXPECT_EQ(message, plaintext);
5798
5799 // Decrypting corrupted ciphertext should fail.
5800 size_t offset_to_corrupt = random() % ciphertext1.size();
5801 char corrupt_byte;
5802 do {
5803 corrupt_byte = static_cast<char>(random() % 256);
5804 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5805 ciphertext1[offset_to_corrupt] = corrupt_byte;
5806
5807 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5808 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005809 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005810 EXPECT_EQ(0U, result.size());
5811}
5812
5813/*
Selene Huang31ab4042020-04-29 04:22:39 -07005814 * EncryptionOperationsTest.EcdsaEncrypt
5815 *
5816 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5817 */
5818TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5819 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5820 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005821 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005822 .Digest(Digest::NONE)
5823 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005824 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5825 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5826 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5827}
5828
5829/*
5830 * EncryptionOperationsTest.HmacEncrypt
5831 *
5832 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5833 */
5834TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5835 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5836 .Authorization(TAG_NO_AUTH_REQUIRED)
5837 .HmacKey(128)
5838 .Digest(Digest::SHA_2_256)
5839 .Padding(PaddingMode::NONE)
5840 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5841 auto params = AuthorizationSetBuilder()
5842 .Digest(Digest::SHA_2_256)
5843 .Padding(PaddingMode::NONE)
5844 .Authorization(TAG_MAC_LENGTH, 128);
5845 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5846 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5847}
5848
5849/*
5850 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5851 *
5852 * Verifies that AES ECB mode works.
5853 */
5854TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5855 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5856 .Authorization(TAG_NO_AUTH_REQUIRED)
5857 .AesEncryptionKey(128)
5858 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5859 .Padding(PaddingMode::NONE)));
5860
5861 ASSERT_GT(key_blob_.size(), 0U);
5862 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5863
5864 // Two-block message.
5865 string message = "12345678901234567890123456789012";
5866 string ciphertext1 = EncryptMessage(message, params);
5867 EXPECT_EQ(message.size(), ciphertext1.size());
5868
5869 string ciphertext2 = EncryptMessage(string(message), params);
5870 EXPECT_EQ(message.size(), ciphertext2.size());
5871
5872 // ECB is deterministic.
5873 EXPECT_EQ(ciphertext1, ciphertext2);
5874
5875 string plaintext = DecryptMessage(ciphertext1, params);
5876 EXPECT_EQ(message, plaintext);
5877}
5878
5879/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005880 * EncryptionOperationsTest.AesEcbUnknownTag
5881 *
5882 * Verifies that AES ECB operations ignore unknown tags.
5883 */
5884TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5885 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5886 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5887 KeyParameter unknown_param;
5888 unknown_param.tag = unknown_tag;
5889
5890 vector<KeyCharacteristics> key_characteristics;
5891 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5892 .Authorization(TAG_NO_AUTH_REQUIRED)
5893 .AesEncryptionKey(128)
5894 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5895 .Padding(PaddingMode::NONE)
5896 .Authorization(unknown_param),
5897 &key_blob_, &key_characteristics));
5898 ASSERT_GT(key_blob_.size(), 0U);
5899
5900 // Unknown tags should not be returned in key characteristics.
5901 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5902 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5903 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5904 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5905
5906 // Encrypt without mentioning the unknown parameter.
5907 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5908 string message = "12345678901234567890123456789012";
5909 string ciphertext = EncryptMessage(message, params);
5910 EXPECT_EQ(message.size(), ciphertext.size());
5911
5912 // Decrypt including the unknown parameter.
5913 auto decrypt_params = AuthorizationSetBuilder()
5914 .BlockMode(BlockMode::ECB)
5915 .Padding(PaddingMode::NONE)
5916 .Authorization(unknown_param);
5917 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5918 EXPECT_EQ(message, plaintext);
5919}
5920
5921/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005922 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005923 *
5924 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5925 */
5926TEST_P(EncryptionOperationsTest, AesWrongMode) {
5927 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5928 .Authorization(TAG_NO_AUTH_REQUIRED)
5929 .AesEncryptionKey(128)
5930 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5931 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005932 ASSERT_GT(key_blob_.size(), 0U);
5933
Selene Huang31ab4042020-04-29 04:22:39 -07005934 EXPECT_EQ(
5935 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5936 Begin(KeyPurpose::ENCRYPT,
5937 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5938}
5939
5940/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005941 * EncryptionOperationsTest.AesWrongPadding
5942 *
5943 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5944 */
5945TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5946 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5947 .Authorization(TAG_NO_AUTH_REQUIRED)
5948 .AesEncryptionKey(128)
5949 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5950 .Padding(PaddingMode::NONE)));
5951 ASSERT_GT(key_blob_.size(), 0U);
5952
5953 EXPECT_EQ(
5954 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5955 Begin(KeyPurpose::ENCRYPT,
5956 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5957}
5958
5959/*
5960 * EncryptionOperationsTest.AesInvalidParams
5961 *
5962 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5963 */
5964TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5965 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5966 .Authorization(TAG_NO_AUTH_REQUIRED)
5967 .AesEncryptionKey(128)
5968 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5969 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5970 .Padding(PaddingMode::NONE)
5971 .Padding(PaddingMode::PKCS7)));
5972 ASSERT_GT(key_blob_.size(), 0U);
5973
5974 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5975 .BlockMode(BlockMode::CBC)
5976 .BlockMode(BlockMode::ECB)
5977 .Padding(PaddingMode::NONE));
5978 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
David Drysdale0269d492024-11-14 16:51:58 +00005979 result == ErrorCode::UNSUPPORTED_BLOCK_MODE)
5980 << "unexpected result " << result;
David Drysdaled2cc8c22021-04-15 13:29:45 +01005981
5982 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5983 .BlockMode(BlockMode::ECB)
5984 .Padding(PaddingMode::NONE)
5985 .Padding(PaddingMode::PKCS7));
5986 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdale0269d492024-11-14 16:51:58 +00005987 result == ErrorCode::UNSUPPORTED_PADDING_MODE)
5988 << "unexpected result " << result;
David Drysdaled2cc8c22021-04-15 13:29:45 +01005989}
5990
5991/*
Selene Huang31ab4042020-04-29 04:22:39 -07005992 * EncryptionOperationsTest.AesWrongPurpose
5993 *
5994 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5995 * specified.
5996 */
5997TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5998 auto err = GenerateKey(AuthorizationSetBuilder()
5999 .Authorization(TAG_NO_AUTH_REQUIRED)
6000 .AesKey(128)
6001 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
6002 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6003 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6004 .Padding(PaddingMode::NONE));
6005 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
6006 ASSERT_GT(key_blob_.size(), 0U);
6007
6008 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
6009 .BlockMode(BlockMode::GCM)
6010 .Padding(PaddingMode::NONE)
6011 .Authorization(TAG_MAC_LENGTH, 128));
6012 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
6013
6014 CheckedDeleteKey();
6015
6016 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6017 .Authorization(TAG_NO_AUTH_REQUIRED)
6018 .AesKey(128)
6019 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
6020 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6021 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6022 .Padding(PaddingMode::NONE)));
6023
6024 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
6025 .BlockMode(BlockMode::GCM)
6026 .Padding(PaddingMode::NONE)
6027 .Authorization(TAG_MAC_LENGTH, 128));
6028 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
6029}
6030
6031/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006032 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07006033 *
6034 * Verifies that AES encryption fails in the correct way when provided an input that is not a
6035 * multiple of the block size and no padding is specified.
6036 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01006037TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
6038 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006039 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01006040 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6041 .Authorization(TAG_NO_AUTH_REQUIRED)
6042 .AesEncryptionKey(128)
6043 .Authorization(TAG_BLOCK_MODE, blockMode)
6044 .Padding(PaddingMode::NONE)));
6045 // Message is slightly shorter than two blocks.
6046 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07006047
David Drysdaled2cc8c22021-04-15 13:29:45 +01006048 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
6049 AuthorizationSet out_params;
6050 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6051 string ciphertext;
6052 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
6053 EXPECT_EQ(0U, ciphertext.size());
6054
6055 CheckedDeleteKey();
6056 }
Selene Huang31ab4042020-04-29 04:22:39 -07006057}
6058
6059/*
6060 * EncryptionOperationsTest.AesEcbPkcs7Padding
6061 *
6062 * Verifies that AES PKCS7 padding works for any message length.
6063 */
6064TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
6065 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6066 .Authorization(TAG_NO_AUTH_REQUIRED)
6067 .AesEncryptionKey(128)
6068 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
6069 .Padding(PaddingMode::PKCS7)));
6070
6071 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6072
6073 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08006074 for (size_t i = 0; i <= 48; i++) {
6075 SCOPED_TRACE(testing::Message() << "i = " << i);
6076 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
6077 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07006078 string ciphertext = EncryptMessage(message, params);
6079 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
6080 string plaintext = DecryptMessage(ciphertext, params);
6081 EXPECT_EQ(message, plaintext);
6082 }
6083}
6084
6085/*
6086 * EncryptionOperationsTest.AesEcbWrongPadding
6087 *
6088 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
6089 * specified.
6090 */
6091TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
6092 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6093 .Authorization(TAG_NO_AUTH_REQUIRED)
6094 .AesEncryptionKey(128)
6095 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
6096 .Padding(PaddingMode::NONE)));
6097
6098 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6099
6100 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08006101 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07006102 string message(i, 'a');
6103 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6104 }
6105}
6106
6107/*
6108 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
6109 *
6110 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
6111 */
6112TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
6113 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6114 .Authorization(TAG_NO_AUTH_REQUIRED)
6115 .AesEncryptionKey(128)
6116 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
6117 .Padding(PaddingMode::PKCS7)));
6118
6119 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6120
6121 string message = "a";
6122 string ciphertext = EncryptMessage(message, params);
6123 EXPECT_EQ(16U, ciphertext.size());
6124 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006125
Seth Moore7a55ae32021-06-23 14:28:11 -07006126 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6127 ++ciphertext[ciphertext.size() / 2];
6128
6129 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6130 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01006131 ErrorCode error = Finish(ciphertext, &plaintext);
6132 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07006133 // This is the expected error, we can exit the test now.
6134 return;
6135 } else {
6136 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01006137 ASSERT_EQ(error, ErrorCode::OK)
6138 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07006139 }
6140 }
6141 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006142}
6143
David Drysdaleb8093292022-04-08 12:22:35 +01006144/*
6145 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
6146 *
6147 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
6148 */
6149TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
6150 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6151 .Authorization(TAG_NO_AUTH_REQUIRED)
6152 .AesEncryptionKey(128)
6153 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
6154 .Padding(PaddingMode::PKCS7)));
6155
6156 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6157
6158 string message = "a";
6159 string ciphertext = EncryptMessage(message, params);
6160 EXPECT_EQ(16U, ciphertext.size());
6161 EXPECT_NE(ciphertext, message);
6162
6163 // Shorten the ciphertext.
6164 ciphertext.resize(ciphertext.size() - 1);
6165 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6166 string plaintext;
6167 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
6168}
6169
Selene Huang31ab4042020-04-29 04:22:39 -07006170vector<uint8_t> CopyIv(const AuthorizationSet& set) {
6171 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006172 EXPECT_TRUE(iv);
6173 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07006174}
6175
6176/*
6177 * EncryptionOperationsTest.AesCtrRoundTripSuccess
6178 *
6179 * Verifies that AES CTR mode works.
6180 */
6181TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
6182 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6183 .Authorization(TAG_NO_AUTH_REQUIRED)
6184 .AesEncryptionKey(128)
6185 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6186 .Padding(PaddingMode::NONE)));
6187
6188 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6189
6190 string message = "123";
6191 AuthorizationSet out_params;
6192 string ciphertext1 = EncryptMessage(message, params, &out_params);
6193 vector<uint8_t> iv1 = CopyIv(out_params);
6194 EXPECT_EQ(16U, iv1.size());
6195
6196 EXPECT_EQ(message.size(), ciphertext1.size());
6197
6198 out_params.Clear();
6199 string ciphertext2 = EncryptMessage(message, params, &out_params);
6200 vector<uint8_t> iv2 = CopyIv(out_params);
6201 EXPECT_EQ(16U, iv2.size());
6202
6203 // IVs should be random, so ciphertexts should differ.
6204 EXPECT_NE(ciphertext1, ciphertext2);
6205
6206 auto params_iv1 =
6207 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
6208 auto params_iv2 =
6209 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
6210
6211 string plaintext = DecryptMessage(ciphertext1, params_iv1);
6212 EXPECT_EQ(message, plaintext);
6213 plaintext = DecryptMessage(ciphertext2, params_iv2);
6214 EXPECT_EQ(message, plaintext);
6215
6216 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
6217 plaintext = DecryptMessage(ciphertext1, params_iv2);
6218 EXPECT_NE(message, plaintext);
6219 plaintext = DecryptMessage(ciphertext2, params_iv1);
6220 EXPECT_NE(message, plaintext);
6221}
6222
6223/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306224 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07006225 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306226 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07006227 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306228TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
6229 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
6230}
Selene Huang31ab4042020-04-29 04:22:39 -07006231
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306232/*
6233 * EncryptionOperationsTest.AesCbcIncremental
6234 *
6235 * Verifies that AES works for CBC block mode, when provided data in various size increments.
6236 */
6237TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
6238 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
6239}
Selene Huang31ab4042020-04-29 04:22:39 -07006240
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306241/*
6242 * EncryptionOperationsTest.AesCtrIncremental
6243 *
6244 * Verifies that AES works for CTR block mode, when provided data in various size increments.
6245 */
6246TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
6247 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
6248}
Selene Huang31ab4042020-04-29 04:22:39 -07006249
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306250/*
6251 * EncryptionOperationsTest.AesGcmIncremental
6252 *
6253 * Verifies that AES works for GCM block mode, when provided data in various size increments.
6254 */
6255TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
6256 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07006257}
6258
Prashant Patildd5f7f02022-07-06 18:58:07 +00006259/*
6260 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
6261 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6262 */
6263TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
6264 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
6265 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
6266 string kat_plaintext =
6267 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
6268 "809FFF37081C22EF278F896AB213A2A631");
6269 string kat_ciphertext =
6270 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
6271 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
6272 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6273 kat_ciphertext);
6274}
6275
6276/*
6277 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
6278 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6279 */
6280TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
6281 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
6282 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
6283 string kat_plaintext =
6284 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
6285 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
6286 string kat_ciphertext =
6287 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
6288 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
6289 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6290 kat_plaintext, kat_ciphertext);
6291}
6292
6293/*
6294 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
6295 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6296 */
6297TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
6298 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
6299 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
6300 string kat_plaintext =
6301 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
6302 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
6303 string kat_ciphertext =
6304 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
6305 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
6306 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6307 kat_ciphertext);
6308}
6309
6310/*
6311 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
6312 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6313 */
6314TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
6315 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
6316 string kat_plaintext =
6317 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
6318 "7B6168A9A27BCE554BEA94EF26E6C742A0");
6319 string kat_ciphertext =
6320 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
6321 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
6322 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6323 kat_ciphertext);
6324}
6325
6326/*
6327 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
6328 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6329 */
6330TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
6331 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
6332 string kat_plaintext =
6333 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
6334 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
6335 string kat_ciphertext =
6336 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6337 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6338 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6339 kat_ciphertext);
6340}
6341
6342/*
6343 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6344 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6345 */
6346TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6347 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6348 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6349 string kat_plaintext =
6350 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6351 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6352 string kat_ciphertext =
6353 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6354 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6355 "bdfcc0cba0");
6356
6357 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6358 kat_ciphertext);
6359}
6360
6361/*
6362 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6363 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6364 */
6365TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6366 if (SecLevel() == SecurityLevel::STRONGBOX) {
6367 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6368 }
6369 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6370 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6371 string kat_plaintext =
6372 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6373 "167f2497c994bd496eb80bfb2ba2c9d5af");
6374 string kat_ciphertext =
6375 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6376 "72c134552f3a138e726fbe493b3a839598");
6377 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6378 kat_ciphertext);
6379}
6380
6381/*
6382 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6383 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6384 */
6385TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6386 if (SecLevel() == SecurityLevel::STRONGBOX) {
6387 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6388 }
6389 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6390 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6391 string kat_plaintext =
6392 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6393 "b170");
6394 string kat_ciphertext =
6395 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6396 "4e3884138ff403a41fd99818708ada301c");
6397 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6398 kat_plaintext, kat_ciphertext);
6399}
6400
6401/*
6402 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6403 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6404 */
6405TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6406 if (SecLevel() == SecurityLevel::STRONGBOX) {
6407 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6408 }
6409 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6410 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6411 string kat_plaintext =
6412 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6413 "28091e09cdbbd3b42b");
6414 string kat_ciphertext =
6415 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6416 "2ae0f90f0c19f42b4a");
6417 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6418 kat_ciphertext);
6419}
6420
6421/*
6422 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6423 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6424 */
6425TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6426 if (SecLevel() == SecurityLevel::STRONGBOX) {
6427 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6428 }
6429 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6430 string kat_plaintext =
6431 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6432 "44ab");
6433 string kat_ciphertext =
6434 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6435 "2453");
6436 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6437 kat_ciphertext);
6438}
6439
6440/*
6441 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6442 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6443 */
6444TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6445 if (SecLevel() == SecurityLevel::STRONGBOX) {
6446 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6447 }
6448 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6449 string kat_plaintext =
6450 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6451 "e2c7");
6452 string kat_ciphertext =
6453 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6454 "bb7e3a889dd4a9589098b44acf1056e7aa");
6455 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6456 kat_ciphertext);
6457}
6458
6459/*
6460 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6461 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6462 */
6463TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6464 if (SecLevel() == SecurityLevel::STRONGBOX) {
6465 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6466 }
6467 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6468 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6469 string kat_plaintext =
6470 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6471 "ff52");
6472 string kat_ciphertext =
6473 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6474 "1413ad70fb0e1970669095ad77ebb5974ae8");
6475
6476 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6477 kat_ciphertext);
6478}
6479
6480/*
6481 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6482 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6483 */
6484TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6485 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6486 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6487 string kat_plaintext =
6488 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6489 "494cb53caca353e4b637ba05687be20f8d");
6490 string kat_ciphertext =
6491 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6492 "6047da1e4fd7c4e1cf2656097f75ae8685");
6493 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6494 kat_ciphertext);
6495}
6496
6497/*
6498 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6499 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6500 */
6501TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6502 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6503 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6504 string kat_plaintext =
6505 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6506 "2545a82b73c48078b9dae62261c65909");
6507 string kat_ciphertext =
6508 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6509 "9403a71987b95124073d69f2a3cb95b0ab");
6510 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6511 kat_plaintext, kat_ciphertext);
6512}
6513
6514/*
6515 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6516 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6517 */
6518TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6519 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6520 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6521 string kat_plaintext =
6522 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6523 "1f6db3c884");
6524 string kat_ciphertext =
6525 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6526 "a7be30d4c3");
6527 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6528 kat_ciphertext);
6529}
6530
6531/*
6532 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6533 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6534 */
6535TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6536 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6537 string kat_plaintext =
6538 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6539 "31a476d6806b8116089c6ec50bb543200f");
6540 string kat_ciphertext =
6541 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6542 "c83e377faf246288931136bef2a07c0be4");
6543 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6544 kat_ciphertext);
6545}
6546
6547/*
6548 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6549 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6550 */
6551TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6552 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6553 string kat_plaintext =
6554 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6555 "6f");
6556 string kat_ciphertext =
6557 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6558 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6559 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6560 kat_ciphertext);
6561}
6562
6563/*
6564 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6565 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6566 */
6567TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6568 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6569 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6570 string kat_plaintext =
6571 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6572 "f0");
6573 string kat_ciphertext =
6574 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6575 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6576
6577 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6578 kat_ciphertext);
6579}
6580
Selene Huang31ab4042020-04-29 04:22:39 -07006581struct AesCtrSp80038aTestVector {
6582 const char* key;
6583 const char* nonce;
6584 const char* plaintext;
6585 const char* ciphertext;
6586};
6587
6588// These test vectors are taken from
6589// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6590static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6591 // AES-128
6592 {
6593 "2b7e151628aed2a6abf7158809cf4f3c",
6594 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6595 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6596 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6597 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6598 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6599 },
6600 // AES-192
6601 {
6602 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6603 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6604 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6605 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6606 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6607 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6608 },
6609 // AES-256
6610 {
6611 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6612 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6613 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6614 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6615 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6616 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6617 },
6618};
6619
6620/*
6621 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6622 *
6623 * Verifies AES CTR implementation against SP800-38A test vectors.
6624 */
6625TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6626 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6627 for (size_t i = 0; i < 3; i++) {
6628 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6629 const string key = hex2str(test.key);
6630 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6631 InvalidSizes.end())
6632 continue;
6633 const string nonce = hex2str(test.nonce);
6634 const string plaintext = hex2str(test.plaintext);
6635 const string ciphertext = hex2str(test.ciphertext);
6636 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6637 }
6638}
6639
6640/*
6641 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6642 *
6643 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6644 */
6645TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6646 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6647 .Authorization(TAG_NO_AUTH_REQUIRED)
6648 .AesEncryptionKey(128)
6649 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6650 .Padding(PaddingMode::PKCS7)));
6651 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6652 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6653}
6654
6655/*
6656 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6657 *
6658 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6659 */
6660TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6661 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6662 .Authorization(TAG_NO_AUTH_REQUIRED)
6663 .AesEncryptionKey(128)
6664 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6665 .Authorization(TAG_CALLER_NONCE)
6666 .Padding(PaddingMode::NONE)));
6667
6668 auto params = AuthorizationSetBuilder()
6669 .BlockMode(BlockMode::CTR)
6670 .Padding(PaddingMode::NONE)
6671 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6672 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6673
6674 params = AuthorizationSetBuilder()
6675 .BlockMode(BlockMode::CTR)
6676 .Padding(PaddingMode::NONE)
6677 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6678 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6679
6680 params = AuthorizationSetBuilder()
6681 .BlockMode(BlockMode::CTR)
6682 .Padding(PaddingMode::NONE)
6683 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6684 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6685}
6686
6687/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006688 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006689 *
6690 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6691 */
6692TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6693 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6694 .Authorization(TAG_NO_AUTH_REQUIRED)
6695 .AesEncryptionKey(128)
6696 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6697 .Padding(PaddingMode::NONE)));
6698 // Two-block message.
6699 string message = "12345678901234567890123456789012";
6700 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6701 AuthorizationSet out_params;
6702 string ciphertext1 = EncryptMessage(message, params, &out_params);
6703 vector<uint8_t> iv1 = CopyIv(out_params);
6704 EXPECT_EQ(message.size(), ciphertext1.size());
6705
6706 out_params.Clear();
6707
6708 string ciphertext2 = EncryptMessage(message, params, &out_params);
6709 vector<uint8_t> iv2 = CopyIv(out_params);
6710 EXPECT_EQ(message.size(), ciphertext2.size());
6711
6712 // IVs should be random, so ciphertexts should differ.
6713 EXPECT_NE(ciphertext1, ciphertext2);
6714
6715 params.push_back(TAG_NONCE, iv1);
6716 string plaintext = DecryptMessage(ciphertext1, params);
6717 EXPECT_EQ(message, plaintext);
6718}
6719
6720/*
Tommy Chiuee705692021-09-23 20:09:13 +08006721 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6722 *
6723 * Verifies that keymaster generates correct output on zero-input with
6724 * NonePadding mode
6725 */
6726TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6727 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6728 .Authorization(TAG_NO_AUTH_REQUIRED)
6729 .AesEncryptionKey(128)
6730 .BlockMode(BlockMode::CBC)
6731 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6732
6733 // Zero input message
6734 string message = "";
6735 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006736 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006737 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6738 AuthorizationSet out_params;
6739 string ciphertext1 = EncryptMessage(message, params, &out_params);
6740 vector<uint8_t> iv1 = CopyIv(out_params);
6741 if (padding == PaddingMode::NONE)
6742 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6743 else
6744 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6745
6746 out_params.Clear();
6747
6748 string ciphertext2 = EncryptMessage(message, params, &out_params);
6749 vector<uint8_t> iv2 = CopyIv(out_params);
6750 if (padding == PaddingMode::NONE)
6751 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6752 else
6753 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6754
6755 // IVs should be random
6756 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6757
6758 params.push_back(TAG_NONCE, iv1);
6759 string plaintext = DecryptMessage(ciphertext1, params);
6760 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6761 }
6762}
6763
6764/*
Selene Huang31ab4042020-04-29 04:22:39 -07006765 * EncryptionOperationsTest.AesCallerNonce
6766 *
6767 * Verifies that AES caller-provided nonces work correctly.
6768 */
6769TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6770 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6771 .Authorization(TAG_NO_AUTH_REQUIRED)
6772 .AesEncryptionKey(128)
6773 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6774 .Authorization(TAG_CALLER_NONCE)
6775 .Padding(PaddingMode::NONE)));
6776
6777 string message = "12345678901234567890123456789012";
6778
6779 // Don't specify nonce, should get a random one.
6780 AuthorizationSetBuilder params =
6781 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6782 AuthorizationSet out_params;
6783 string ciphertext = EncryptMessage(message, params, &out_params);
6784 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006785 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006786
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006787 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006788 string plaintext = DecryptMessage(ciphertext, params);
6789 EXPECT_EQ(message, plaintext);
6790
6791 // Now specify a nonce, should also work.
6792 params = AuthorizationSetBuilder()
6793 .BlockMode(BlockMode::CBC)
6794 .Padding(PaddingMode::NONE)
6795 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6796 out_params.Clear();
6797 ciphertext = EncryptMessage(message, params, &out_params);
6798
6799 // Decrypt with correct nonce.
6800 plaintext = DecryptMessage(ciphertext, params);
6801 EXPECT_EQ(message, plaintext);
6802
6803 // Try with wrong nonce.
6804 params = AuthorizationSetBuilder()
6805 .BlockMode(BlockMode::CBC)
6806 .Padding(PaddingMode::NONE)
6807 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6808 plaintext = DecryptMessage(ciphertext, params);
6809 EXPECT_NE(message, plaintext);
6810}
6811
6812/*
6813 * EncryptionOperationsTest.AesCallerNonceProhibited
6814 *
6815 * Verifies that caller-provided nonces are not permitted when not specified in the key
6816 * authorizations.
6817 */
6818TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6819 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6820 .Authorization(TAG_NO_AUTH_REQUIRED)
6821 .AesEncryptionKey(128)
6822 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6823 .Padding(PaddingMode::NONE)));
6824
6825 string message = "12345678901234567890123456789012";
6826
6827 // Don't specify nonce, should get a random one.
6828 AuthorizationSetBuilder params =
6829 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6830 AuthorizationSet out_params;
6831 string ciphertext = EncryptMessage(message, params, &out_params);
6832 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006833 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006834
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006835 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006836 string plaintext = DecryptMessage(ciphertext, params);
6837 EXPECT_EQ(message, plaintext);
6838
6839 // Now specify a nonce, should fail
6840 params = AuthorizationSetBuilder()
6841 .BlockMode(BlockMode::CBC)
6842 .Padding(PaddingMode::NONE)
6843 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6844 out_params.Clear();
6845 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6846}
6847
6848/*
6849 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6850 *
6851 * Verifies that AES GCM mode works.
6852 */
6853TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6854 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6855 .Authorization(TAG_NO_AUTH_REQUIRED)
6856 .AesEncryptionKey(128)
6857 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6858 .Padding(PaddingMode::NONE)
6859 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6860
6861 string aad = "foobar";
6862 string message = "123456789012345678901234567890123456";
6863
6864 auto begin_params = AuthorizationSetBuilder()
6865 .BlockMode(BlockMode::GCM)
6866 .Padding(PaddingMode::NONE)
6867 .Authorization(TAG_MAC_LENGTH, 128);
6868
Selene Huang31ab4042020-04-29 04:22:39 -07006869 // Encrypt
6870 AuthorizationSet begin_out_params;
6871 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6872 << "Begin encrypt";
6873 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006874 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6875 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006876 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6877
6878 // Grab nonce
6879 begin_params.push_back(begin_out_params);
6880
6881 // Decrypt.
6882 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006883 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006884 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006885 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006886 EXPECT_EQ(message.length(), plaintext.length());
6887 EXPECT_EQ(message, plaintext);
6888}
6889
6890/*
6891 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6892 *
6893 * Verifies that AES GCM mode works, even when there's a long delay
6894 * between operations.
6895 */
6896TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6897 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6898 .Authorization(TAG_NO_AUTH_REQUIRED)
6899 .AesEncryptionKey(128)
6900 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6901 .Padding(PaddingMode::NONE)
6902 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6903
6904 string aad = "foobar";
6905 string message = "123456789012345678901234567890123456";
6906
6907 auto begin_params = AuthorizationSetBuilder()
6908 .BlockMode(BlockMode::GCM)
6909 .Padding(PaddingMode::NONE)
6910 .Authorization(TAG_MAC_LENGTH, 128);
6911
Selene Huang31ab4042020-04-29 04:22:39 -07006912 // Encrypt
6913 AuthorizationSet begin_out_params;
6914 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6915 << "Begin encrypt";
6916 string ciphertext;
6917 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006918 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006919 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006920 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006921
6922 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6923
6924 // Grab nonce
6925 begin_params.push_back(begin_out_params);
6926
6927 // Decrypt.
6928 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6929 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006930 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006931 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006932 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006933 sleep(5);
6934 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6935 EXPECT_EQ(message.length(), plaintext.length());
6936 EXPECT_EQ(message, plaintext);
6937}
6938
6939/*
6940 * EncryptionOperationsTest.AesGcmDifferentNonces
6941 *
6942 * Verifies that encrypting the same data with different nonces produces different outputs.
6943 */
6944TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6945 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6946 .Authorization(TAG_NO_AUTH_REQUIRED)
6947 .AesEncryptionKey(128)
6948 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6949 .Padding(PaddingMode::NONE)
6950 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6951 .Authorization(TAG_CALLER_NONCE)));
6952
6953 string aad = "foobar";
6954 string message = "123456789012345678901234567890123456";
6955 string nonce1 = "000000000000";
6956 string nonce2 = "111111111111";
6957 string nonce3 = "222222222222";
6958
6959 string ciphertext1 =
6960 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6961 string ciphertext2 =
6962 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6963 string ciphertext3 =
6964 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6965
6966 ASSERT_NE(ciphertext1, ciphertext2);
6967 ASSERT_NE(ciphertext1, ciphertext3);
6968 ASSERT_NE(ciphertext2, ciphertext3);
6969}
6970
6971/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006972 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6973 *
6974 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6975 */
6976TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6977 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6978 .Authorization(TAG_NO_AUTH_REQUIRED)
6979 .AesEncryptionKey(128)
6980 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6981 .Padding(PaddingMode::NONE)
6982 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6983
6984 string aad = "foobar";
6985 string message = "123456789012345678901234567890123456";
6986
6987 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6988 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6989 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6990
6991 ASSERT_NE(ciphertext1, ciphertext2);
6992 ASSERT_NE(ciphertext1, ciphertext3);
6993 ASSERT_NE(ciphertext2, ciphertext3);
6994}
6995
6996/*
Selene Huang31ab4042020-04-29 04:22:39 -07006997 * EncryptionOperationsTest.AesGcmTooShortTag
6998 *
6999 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
7000 */
7001TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
7002 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7003 .Authorization(TAG_NO_AUTH_REQUIRED)
7004 .AesEncryptionKey(128)
7005 .BlockMode(BlockMode::GCM)
7006 .Padding(PaddingMode::NONE)
7007 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7008 string message = "123456789012345678901234567890123456";
7009 auto params = AuthorizationSetBuilder()
7010 .BlockMode(BlockMode::GCM)
7011 .Padding(PaddingMode::NONE)
7012 .Authorization(TAG_MAC_LENGTH, 96);
7013
7014 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
7015}
7016
7017/*
7018 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
7019 *
7020 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
7021 */
7022TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
7023 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7024 .Authorization(TAG_NO_AUTH_REQUIRED)
7025 .AesEncryptionKey(128)
7026 .BlockMode(BlockMode::GCM)
7027 .Padding(PaddingMode::NONE)
7028 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7029 string aad = "foobar";
7030 string message = "123456789012345678901234567890123456";
7031 auto params = AuthorizationSetBuilder()
7032 .BlockMode(BlockMode::GCM)
7033 .Padding(PaddingMode::NONE)
7034 .Authorization(TAG_MAC_LENGTH, 128);
7035
Selene Huang31ab4042020-04-29 04:22:39 -07007036 // Encrypt
7037 AuthorizationSet begin_out_params;
7038 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
7039 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08007040 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007041
7042 AuthorizationSet finish_out_params;
7043 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007044 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
7045 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007046
7047 params = AuthorizationSetBuilder()
7048 .Authorizations(begin_out_params)
7049 .BlockMode(BlockMode::GCM)
7050 .Padding(PaddingMode::NONE)
7051 .Authorization(TAG_MAC_LENGTH, 96);
7052
7053 // Decrypt.
7054 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
7055}
7056
7057/*
7058 * EncryptionOperationsTest.AesGcmCorruptKey
7059 *
7060 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
7061 */
7062TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
7063 const uint8_t nonce_bytes[] = {
7064 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
7065 };
7066 string nonce = make_string(nonce_bytes);
7067 const uint8_t ciphertext_bytes[] = {
7068 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
7069 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
7070 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
7071 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
7072 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
7073 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
7074 };
7075 string ciphertext = make_string(ciphertext_bytes);
7076
7077 auto params = AuthorizationSetBuilder()
7078 .BlockMode(BlockMode::GCM)
7079 .Padding(PaddingMode::NONE)
7080 .Authorization(TAG_MAC_LENGTH, 128)
7081 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
7082
7083 auto import_params = AuthorizationSetBuilder()
7084 .Authorization(TAG_NO_AUTH_REQUIRED)
7085 .AesEncryptionKey(128)
7086 .BlockMode(BlockMode::GCM)
7087 .Padding(PaddingMode::NONE)
7088 .Authorization(TAG_CALLER_NONCE)
7089 .Authorization(TAG_MIN_MAC_LENGTH, 128);
7090
7091 // Import correct key and decrypt
7092 const uint8_t key_bytes[] = {
7093 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
7094 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
7095 };
7096 string key = make_string(key_bytes);
7097 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
7098 string plaintext = DecryptMessage(ciphertext, params);
7099 CheckedDeleteKey();
7100
7101 // Corrupt key and attempt to decrypt
7102 key[0] = 0;
7103 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
7104 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
7105 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
7106 CheckedDeleteKey();
7107}
7108
7109/*
7110 * EncryptionOperationsTest.AesGcmAadNoData
7111 *
7112 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
7113 * encrypt.
7114 */
7115TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
7116 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7117 .Authorization(TAG_NO_AUTH_REQUIRED)
7118 .AesEncryptionKey(128)
7119 .BlockMode(BlockMode::GCM)
7120 .Padding(PaddingMode::NONE)
7121 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7122
7123 string aad = "1234567890123456";
7124 auto params = AuthorizationSetBuilder()
7125 .BlockMode(BlockMode::GCM)
7126 .Padding(PaddingMode::NONE)
7127 .Authorization(TAG_MAC_LENGTH, 128);
7128
Selene Huang31ab4042020-04-29 04:22:39 -07007129 // Encrypt
7130 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007131 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007132 string ciphertext;
7133 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07007134 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
7135 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007136 EXPECT_TRUE(finish_out_params.empty());
7137
7138 // Grab nonce
7139 params.push_back(begin_out_params);
7140
7141 // Decrypt.
7142 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007143 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007144 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007145 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007146
7147 EXPECT_TRUE(finish_out_params.empty());
7148
7149 EXPECT_EQ("", plaintext);
7150}
7151
7152/*
7153 * EncryptionOperationsTest.AesGcmMultiPartAad
7154 *
7155 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
7156 * chunks.
7157 */
7158TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
7159 const size_t tag_bits = 128;
7160 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7161 .Authorization(TAG_NO_AUTH_REQUIRED)
7162 .AesEncryptionKey(128)
7163 .BlockMode(BlockMode::GCM)
7164 .Padding(PaddingMode::NONE)
7165 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7166
7167 string message = "123456789012345678901234567890123456";
7168 auto begin_params = AuthorizationSetBuilder()
7169 .BlockMode(BlockMode::GCM)
7170 .Padding(PaddingMode::NONE)
7171 .Authorization(TAG_MAC_LENGTH, tag_bits);
7172 AuthorizationSet begin_out_params;
7173
David Drysdale7fc26b92022-05-13 09:54:24 +01007174 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007175
7176 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07007177 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
7178 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007179 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007180 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7181 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007182
Selene Huang31ab4042020-04-29 04:22:39 -07007183 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07007184 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07007185
7186 // Grab nonce.
7187 begin_params.push_back(begin_out_params);
7188
7189 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01007190 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007191 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007192 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007193 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007194 EXPECT_EQ(message, plaintext);
7195}
7196
7197/*
7198 * EncryptionOperationsTest.AesGcmAadOutOfOrder
7199 *
7200 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
7201 */
7202TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
7203 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7204 .Authorization(TAG_NO_AUTH_REQUIRED)
7205 .AesEncryptionKey(128)
7206 .BlockMode(BlockMode::GCM)
7207 .Padding(PaddingMode::NONE)
7208 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7209
7210 string message = "123456789012345678901234567890123456";
7211 auto begin_params = AuthorizationSetBuilder()
7212 .BlockMode(BlockMode::GCM)
7213 .Padding(PaddingMode::NONE)
7214 .Authorization(TAG_MAC_LENGTH, 128);
7215 AuthorizationSet begin_out_params;
7216
David Drysdale7fc26b92022-05-13 09:54:24 +01007217 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007218
Shawn Willden92d79c02021-02-19 07:31:55 -07007219 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007220 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007221 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7222 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007223
David Drysdaled2cc8c22021-04-15 13:29:45 +01007224 // The failure should have already cancelled the operation.
7225 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
7226
Shawn Willden92d79c02021-02-19 07:31:55 -07007227 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07007228}
7229
7230/*
7231 * EncryptionOperationsTest.AesGcmBadAad
7232 *
7233 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
7234 */
7235TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
7236 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7237 .Authorization(TAG_NO_AUTH_REQUIRED)
7238 .AesEncryptionKey(128)
7239 .BlockMode(BlockMode::GCM)
7240 .Padding(PaddingMode::NONE)
7241 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7242
7243 string message = "12345678901234567890123456789012";
7244 auto begin_params = AuthorizationSetBuilder()
7245 .BlockMode(BlockMode::GCM)
7246 .Padding(PaddingMode::NONE)
7247 .Authorization(TAG_MAC_LENGTH, 128);
7248
Selene Huang31ab4042020-04-29 04:22:39 -07007249 // Encrypt
7250 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007251 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007252 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007253 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007254 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007255
7256 // Grab nonce
7257 begin_params.push_back(begin_out_params);
7258
Selene Huang31ab4042020-04-29 04:22:39 -07007259 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007260 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007261 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007262 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007263 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007264}
7265
7266/*
7267 * EncryptionOperationsTest.AesGcmWrongNonce
7268 *
7269 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
7270 */
7271TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
7272 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7273 .Authorization(TAG_NO_AUTH_REQUIRED)
7274 .AesEncryptionKey(128)
7275 .BlockMode(BlockMode::GCM)
7276 .Padding(PaddingMode::NONE)
7277 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7278
7279 string message = "12345678901234567890123456789012";
7280 auto begin_params = AuthorizationSetBuilder()
7281 .BlockMode(BlockMode::GCM)
7282 .Padding(PaddingMode::NONE)
7283 .Authorization(TAG_MAC_LENGTH, 128);
7284
Selene Huang31ab4042020-04-29 04:22:39 -07007285 // Encrypt
7286 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007287 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007288 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007289 string ciphertext;
7290 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07007291 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007292
7293 // Wrong nonce
7294 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
7295
7296 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007297 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007298 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007299 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007300 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007301
7302 // With wrong nonce, should have gotten garbage plaintext (or none).
7303 EXPECT_NE(message, plaintext);
7304}
7305
7306/*
7307 * EncryptionOperationsTest.AesGcmCorruptTag
7308 *
7309 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
7310 */
7311TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
7312 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7313 .Authorization(TAG_NO_AUTH_REQUIRED)
7314 .AesEncryptionKey(128)
7315 .BlockMode(BlockMode::GCM)
7316 .Padding(PaddingMode::NONE)
7317 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7318
7319 string aad = "1234567890123456";
7320 string message = "123456789012345678901234567890123456";
7321
7322 auto params = AuthorizationSetBuilder()
7323 .BlockMode(BlockMode::GCM)
7324 .Padding(PaddingMode::NONE)
7325 .Authorization(TAG_MAC_LENGTH, 128);
7326
Selene Huang31ab4042020-04-29 04:22:39 -07007327 // Encrypt
7328 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007329 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007330 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007331 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007332 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007333
7334 // Corrupt tag
7335 ++(*ciphertext.rbegin());
7336
7337 // Grab nonce
7338 params.push_back(begin_out_params);
7339
7340 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007341 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007342 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007343 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007344 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007345}
7346
7347/*
7348 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7349 *
7350 * Verifies that 3DES is basically functional.
7351 */
7352TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7353 auto auths = AuthorizationSetBuilder()
7354 .TripleDesEncryptionKey(168)
7355 .BlockMode(BlockMode::ECB)
7356 .Authorization(TAG_NO_AUTH_REQUIRED)
7357 .Padding(PaddingMode::NONE);
7358
7359 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7360 // Two-block message.
7361 string message = "1234567890123456";
7362 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7363 string ciphertext1 = EncryptMessage(message, inParams);
7364 EXPECT_EQ(message.size(), ciphertext1.size());
7365
7366 string ciphertext2 = EncryptMessage(string(message), inParams);
7367 EXPECT_EQ(message.size(), ciphertext2.size());
7368
7369 // ECB is deterministic.
7370 EXPECT_EQ(ciphertext1, ciphertext2);
7371
7372 string plaintext = DecryptMessage(ciphertext1, inParams);
7373 EXPECT_EQ(message, plaintext);
7374}
7375
7376/*
7377 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7378 *
7379 * Verifies that CBC keys reject ECB usage.
7380 */
7381TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7382 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7383 .TripleDesEncryptionKey(168)
7384 .BlockMode(BlockMode::CBC)
7385 .Authorization(TAG_NO_AUTH_REQUIRED)
7386 .Padding(PaddingMode::NONE)));
7387
7388 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7389 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7390}
7391
7392/*
7393 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7394 *
7395 * Tests ECB mode with PKCS#7 padding, various message sizes.
7396 */
7397TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7398 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7399 .TripleDesEncryptionKey(168)
7400 .BlockMode(BlockMode::ECB)
7401 .Authorization(TAG_NO_AUTH_REQUIRED)
7402 .Padding(PaddingMode::PKCS7)));
7403
7404 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007405 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007406 string message(i, 'a');
7407 auto inParams =
7408 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7409 string ciphertext = EncryptMessage(message, inParams);
7410 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7411 string plaintext = DecryptMessage(ciphertext, inParams);
7412 EXPECT_EQ(message, plaintext);
7413 }
7414}
7415
7416/*
7417 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7418 *
7419 * Verifies that keys configured for no padding reject PKCS7 padding
7420 */
7421TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7422 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7423 .TripleDesEncryptionKey(168)
7424 .BlockMode(BlockMode::ECB)
7425 .Authorization(TAG_NO_AUTH_REQUIRED)
7426 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007427 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7428 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007429}
7430
7431/*
7432 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7433 *
7434 * Verifies that corrupted padding is detected.
7435 */
7436TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7437 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7438 .TripleDesEncryptionKey(168)
7439 .BlockMode(BlockMode::ECB)
7440 .Authorization(TAG_NO_AUTH_REQUIRED)
7441 .Padding(PaddingMode::PKCS7)));
7442
7443 string message = "a";
7444 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7445 EXPECT_EQ(8U, ciphertext.size());
7446 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007447
7448 AuthorizationSetBuilder begin_params;
7449 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7450 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007451
7452 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7453 ++ciphertext[ciphertext.size() / 2];
7454
David Drysdale7fc26b92022-05-13 09:54:24 +01007455 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007456 string plaintext;
7457 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7458 ErrorCode error = Finish(&plaintext);
7459 if (error == ErrorCode::INVALID_ARGUMENT) {
7460 // This is the expected error, we can exit the test now.
7461 return;
7462 } else {
7463 // Very small chance we got valid decryption, so try again.
7464 ASSERT_EQ(error, ErrorCode::OK);
7465 }
7466 }
7467 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007468}
7469
7470struct TripleDesTestVector {
7471 const char* name;
7472 const KeyPurpose purpose;
7473 const BlockMode block_mode;
7474 const PaddingMode padding_mode;
7475 const char* key;
7476 const char* iv;
7477 const char* input;
7478 const char* output;
7479};
7480
7481// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7482// of the NIST vectors are multiples of the block size.
7483static const TripleDesTestVector kTripleDesTestVectors[] = {
7484 {
7485 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7486 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7487 "", // IV
7488 "329d86bdf1bc5af4", // input
7489 "d946c2756d78633f", // output
7490 },
7491 {
7492 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7493 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7494 "", // IV
7495 "6b1540781b01ce1997adae102dbf3c5b", // input
7496 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7497 },
7498 {
7499 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7500 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7501 "", // IV
7502 "6daad94ce08acfe7", // input
7503 "660e7d32dcc90e79", // output
7504 },
7505 {
7506 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7507 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7508 "", // IV
7509 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7510 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7511 },
7512 {
7513 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7514 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7515 "43f791134c5647ba", // IV
7516 "dcc153cef81d6f24", // input
7517 "92538bd8af18d3ba", // output
7518 },
7519 {
7520 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7521 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7522 "c2e999cb6249023c", // IV
7523 "c689aee38a301bb316da75db36f110b5", // input
7524 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7525 },
7526 {
7527 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7528 PaddingMode::PKCS7,
7529 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7530 "c2e999cb6249023c", // IV
7531 "c689aee38a301bb316da75db36f110b500", // input
7532 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7533 },
7534 {
7535 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7536 PaddingMode::PKCS7,
7537 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7538 "c2e999cb6249023c", // IV
7539 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7540 "c689aee38a301bb316da75db36f110b500", // output
7541 },
7542 {
7543 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7544 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7545 "41746c7e442d3681", // IV
7546 "c53a7b0ec40600fe", // input
7547 "d4f00eb455de1034", // output
7548 },
7549 {
7550 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7551 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7552 "3982bc02c3727d45", // IV
7553 "6006f10adef52991fcc777a1238bbb65", // input
7554 "edae09288e9e3bc05746d872b48e3b29", // output
7555 },
7556};
7557
7558/*
7559 * EncryptionOperationsTest.TripleDesTestVector
7560 *
7561 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7562 */
7563TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7564 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7565 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7566 SCOPED_TRACE(test->name);
7567 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7568 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7569 hex2str(test->output));
7570 }
7571}
7572
7573/*
7574 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7575 *
7576 * Validates CBC mode functionality.
7577 */
7578TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7579 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7580 .TripleDesEncryptionKey(168)
7581 .BlockMode(BlockMode::CBC)
7582 .Authorization(TAG_NO_AUTH_REQUIRED)
7583 .Padding(PaddingMode::NONE)));
7584
7585 ASSERT_GT(key_blob_.size(), 0U);
7586
Brian J Murray734c8412022-01-13 14:55:30 -08007587 // Four-block message.
7588 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007589 vector<uint8_t> iv1;
7590 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7591 EXPECT_EQ(message.size(), ciphertext1.size());
7592
7593 vector<uint8_t> iv2;
7594 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7595 EXPECT_EQ(message.size(), ciphertext2.size());
7596
7597 // IVs should be random, so ciphertexts should differ.
7598 EXPECT_NE(iv1, iv2);
7599 EXPECT_NE(ciphertext1, ciphertext2);
7600
7601 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7602 EXPECT_EQ(message, plaintext);
7603}
7604
7605/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007606 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7607 *
7608 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7609 */
7610TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7611 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7612 .TripleDesEncryptionKey(168)
7613 .BlockMode(BlockMode::CBC)
7614 .Authorization(TAG_NO_AUTH_REQUIRED)
7615 .Authorization(TAG_CALLER_NONCE)
7616 .Padding(PaddingMode::NONE)));
7617 auto params = AuthorizationSetBuilder()
7618 .BlockMode(BlockMode::CBC)
7619 .Padding(PaddingMode::NONE)
7620 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7621 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7622}
7623
7624/*
Selene Huang31ab4042020-04-29 04:22:39 -07007625 * EncryptionOperationsTest.TripleDesCallerIv
7626 *
7627 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7628 */
7629TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7630 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7631 .TripleDesEncryptionKey(168)
7632 .BlockMode(BlockMode::CBC)
7633 .Authorization(TAG_NO_AUTH_REQUIRED)
7634 .Authorization(TAG_CALLER_NONCE)
7635 .Padding(PaddingMode::NONE)));
7636 string message = "1234567890123456";
7637 vector<uint8_t> iv;
7638 // Don't specify IV, should get a random one.
7639 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7640 EXPECT_EQ(message.size(), ciphertext1.size());
7641 EXPECT_EQ(8U, iv.size());
7642
7643 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7644 EXPECT_EQ(message, plaintext);
7645
7646 // Now specify an IV, should also work.
7647 iv = AidlBuf("abcdefgh");
7648 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7649
7650 // Decrypt with correct IV.
7651 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7652 EXPECT_EQ(message, plaintext);
7653
7654 // Now try with wrong IV.
7655 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7656 EXPECT_NE(message, plaintext);
7657}
7658
7659/*
7660 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7661 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007662 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007663 */
7664TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7665 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7666 .TripleDesEncryptionKey(168)
7667 .BlockMode(BlockMode::CBC)
7668 .Authorization(TAG_NO_AUTH_REQUIRED)
7669 .Padding(PaddingMode::NONE)));
7670
7671 string message = "12345678901234567890123456789012";
7672 vector<uint8_t> iv;
7673 // Don't specify nonce, should get a random one.
7674 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7675 EXPECT_EQ(message.size(), ciphertext1.size());
7676 EXPECT_EQ(8U, iv.size());
7677
7678 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7679 EXPECT_EQ(message, plaintext);
7680
7681 // Now specify a nonce, should fail.
7682 auto input_params = AuthorizationSetBuilder()
7683 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7684 .BlockMode(BlockMode::CBC)
7685 .Padding(PaddingMode::NONE);
7686 AuthorizationSet output_params;
7687 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7688 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7689}
7690
7691/*
7692 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7693 *
7694 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7695 */
7696TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7697 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7698 .TripleDesEncryptionKey(168)
7699 .BlockMode(BlockMode::ECB)
7700 .Authorization(TAG_NO_AUTH_REQUIRED)
7701 .Padding(PaddingMode::NONE)));
7702 // Two-block message.
7703 string message = "1234567890123456";
7704 auto begin_params =
7705 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7706 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7707}
7708
7709/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007710 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007711 *
7712 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7713 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007714TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7715 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007716 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007717 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7718 .TripleDesEncryptionKey(168)
7719 .BlockMode(blockMode)
7720 .Authorization(TAG_NO_AUTH_REQUIRED)
7721 .Padding(PaddingMode::NONE)));
7722 // Message is slightly shorter than two blocks.
7723 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007724
David Drysdaled2cc8c22021-04-15 13:29:45 +01007725 auto begin_params =
7726 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7727 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007728 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007729 string ciphertext;
7730 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7731
7732 CheckedDeleteKey();
7733 }
Selene Huang31ab4042020-04-29 04:22:39 -07007734}
7735
7736/*
7737 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7738 *
7739 * Verifies that PKCS7 padding works correctly in CBC mode.
7740 */
7741TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7742 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7743 .TripleDesEncryptionKey(168)
7744 .BlockMode(BlockMode::CBC)
7745 .Authorization(TAG_NO_AUTH_REQUIRED)
7746 .Padding(PaddingMode::PKCS7)));
7747
7748 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007749 for (size_t i = 0; i <= 32; i++) {
7750 SCOPED_TRACE(testing::Message() << "i = " << i);
7751 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7752 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007753 vector<uint8_t> iv;
7754 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7755 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7756 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7757 EXPECT_EQ(message, plaintext);
7758 }
7759}
7760
7761/*
7762 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7763 *
7764 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7765 */
7766TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7767 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7768 .TripleDesEncryptionKey(168)
7769 .BlockMode(BlockMode::CBC)
7770 .Authorization(TAG_NO_AUTH_REQUIRED)
7771 .Padding(PaddingMode::NONE)));
7772
7773 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007774 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007775 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007776 auto begin_params =
7777 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7778 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7779 }
7780}
7781
7782/*
7783 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7784 *
7785 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7786 */
7787TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7788 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7789 .TripleDesEncryptionKey(168)
7790 .BlockMode(BlockMode::CBC)
7791 .Authorization(TAG_NO_AUTH_REQUIRED)
7792 .Padding(PaddingMode::PKCS7)));
7793
7794 string message = "a";
7795 vector<uint8_t> iv;
7796 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7797 EXPECT_EQ(8U, ciphertext.size());
7798 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007799
7800 auto begin_params = AuthorizationSetBuilder()
7801 .BlockMode(BlockMode::CBC)
7802 .Padding(PaddingMode::PKCS7)
7803 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007804
7805 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007806 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007807 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007808 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007809 string plaintext;
7810 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7811 ErrorCode error = Finish(&plaintext);
7812 if (error == ErrorCode::INVALID_ARGUMENT) {
7813 // This is the expected error, we can exit the test now.
7814 return;
7815 } else {
7816 // Very small chance we got valid decryption, so try again.
7817 ASSERT_EQ(error, ErrorCode::OK);
7818 }
7819 }
7820 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007821}
7822
7823/*
7824 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7825 *
7826 * Verifies that 3DES CBC works with many different input sizes.
7827 */
7828TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7829 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7830 .TripleDesEncryptionKey(168)
7831 .BlockMode(BlockMode::CBC)
7832 .Authorization(TAG_NO_AUTH_REQUIRED)
7833 .Padding(PaddingMode::NONE)));
7834
7835 int increment = 7;
7836 string message(240, 'a');
7837 AuthorizationSet input_params =
7838 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7839 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007840 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007841
7842 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007843 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007844 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007845 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7846 EXPECT_EQ(message.size(), ciphertext.size());
7847
7848 // Move TAG_NONCE into input_params
7849 input_params = output_params;
7850 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7851 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7852 output_params.Clear();
7853
David Drysdale7fc26b92022-05-13 09:54:24 +01007854 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007855 string plaintext;
7856 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007857 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007858 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7859 EXPECT_EQ(ciphertext.size(), plaintext.size());
7860 EXPECT_EQ(message, plaintext);
7861}
7862
7863INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7864
7865typedef KeyMintAidlTestBase MaxOperationsTest;
7866
7867/*
7868 * MaxOperationsTest.TestLimitAes
7869 *
7870 * Verifies that the max uses per boot tag works correctly with AES keys.
7871 */
7872TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007873 if (SecLevel() == SecurityLevel::STRONGBOX) {
7874 GTEST_SKIP() << "Test not applicable to StrongBox device";
7875 }
Selene Huang31ab4042020-04-29 04:22:39 -07007876
7877 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7878 .Authorization(TAG_NO_AUTH_REQUIRED)
7879 .AesEncryptionKey(128)
7880 .EcbMode()
7881 .Padding(PaddingMode::NONE)
7882 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7883
7884 string message = "1234567890123456";
7885
7886 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7887
7888 EncryptMessage(message, params);
7889 EncryptMessage(message, params);
7890 EncryptMessage(message, params);
7891
7892 // Fourth time should fail.
7893 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7894}
7895
7896/*
Qi Wud22ec842020-11-26 13:27:53 +08007897 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007898 *
7899 * Verifies that the max uses per boot tag works correctly with RSA keys.
7900 */
7901TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007902 if (SecLevel() == SecurityLevel::STRONGBOX) {
7903 GTEST_SKIP() << "Test not applicable to StrongBox device";
7904 }
Selene Huang31ab4042020-04-29 04:22:39 -07007905
7906 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7907 .Authorization(TAG_NO_AUTH_REQUIRED)
7908 .RsaSigningKey(1024, 65537)
7909 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007910 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7911 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007912
7913 string message = "1234567890123456";
7914
7915 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7916
7917 SignMessage(message, params);
7918 SignMessage(message, params);
7919 SignMessage(message, params);
7920
7921 // Fourth time should fail.
7922 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7923}
7924
7925INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7926
Qi Wud22ec842020-11-26 13:27:53 +08007927typedef KeyMintAidlTestBase UsageCountLimitTest;
7928
7929/*
Qi Wubeefae42021-01-28 23:16:37 +08007930 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007931 *
Qi Wubeefae42021-01-28 23:16:37 +08007932 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007933 */
Qi Wubeefae42021-01-28 23:16:37 +08007934TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007935 if (SecLevel() == SecurityLevel::STRONGBOX) {
7936 GTEST_SKIP() << "Test not applicable to StrongBox device";
7937 }
Qi Wud22ec842020-11-26 13:27:53 +08007938
7939 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7940 .Authorization(TAG_NO_AUTH_REQUIRED)
7941 .AesEncryptionKey(128)
7942 .EcbMode()
7943 .Padding(PaddingMode::NONE)
7944 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7945
7946 // Check the usage count limit tag appears in the authorizations.
7947 AuthorizationSet auths;
7948 for (auto& entry : key_characteristics_) {
7949 auths.push_back(AuthorizationSet(entry.authorizations));
7950 }
7951 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7952 << "key usage count limit " << 1U << " missing";
7953
7954 string message = "1234567890123456";
7955 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7956
Qi Wubeefae42021-01-28 23:16:37 +08007957 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7958 AuthorizationSet keystore_auths =
7959 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7960
Qi Wud22ec842020-11-26 13:27:53 +08007961 // First usage of AES key should work.
7962 EncryptMessage(message, params);
7963
Qi Wud22ec842020-11-26 13:27:53 +08007964 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7965 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7966 // must be invalidated from secure storage (such as RPMB partition).
7967 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7968 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007969 // Usage count limit tag is enforced by keystore, keymint does nothing.
7970 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007971 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007972 }
7973}
7974
7975/*
Qi Wubeefae42021-01-28 23:16:37 +08007976 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007977 *
Qi Wubeefae42021-01-28 23:16:37 +08007978 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007979 */
Qi Wubeefae42021-01-28 23:16:37 +08007980TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007981 if (SecLevel() == SecurityLevel::STRONGBOX) {
7982 GTEST_SKIP() << "Test not applicable to StrongBox device";
7983 }
Qi Wubeefae42021-01-28 23:16:37 +08007984
7985 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7986 .Authorization(TAG_NO_AUTH_REQUIRED)
7987 .AesEncryptionKey(128)
7988 .EcbMode()
7989 .Padding(PaddingMode::NONE)
7990 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7991
7992 // Check the usage count limit tag appears in the authorizations.
7993 AuthorizationSet auths;
7994 for (auto& entry : key_characteristics_) {
7995 auths.push_back(AuthorizationSet(entry.authorizations));
7996 }
7997 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7998 << "key usage count limit " << 3U << " missing";
7999
8000 string message = "1234567890123456";
8001 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
8002
8003 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
8004 AuthorizationSet keystore_auths =
8005 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
8006
8007 EncryptMessage(message, params);
8008 EncryptMessage(message, params);
8009 EncryptMessage(message, params);
8010
8011 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
8012 // Usage count limit tag is enforced by hardware. After using the key, the key blob
8013 // must be invalidated from secure storage (such as RPMB partition).
8014 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
8015 } else {
8016 // Usage count limit tag is enforced by keystore, keymint does nothing.
8017 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01008018 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08008019 }
8020}
8021
8022/*
8023 * UsageCountLimitTest.TestSingleUseRsa
8024 *
8025 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
8026 */
8027TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01008028 if (SecLevel() == SecurityLevel::STRONGBOX) {
8029 GTEST_SKIP() << "Test not applicable to StrongBox device";
8030 }
Qi Wud22ec842020-11-26 13:27:53 +08008031
8032 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8033 .Authorization(TAG_NO_AUTH_REQUIRED)
8034 .RsaSigningKey(1024, 65537)
8035 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08008036 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
8037 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08008038
8039 // Check the usage count limit tag appears in the authorizations.
8040 AuthorizationSet auths;
8041 for (auto& entry : key_characteristics_) {
8042 auths.push_back(AuthorizationSet(entry.authorizations));
8043 }
8044 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
8045 << "key usage count limit " << 1U << " missing";
8046
8047 string message = "1234567890123456";
8048 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
8049
Qi Wubeefae42021-01-28 23:16:37 +08008050 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
8051 AuthorizationSet keystore_auths =
8052 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
8053
Qi Wud22ec842020-11-26 13:27:53 +08008054 // First usage of RSA key should work.
8055 SignMessage(message, params);
8056
Qi Wud22ec842020-11-26 13:27:53 +08008057 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
8058 // Usage count limit tag is enforced by hardware. After using the key, the key blob
8059 // must be invalidated from secure storage (such as RPMB partition).
8060 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
8061 } else {
Qi Wubeefae42021-01-28 23:16:37 +08008062 // Usage count limit tag is enforced by keystore, keymint does nothing.
8063 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01008064 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08008065 }
8066}
8067
8068/*
8069 * UsageCountLimitTest.TestLimitUseRsa
8070 *
8071 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
8072 */
8073TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01008074 if (SecLevel() == SecurityLevel::STRONGBOX) {
8075 GTEST_SKIP() << "Test not applicable to StrongBox device";
8076 }
Qi Wubeefae42021-01-28 23:16:37 +08008077
8078 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8079 .Authorization(TAG_NO_AUTH_REQUIRED)
8080 .RsaSigningKey(1024, 65537)
8081 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08008082 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
8083 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08008084
8085 // Check the usage count limit tag appears in the authorizations.
8086 AuthorizationSet auths;
8087 for (auto& entry : key_characteristics_) {
8088 auths.push_back(AuthorizationSet(entry.authorizations));
8089 }
8090 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
8091 << "key usage count limit " << 3U << " missing";
8092
8093 string message = "1234567890123456";
8094 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
8095
8096 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
8097 AuthorizationSet keystore_auths =
8098 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
8099
8100 SignMessage(message, params);
8101 SignMessage(message, params);
8102 SignMessage(message, params);
8103
8104 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
8105 // Usage count limit tag is enforced by hardware. After using the key, the key blob
8106 // must be invalidated from secure storage (such as RPMB partition).
8107 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
8108 } else {
8109 // Usage count limit tag is enforced by keystore, keymint does nothing.
8110 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01008111 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08008112 }
8113}
8114
Qi Wu8e727f72021-02-11 02:49:33 +08008115/*
8116 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
8117 *
8118 * Verifies that when rollback resistance is supported by the KeyMint implementation with
8119 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
8120 * in hardware.
8121 */
8122TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
Qi Wu8e727f72021-02-11 02:49:33 +08008123 auto error = GenerateKey(AuthorizationSetBuilder()
8124 .RsaSigningKey(2048, 65537)
8125 .Digest(Digest::NONE)
8126 .Padding(PaddingMode::NONE)
8127 .Authorization(TAG_NO_AUTH_REQUIRED)
8128 .Authorization(TAG_ROLLBACK_RESISTANCE)
8129 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008130 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8131 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08008132 }
David Drysdale513bf122021-10-06 11:53:13 +01008133
8134 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
8135 ASSERT_EQ(ErrorCode::OK, error);
8136 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8137 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
8138 ASSERT_EQ(ErrorCode::OK, DeleteKey());
8139
8140 // The KeyMint should also enforce single use key in hardware when it supports rollback
8141 // resistance.
8142 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8143 .Authorization(TAG_NO_AUTH_REQUIRED)
8144 .RsaSigningKey(1024, 65537)
8145 .NoDigestOrPadding()
8146 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
8147 .SetDefaultValidity()));
8148
8149 // Check the usage count limit tag appears in the hardware authorizations.
8150 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
8151 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
8152 << "key usage count limit " << 1U << " missing";
8153
8154 string message = "1234567890123456";
8155 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
8156
8157 // First usage of RSA key should work.
8158 SignMessage(message, params);
8159
8160 // Usage count limit tag is enforced by hardware. After using the key, the key blob
8161 // must be invalidated from secure storage (such as RPMB partition).
8162 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08008163}
8164
Qi Wud22ec842020-11-26 13:27:53 +08008165INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
8166
David Drysdale7de9feb2021-03-05 14:56:19 +00008167typedef KeyMintAidlTestBase GetHardwareInfoTest;
8168
8169TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
8170 // Retrieving hardware info should give the same result each time.
8171 KeyMintHardwareInfo info;
8172 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
8173 KeyMintHardwareInfo info2;
8174 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
8175 EXPECT_EQ(info, info2);
8176}
8177
8178INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
8179
Selene Huang31ab4042020-04-29 04:22:39 -07008180typedef KeyMintAidlTestBase AddEntropyTest;
8181
8182/*
8183 * AddEntropyTest.AddEntropy
8184 *
8185 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
8186 * is actually added.
8187 */
8188TEST_P(AddEntropyTest, AddEntropy) {
8189 string data = "foo";
8190 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
8191}
8192
8193/*
8194 * AddEntropyTest.AddEmptyEntropy
8195 *
8196 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
8197 */
8198TEST_P(AddEntropyTest, AddEmptyEntropy) {
8199 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
8200}
8201
8202/*
8203 * AddEntropyTest.AddLargeEntropy
8204 *
8205 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
8206 */
8207TEST_P(AddEntropyTest, AddLargeEntropy) {
8208 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
8209}
8210
David Drysdalebb3d85e2021-04-13 11:15:51 +01008211/*
8212 * AddEntropyTest.AddTooLargeEntropy
8213 *
8214 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
8215 */
8216TEST_P(AddEntropyTest, AddTooLargeEntropy) {
8217 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
8218 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
8219}
8220
Selene Huang31ab4042020-04-29 04:22:39 -07008221INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
8222
Selene Huang31ab4042020-04-29 04:22:39 -07008223typedef KeyMintAidlTestBase KeyDeletionTest;
8224
8225/**
8226 * KeyDeletionTest.DeleteKey
8227 *
8228 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
8229 * valid key blob.
8230 */
8231TEST_P(KeyDeletionTest, DeleteKey) {
8232 auto error = GenerateKey(AuthorizationSetBuilder()
8233 .RsaSigningKey(2048, 65537)
8234 .Digest(Digest::NONE)
8235 .Padding(PaddingMode::NONE)
8236 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008237 .Authorization(TAG_ROLLBACK_RESISTANCE)
8238 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008239 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8240 GTEST_SKIP() << "Rollback resistance not supported";
8241 }
Selene Huang31ab4042020-04-29 04:22:39 -07008242
8243 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008244 ASSERT_EQ(ErrorCode::OK, error);
8245 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8246 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008247
David Drysdale513bf122021-10-06 11:53:13 +01008248 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07008249
David Drysdale513bf122021-10-06 11:53:13 +01008250 string message = "12345678901234567890123456789012";
8251 AuthorizationSet begin_out_params;
8252 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8253 Begin(KeyPurpose::SIGN, key_blob_,
8254 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8255 &begin_out_params));
8256 AbortIfNeeded();
8257 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008258}
8259
8260/**
8261 * KeyDeletionTest.DeleteInvalidKey
8262 *
8263 * This test checks that the HAL excepts invalid key blobs..
8264 */
8265TEST_P(KeyDeletionTest, DeleteInvalidKey) {
8266 // Generate key just to check if rollback protection is implemented
8267 auto error = GenerateKey(AuthorizationSetBuilder()
8268 .RsaSigningKey(2048, 65537)
8269 .Digest(Digest::NONE)
8270 .Padding(PaddingMode::NONE)
8271 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008272 .Authorization(TAG_ROLLBACK_RESISTANCE)
8273 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008274 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8275 GTEST_SKIP() << "Rollback resistance not supported";
8276 }
Selene Huang31ab4042020-04-29 04:22:39 -07008277
8278 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008279 ASSERT_EQ(ErrorCode::OK, error);
8280 AuthorizationSet enforced(SecLevelAuthorizations());
8281 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008282
David Drysdale513bf122021-10-06 11:53:13 +01008283 // Delete the key we don't care about the result at this point.
8284 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07008285
David Drysdale513bf122021-10-06 11:53:13 +01008286 // Now create an invalid key blob and delete it.
8287 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07008288
David Drysdale513bf122021-10-06 11:53:13 +01008289 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07008290}
8291
8292/**
8293 * KeyDeletionTest.DeleteAllKeys
8294 *
8295 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
8296 *
8297 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
8298 * FBE/FDE encryption keys, which means that the device will not even boot until after the
8299 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
8300 * been provisioned. Use this test only on dedicated testing devices that have no valuable
8301 * credentials stored in Keystore/Keymint.
8302 */
8303TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01008304 if (!arm_deleteAllKeys) {
8305 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
8306 return;
8307 }
Victor Hsiehff635632024-12-05 18:50:40 +00008308 // This test was introduced in API level 36, but is not version guarded because it requires a
8309 // manual opt-in anyway. This makes it easier to run on older devices.
Selene Huang31ab4042020-04-29 04:22:39 -07008310 auto error = GenerateKey(AuthorizationSetBuilder()
8311 .RsaSigningKey(2048, 65537)
8312 .Digest(Digest::NONE)
8313 .Padding(PaddingMode::NONE)
8314 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06008315 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008316 ASSERT_EQ(ErrorCode::OK, error);
Selene Huang31ab4042020-04-29 04:22:39 -07008317
David Drysdale513bf122021-10-06 11:53:13 +01008318 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07008319
David Drysdale513bf122021-10-06 11:53:13 +01008320 string message = "12345678901234567890123456789012";
8321 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07008322
David Drysdale513bf122021-10-06 11:53:13 +01008323 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8324 Begin(KeyPurpose::SIGN, key_blob_,
8325 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8326 &begin_out_params));
8327 AbortIfNeeded();
8328 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008329}
8330
8331INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8332
David Drysdaled2cc8c22021-04-15 13:29:45 +01008333typedef KeyMintAidlTestBase KeyUpgradeTest;
8334
8335/**
8336 * KeyUpgradeTest.UpgradeInvalidKey
8337 *
8338 * This test checks that the HAL excepts invalid key blobs..
8339 */
8340TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8341 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8342
8343 std::vector<uint8_t> new_blob;
8344 Status result = keymint_->upgradeKey(key_blob,
8345 AuthorizationSetBuilder()
8346 .Authorization(TAG_APPLICATION_ID, "clientid")
8347 .Authorization(TAG_APPLICATION_DATA, "appdata")
8348 .vector_data(),
8349 &new_blob);
8350 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8351}
8352
8353INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8354
Selene Huang31ab4042020-04-29 04:22:39 -07008355using UpgradeKeyTest = KeyMintAidlTestBase;
8356
8357/*
8358 * UpgradeKeyTest.UpgradeKey
8359 *
8360 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8361 */
8362TEST_P(UpgradeKeyTest, UpgradeKey) {
8363 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8364 .AesEncryptionKey(128)
8365 .Padding(PaddingMode::NONE)
8366 .Authorization(TAG_NO_AUTH_REQUIRED)));
8367
8368 auto result = UpgradeKey(key_blob_);
8369
8370 // Key doesn't need upgrading. Should get okay, but no new key blob.
8371 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8372}
8373
8374INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8375
8376using ClearOperationsTest = KeyMintAidlTestBase;
8377
8378/*
8379 * ClearSlotsTest.TooManyOperations
8380 *
8381 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8382 * operations are started without being finished or aborted. Also verifies
8383 * that aborting the operations clears the operations.
8384 *
8385 */
8386TEST_P(ClearOperationsTest, TooManyOperations) {
8387 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8388 .Authorization(TAG_NO_AUTH_REQUIRED)
8389 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008390 .Padding(PaddingMode::NONE)
8391 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008392
8393 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8394 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008395 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008396 AuthorizationSet out_params;
8397 ErrorCode result;
8398 size_t i;
8399
8400 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008401 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008402 if (ErrorCode::OK != result) {
8403 break;
8404 }
8405 }
8406 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8407 // Try again just in case there's a weird overflow bug
8408 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008409 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008410 for (size_t j = 0; j < i; j++) {
8411 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8412 << "Aboort failed for i = " << j << std::endl;
8413 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008414 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008415 AbortIfNeeded();
8416}
8417
8418INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8419
8420typedef KeyMintAidlTestBase TransportLimitTest;
8421
8422/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008423 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008424 *
8425 * Verifies that passing input data to finish succeeds as expected.
8426 */
8427TEST_P(TransportLimitTest, LargeFinishInput) {
8428 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8429 .Authorization(TAG_NO_AUTH_REQUIRED)
8430 .AesEncryptionKey(128)
8431 .BlockMode(BlockMode::ECB)
8432 .Padding(PaddingMode::NONE)));
8433
8434 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008435 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008436 auto cipher_params =
8437 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8438
8439 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008440 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008441
8442 string plain_message = std::string(1 << msg_size, 'x');
8443 string encrypted_message;
8444 auto rc = Finish(plain_message, &encrypted_message);
8445
8446 EXPECT_EQ(ErrorCode::OK, rc);
8447 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8448 << "Encrypt finish returned OK, but did not consume all of the given input";
8449 cipher_params.push_back(out_params);
8450
David Drysdale7fc26b92022-05-13 09:54:24 +01008451 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008452
8453 string decrypted_message;
8454 rc = Finish(encrypted_message, &decrypted_message);
8455 EXPECT_EQ(ErrorCode::OK, rc);
8456 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8457 << "Decrypt finish returned OK, did not consume all of the given input";
8458 }
8459}
8460
8461INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8462
Seth Moored79a0ec2021-12-13 20:03:33 +00008463static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008464 switch (curve) {
8465 case EcCurve::P_224:
8466 return NID_secp224r1;
8467 case EcCurve::P_256:
8468 return NID_X9_62_prime256v1;
8469 case EcCurve::P_384:
8470 return NID_secp384r1;
8471 case EcCurve::P_521:
8472 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008473 case EcCurve::CURVE_25519:
8474 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008475 }
8476}
8477
David Drysdale42fe1892021-10-14 14:43:46 +01008478class KeyAgreementTest : public KeyMintAidlTestBase {
8479 protected:
8480 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8481 std::vector<uint8_t>* localPublicKey) {
8482 // Generate EC key locally (with access to private key material)
8483 if (localCurve == EcCurve::CURVE_25519) {
8484 uint8_t privKeyData[32];
8485 uint8_t pubKeyData[32];
8486 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008487 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8488 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8489 } else {
8490 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8491 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8492 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8493 ASSERT_NE(group, nullptr);
8494 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8495 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8496 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8497 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008498 }
David Drysdalea410b772022-05-09 16:44:13 +01008499
8500 // Get encoded form of the public part of the locally generated key...
8501 unsigned char* p = nullptr;
8502 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8503 ASSERT_GT(localPublicKeySize, 0);
8504 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8505 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8506 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008507 }
8508
8509 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8510 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008511 auto builder = AuthorizationSetBuilder()
8512 .Authorization(TAG_NO_AUTH_REQUIRED)
8513 .Authorization(TAG_EC_CURVE, curve)
8514 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8515 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8516 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8517 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8518 .SetDefaultValidity();
8519 ErrorCode result = GenerateKey(builder);
David Drysdale42fe1892021-10-14 14:43:46 +01008520 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8521 ASSERT_GT(cert_chain_.size(), 0);
8522 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8523 ASSERT_NE(kmKeyCert, nullptr);
8524 // Check that keyAgreement (bit 4) is set in KeyUsage
8525 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8526 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8527 ASSERT_NE(*kmPubKey, nullptr);
8528 if (dump_Attestations) {
8529 for (size_t n = 0; n < cert_chain_.size(); n++) {
8530 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8531 }
8532 }
8533 }
8534
8535 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8536 const std::vector<uint8_t>& localPublicKey) {
8537 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8538 string ZabFromKeyMintStr;
8539 ASSERT_EQ(ErrorCode::OK,
8540 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8541 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8542 vector<uint8_t> ZabFromTest;
8543
8544 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8545 size_t kmPubKeySize = 32;
8546 uint8_t kmPubKeyData[32];
8547 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8548 ASSERT_EQ(kmPubKeySize, 32);
8549
8550 uint8_t localPrivKeyData[32];
8551 size_t localPrivKeySize = 32;
8552 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8553 &localPrivKeySize));
8554 ASSERT_EQ(localPrivKeySize, 32);
8555
8556 uint8_t sharedKey[32];
8557 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8558 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8559 } else {
8560 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8561 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8562 ASSERT_NE(ctx, nullptr);
8563 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8564 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8565 size_t ZabFromTestLen = 0;
8566 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8567 ZabFromTest.resize(ZabFromTestLen);
8568 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8569 }
8570 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8571 }
8572};
8573
David Zeuthene0c40892021-01-08 12:54:11 -05008574/*
8575 * KeyAgreementTest.Ecdh
8576 *
David Drysdale42fe1892021-10-14 14:43:46 +01008577 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008578 */
8579TEST_P(KeyAgreementTest, Ecdh) {
8580 // Because it's possible to use this API with keys on different curves, we
8581 // check all N^2 combinations where N is the number of supported
8582 // curves.
8583 //
8584 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8585 // lot more curves we can be smart about things and just pick |otherCurve| so
8586 // it's not |curve| and that way we end up with only 2*N runs
8587 //
8588 for (auto curve : ValidCurves()) {
8589 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008590 SCOPED_TRACE(testing::Message()
8591 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8592
David Zeuthene0c40892021-01-08 12:54:11 -05008593 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008594 EVP_PKEY_Ptr localPrivKey;
8595 vector<uint8_t> localPublicKey;
8596 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008597
8598 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008599 EVP_PKEY_Ptr kmPubKey;
8600 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008601
8602 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8603 if (curve != localCurve) {
8604 // If the keys are using different curves KeyMint should fail with
8605 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008606 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008607 string ZabFromKeyMintStr;
8608 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008609 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008610 &ZabFromKeyMintStr));
8611
8612 } else {
8613 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008614 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008615 }
8616
8617 CheckedDeleteKey();
8618 }
8619 }
8620}
8621
David Drysdale42fe1892021-10-14 14:43:46 +01008622/*
8623 * KeyAgreementTest.EcdhCurve25519
8624 *
8625 * Verifies that ECDH works for curve25519. This is also covered by the general
8626 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8627 * KeyMint 1.0.
8628 */
8629TEST_P(KeyAgreementTest, EcdhCurve25519) {
8630 if (!Curve25519Supported()) {
8631 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8632 }
8633
8634 // Generate EC key in KeyMint (only access to public key material)
8635 EcCurve curve = EcCurve::CURVE_25519;
8636 EVP_PKEY_Ptr kmPubKey = nullptr;
8637 GenerateKeyMintEcKey(curve, &kmPubKey);
8638
8639 // Generate EC key on same curve locally (with access to private key material).
8640 EVP_PKEY_Ptr privKey;
8641 vector<uint8_t> encodedPublicKey;
8642 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8643
8644 // Agree on a key between local and KeyMint and check it.
8645 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8646
8647 CheckedDeleteKey();
8648}
8649
8650/*
8651 * KeyAgreementTest.EcdhCurve25519Imported
8652 *
8653 * Verifies that ECDH works for an imported curve25519 key.
8654 */
8655TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8656 if (!Curve25519Supported()) {
8657 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8658 }
8659
8660 // Import x25519 key into KeyMint.
8661 EcCurve curve = EcCurve::CURVE_25519;
8662 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8663 .Authorization(TAG_NO_AUTH_REQUIRED)
8664 .EcdsaKey(EcCurve::CURVE_25519)
8665 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8666 .SetDefaultValidity(),
8667 KeyFormat::PKCS8, x25519_pkcs8_key));
8668 ASSERT_GT(cert_chain_.size(), 0);
8669 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8670 ASSERT_NE(kmKeyCert, nullptr);
8671 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8672 ASSERT_NE(kmPubKey.get(), nullptr);
8673
8674 // Expect the import to emit corresponding public key data.
8675 size_t kmPubKeySize = 32;
8676 uint8_t kmPubKeyData[32];
8677 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8678 ASSERT_EQ(kmPubKeySize, 32);
8679 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8680 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8681
8682 // Generate EC key on same curve locally (with access to private key material).
8683 EVP_PKEY_Ptr privKey;
8684 vector<uint8_t> encodedPublicKey;
8685 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8686
8687 // Agree on a key between local and KeyMint and check it.
8688 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8689
8690 CheckedDeleteKey();
8691}
8692
8693/*
8694 * KeyAgreementTest.EcdhCurve25519InvalidSize
8695 *
8696 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8697 */
8698TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8699 if (!Curve25519Supported()) {
8700 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8701 }
8702
8703 // Generate EC key in KeyMint (only access to public key material)
8704 EcCurve curve = EcCurve::CURVE_25519;
8705 EVP_PKEY_Ptr kmPubKey = nullptr;
8706 GenerateKeyMintEcKey(curve, &kmPubKey);
8707
8708 // Generate EC key on same curve locally (with access to private key material).
8709 EVP_PKEY_Ptr privKey;
8710 vector<uint8_t> encodedPublicKey;
8711 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8712
8713 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8714 string ZabFromKeyMintStr;
8715 // Send in an incomplete public key.
8716 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8717 &ZabFromKeyMintStr));
8718
8719 CheckedDeleteKey();
8720}
8721
8722/*
8723 * KeyAgreementTest.EcdhCurve25519Mismatch
8724 *
8725 * Verifies that ECDH fails between curve25519 and other curves.
8726 */
8727TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8728 if (!Curve25519Supported()) {
8729 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8730 }
8731
8732 // Generate EC key in KeyMint (only access to public key material)
8733 EcCurve curve = EcCurve::CURVE_25519;
8734 EVP_PKEY_Ptr kmPubKey = nullptr;
8735 GenerateKeyMintEcKey(curve, &kmPubKey);
8736
8737 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008738 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008739 if (localCurve == curve) {
8740 continue;
8741 }
8742 // Generate EC key on a different curve locally (with access to private key material).
8743 EVP_PKEY_Ptr privKey;
8744 vector<uint8_t> encodedPublicKey;
8745 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8746
David Drysdale7fc26b92022-05-13 09:54:24 +01008747 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008748 string ZabFromKeyMintStr;
8749 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8750 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8751 &ZabFromKeyMintStr));
8752 }
8753
8754 CheckedDeleteKey();
8755}
8756
David Zeuthene0c40892021-01-08 12:54:11 -05008757INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8758
David Drysdaled2cc8c22021-04-15 13:29:45 +01008759using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8760
8761// This is a problematic test, as it can render the device under test permanently unusable.
8762// Re-enable and run at your own risk.
8763TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8764 auto result = DestroyAttestationIds();
David Drysdale0269d492024-11-14 16:51:58 +00008765 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED)
8766 << "unexpected result " << result;
David Drysdaled2cc8c22021-04-15 13:29:45 +01008767}
8768
8769INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8770
Shawn Willdend659c7c2021-02-19 14:51:51 -07008771using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008772
David Drysdaledb0dcf52021-05-18 11:43:31 +01008773/*
8774 * EarlyBootKeyTest.CreateEarlyBootKeys
8775 *
8776 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8777 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008778TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008779 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008780 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8781 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008782 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8783 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8784 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8785 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008786
David Drysdaleadfe6112021-05-27 12:00:53 +01008787 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8788 ASSERT_GT(keyData.blob.size(), 0U);
8789 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8790 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8791 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008792}
8793
David Drysdaledb0dcf52021-05-18 11:43:31 +01008794/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008795 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8796 *
8797 * Verifies that creating an early boot key with attestation succeeds.
8798 */
8799TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8800 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8801 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8802 builder->AttestationChallenge("challenge");
8803 builder->AttestationApplicationId("app_id");
8804 });
David Drysdale1b9febc2023-06-07 13:43:24 +01008805 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8806 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8807 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8808 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
David Drysdaleadfe6112021-05-27 12:00:53 +01008809
8810 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8811 ASSERT_GT(keyData.blob.size(), 0U);
8812 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8813 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8814 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008815}
8816
8817/*
8818 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008819 *
8820 * Verifies that using early boot keys at a later stage fails.
8821 */
8822TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8823 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8824 .Authorization(TAG_NO_AUTH_REQUIRED)
8825 .Authorization(TAG_EARLY_BOOT_ONLY)
8826 .HmacKey(128)
8827 .Digest(Digest::SHA_2_256)
8828 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8829 AuthorizationSet output_params;
8830 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8831 AuthorizationSetBuilder()
8832 .Digest(Digest::SHA_2_256)
8833 .Authorization(TAG_MAC_LENGTH, 256),
8834 &output_params));
8835}
8836
8837/*
8838 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8839 *
8840 * Verifies that importing early boot keys fails.
8841 */
8842TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8843 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8844 .Authorization(TAG_NO_AUTH_REQUIRED)
8845 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008846 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008847 .Digest(Digest::SHA_2_256)
8848 .SetDefaultValidity(),
8849 KeyFormat::PKCS8, ec_256_key));
8850}
8851
David Drysdaled2cc8c22021-04-15 13:29:45 +01008852// 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 +00008853// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8854// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8855// early boot, so you'll have to reboot between runs.
8856TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8857 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8858 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008859 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8860 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8861 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8862 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
8863
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008864 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8865 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8866 EXPECT_TRUE(
8867 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8868 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8869 EXPECT_TRUE(
8870 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8871
8872 // Should be able to use keys, since early boot has not ended
8873 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8874 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8875 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8876 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8877
8878 // End early boot
8879 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8880 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8881
8882 // Should not be able to use already-created keys.
8883 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8884 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8885 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8886 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8887
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008888 // Should not be able to create new keys
David Drysdale1b9febc2023-06-07 13:43:24 +01008889 auto [aesKeyData2, hmacKeyData2, rsaKeyData2, ecdsaKeyData2] =
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008890 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
David Drysdale1b9febc2023-06-07 13:43:24 +01008891 KeyBlobDeleter aes_deleter2(keymint_, aesKeyData2.blob);
8892 KeyBlobDeleter hmac_deleter2(keymint_, hmacKeyData2.blob);
8893 KeyBlobDeleter rsa_deleter2(keymint_, rsaKeyData2.blob);
8894 KeyBlobDeleter ecdsa_deleter2(keymint_, ecdsaKeyData2.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008895}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008896
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008897INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8898
David Drysdaleda0b04c2024-11-07 13:35:43 +00008899using ModuleHashTest = KeyMintAidlTestBase;
8900
8901TEST_P(ModuleHashTest, SetSameValue) {
8902 if (AidlVersion() < 4) {
8903 GTEST_SKIP() << "Module hash only available for >= v4, this device is v" << AidlVersion();
8904 }
8905 auto module_hash = getModuleHash();
8906 ASSERT_TRUE(module_hash.has_value());
8907
8908 // Setting the same value that's already there should work.
8909 vector<KeyParameter> info = {Authorization(TAG_MODULE_HASH, module_hash.value())};
8910 EXPECT_TRUE(keymint_->setAdditionalAttestationInfo(info).isOk());
8911}
8912
8913TEST_P(ModuleHashTest, SetDifferentValue) {
8914 if (AidlVersion() < 4) {
8915 GTEST_SKIP() << "Module hash only available for >= v4, this device is v" << AidlVersion();
8916 }
8917 auto module_hash = getModuleHash();
8918 ASSERT_TRUE(module_hash.has_value());
8919 vector<uint8_t> wrong_hash = module_hash.value();
8920 ASSERT_EQ(wrong_hash.size(), 32);
8921
8922 // Setting a slightly different value should fail.
8923 wrong_hash[0] ^= 0x01;
8924 vector<KeyParameter> info = {Authorization(TAG_MODULE_HASH, wrong_hash)};
8925 EXPECT_EQ(GetReturnErrorCode(keymint_->setAdditionalAttestationInfo(info)),
8926 ErrorCode::MODULE_HASH_ALREADY_SET);
8927}
8928
8929TEST_P(ModuleHashTest, SetUnrelatedTag) {
8930 if (AidlVersion() < 4) {
8931 GTEST_SKIP() << "Module hash only available for >= v4, this device is v" << AidlVersion();
8932 }
8933
8934 // Trying to set an unexpected tag should be silently ignored..
8935 vector<uint8_t> data = {0, 1, 2, 3, 4};
8936 vector<KeyParameter> info = {Authorization(TAG_ROOT_OF_TRUST, data)};
8937 EXPECT_EQ(GetReturnErrorCode(keymint_->setAdditionalAttestationInfo(info)), ErrorCode::OK);
8938}
8939
8940INSTANTIATE_KEYMINT_AIDL_TEST(ModuleHashTest);
8941
Shawn Willden22fb9c12022-06-02 14:04:33 -06008942using VsrRequirementTest = KeyMintAidlTestBase;
8943
Eran Messeri5fe06ea2023-08-02 22:34:24 +01008944// @VsrTest = VSR-3.10-008
Shawn Willden22fb9c12022-06-02 14:04:33 -06008945TEST_P(VsrRequirementTest, Vsr13Test) {
8946 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008947 if (vsr_api_level < __ANDROID_API_T__) {
Shawn Willden22fb9c12022-06-02 14:04:33 -06008948 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8949 }
8950 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8951}
8952
Eran Messeri5fe06ea2023-08-02 22:34:24 +01008953// @VsrTest = VSR-3.10-013.001
Eran Messerib9346f52022-12-15 14:58:34 +00008954TEST_P(VsrRequirementTest, Vsr14Test) {
8955 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008956 if (vsr_api_level < __ANDROID_API_U__) {
Eran Messerib9346f52022-12-15 14:58:34 +00008957 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8958 }
8959 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8960}
8961
David Drysdaleda0b04c2024-11-07 13:35:43 +00008962// @VsrTest = GMS-VSR-3.10-019
8963TEST_P(VsrRequirementTest, Vsr16Test) {
8964 int vsr_api_level = get_vsr_api_level();
8965 if (vsr_api_level <= __ANDROID_API_V__) {
8966 GTEST_SKIP() << "Applies only to VSR API level > 35, this device is: " << vsr_api_level;
8967 }
8968 if (SecLevel() == SecurityLevel::STRONGBOX) {
8969 GTEST_SKIP() << "Applies only to TEE KeyMint, not StrongBox KeyMint";
8970 }
8971 EXPECT_GE(AidlVersion(), 4) << "VSR 16+ requires KeyMint version 4 in TEE";
8972}
8973
Shawn Willden22fb9c12022-06-02 14:04:33 -06008974INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8975
David Drysdale6c9bdb82024-01-23 09:32:04 +00008976class InstanceTest : public testing::Test {
8977 protected:
8978 static void SetUpTestSuite() {
8979 auto params = ::android::getAidlHalInstanceNames(IKeyMintDevice::descriptor);
8980 for (auto& param : params) {
8981 ASSERT_TRUE(AServiceManager_isDeclared(param.c_str()))
8982 << "IKeyMintDevice instance " << param << " found but not declared.";
8983 ::ndk::SpAIBinder binder(AServiceManager_waitForService(param.c_str()));
8984 auto keymint = IKeyMintDevice::fromBinder(binder);
8985 ASSERT_NE(keymint, nullptr) << "Failed to get IKeyMintDevice instance " << param;
8986
8987 KeyMintHardwareInfo info;
8988 ASSERT_TRUE(keymint->getHardwareInfo(&info).isOk());
8989 ASSERT_EQ(keymints_.count(info.securityLevel), 0)
8990 << "There must be exactly one IKeyMintDevice with security level "
8991 << info.securityLevel;
8992
8993 keymints_[info.securityLevel] = std::move(keymint);
8994 }
8995 }
8996
8997 int32_t AidlVersion(shared_ptr<IKeyMintDevice> keymint) {
8998 int32_t version = 0;
8999 auto status = keymint->getInterfaceVersion(&version);
9000 if (!status.isOk()) {
9001 ADD_FAILURE() << "Failed to determine interface version";
9002 }
9003 return version;
9004 }
9005
9006 static std::map<SecurityLevel, shared_ptr<IKeyMintDevice>> keymints_;
9007};
9008
9009std::map<SecurityLevel, shared_ptr<IKeyMintDevice>> InstanceTest::keymints_;
9010
9011// @VsrTest = VSR-3.10-017
9012// Check that the AIDL version advertised by the HAL service matches
9013// the value in the package manager feature version.
9014TEST_F(InstanceTest, AidlVersionInFeature) {
9015 if (is_gsi_image()) {
9016 GTEST_SKIP() << "Versions not required to match under GSI";
9017 }
9018 if (keymints_.count(SecurityLevel::TRUSTED_ENVIRONMENT) == 1) {
9019 auto tee = keymints_.find(SecurityLevel::TRUSTED_ENVIRONMENT)->second;
9020 int32_t tee_aidl_version = AidlVersion(tee) * 100;
9021 std::optional<int32_t> tee_feature_version = keymint_feature_value(/* strongbox */ false);
9022 ASSERT_TRUE(tee_feature_version.has_value());
9023 EXPECT_EQ(tee_aidl_version, tee_feature_version.value());
9024 }
9025 if (keymints_.count(SecurityLevel::STRONGBOX) == 1) {
9026 auto sb = keymints_.find(SecurityLevel::STRONGBOX)->second;
9027 int32_t sb_aidl_version = AidlVersion(sb) * 100;
9028 std::optional<int32_t> sb_feature_version = keymint_feature_value(/* strongbox */ true);
9029 ASSERT_TRUE(sb_feature_version.has_value());
9030 EXPECT_EQ(sb_aidl_version, sb_feature_version.value());
9031 }
9032}
9033
9034// @VsrTest = VSR-3.10-017
9035// Check that if package manager advertises support for KeyMint of a particular version, that
9036// version is present as a HAL service.
9037TEST_F(InstanceTest, FeatureVersionInAidl) {
9038 if (is_gsi_image()) {
9039 GTEST_SKIP() << "Versions not required to match under GSI";
9040 }
9041 std::optional<int32_t> tee_feature_version = keymint_feature_value(/* strongbox */ false);
9042 if (tee_feature_version.has_value() && tee_feature_version.value() >= 100) {
9043 // Feature flag advertises the existence of KeyMint; check it is present.
9044 ASSERT_EQ(keymints_.count(SecurityLevel::TRUSTED_ENVIRONMENT), 1);
9045 auto tee = keymints_.find(SecurityLevel::TRUSTED_ENVIRONMENT)->second;
9046 int32_t tee_aidl_version = AidlVersion(tee) * 100;
9047 EXPECT_EQ(tee_aidl_version, tee_feature_version.value());
9048 }
9049
9050 std::optional<int32_t> sb_feature_version = keymint_feature_value(/* strongbox */ true);
9051 if (sb_feature_version.has_value() && sb_feature_version.value() >= 100) {
9052 // Feature flag advertises the existence of KeyMint; check it is present.
9053 ASSERT_EQ(keymints_.count(SecurityLevel::STRONGBOX), 1);
9054 auto sb = keymints_.find(SecurityLevel::STRONGBOX)->second;
9055 int32_t sb_aidl_version = AidlVersion(sb) * 100;
9056 EXPECT_EQ(sb_aidl_version, sb_feature_version.value());
9057 }
9058}
9059
Janis Danisevskis24c04702020-12-16 18:28:39 -08009060} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07009061
David Drysdale77a86d82024-01-03 11:22:56 +00009062using aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase;
9063
Selene Huang31ab4042020-04-29 04:22:39 -07009064int main(int argc, char** argv) {
9065 ::testing::InitGoogleTest(&argc, argv);
9066 for (int i = 1; i < argc; ++i) {
9067 if (argv[i][0] == '-') {
9068 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
David Drysdale77a86d82024-01-03 11:22:56 +00009069 KeyMintAidlTestBase::arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07009070 }
9071 if (std::string(argv[i]) == "--dump_attestations") {
David Drysdale77a86d82024-01-03 11:22:56 +00009072 KeyMintAidlTestBase::dump_Attestations = true;
Shawn Willden7c130392020-12-21 09:58:22 -07009073 } else {
9074 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07009075 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00009076 if (std::string(argv[i]) == "--skip_boot_pl_check") {
9077 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
9078 // be run in emulated environments that don't have the normal bootloader
9079 // interactions.
9080 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
9081 }
David Drysdale9f5c0c52022-11-03 15:10:16 +00009082 if (std::string(argv[i]) == "--keyblob_dir") {
9083 if (i + 1 >= argc) {
9084 std::cerr << "Missing argument for --keyblob_dir\n";
9085 return 1;
9086 }
David Drysdale77a86d82024-01-03 11:22:56 +00009087 KeyMintAidlTestBase::keyblob_dir = std::string(argv[i + 1]);
David Drysdale9f5c0c52022-11-03 15:10:16 +00009088 ++i;
9089 }
Tommy Chiu025f3c52023-05-15 06:23:44 +00009090 if (std::string(argv[i]) == "--expect_upgrade") {
9091 if (i + 1 >= argc) {
9092 std::cerr << "Missing argument for --expect_upgrade\n";
9093 return 1;
9094 }
9095 std::string arg = argv[i + 1];
David Drysdale77a86d82024-01-03 11:22:56 +00009096 KeyMintAidlTestBase::expect_upgrade =
9097 arg == "yes" ? true
9098 : (arg == "no" ? false : std::optional<bool>(std::nullopt));
9099 if (KeyMintAidlTestBase::expect_upgrade.has_value()) {
9100 std::cout << "expect_upgrade = "
9101 << (KeyMintAidlTestBase::expect_upgrade.value() ? "true" : "false")
9102 << std::endl;
9103 } else {
9104 std::cerr << "Error! Option --expect_upgrade " << arg << " unrecognized"
9105 << std::endl;
9106 }
Tommy Chiu025f3c52023-05-15 06:23:44 +00009107 ++i;
9108 }
Selene Huang31ab4042020-04-29 04:22:39 -07009109 }
9110 }
Shawn Willden08a7e432020-12-11 13:05:27 +00009111 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07009112}