blob: a8f41c3d6ade28b7a000b1107be0e88a28f6a37c [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale37af4b32021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
David Drysdale6c9bdb82024-01-23 09:32:04 +000024#include <map>
Selene Huang31ab4042020-04-29 04:22:39 -070025
David Drysdale42fe1892021-10-14 14:43:46 +010026#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050027#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070028#include <openssl/evp.h>
29#include <openssl/mem.h>
David Drysdalead785f52023-03-27 19:53:01 +010030#include <openssl/x509.h>
David Zeuthene0c40892021-01-08 12:54:11 -050031#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070032
33#include <cutils/properties.h>
34
David Drysdale4dc01072021-04-01 12:17:35 +010035#include <android/binder_manager.h>
36
37#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080038#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070039
Shawn Willden08a7e432020-12-11 13:05:27 +000040#include <keymint_support/key_param_output.h>
41#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070042
43#include "KeyMintAidlTestBase.h"
44
Janis Danisevskis24c04702020-12-16 18:28:39 -080045using aidl::android::hardware::security::keymint::AuthorizationSet;
46using aidl::android::hardware::security::keymint::KeyCharacteristics;
47using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070048
Selene Huang31ab4042020-04-29 04:22:39 -070049namespace std {
50
Janis Danisevskis24c04702020-12-16 18:28:39 -080051using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070052
53template <>
54struct std::equal_to<KeyCharacteristics> {
55 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070056 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070057
Shawn Willden7f424372021-01-10 18:06:50 -070058 // this isn't very efficient. Oh, well.
59 AuthorizationSet a_auths(a.authorizations);
60 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070061
Shawn Willden7f424372021-01-10 18:06:50 -070062 a_auths.Sort();
63 b_auths.Sort();
64
65 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070066 }
67};
68
69} // namespace std
70
Janis Danisevskis24c04702020-12-16 18:28:39 -080071namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000072
Selene Huang31ab4042020-04-29 04:22:39 -070073namespace {
74
David Drysdalefeab5d92022-01-06 15:46:23 +000075// Maximum supported Ed25519 message size.
76const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
77
David Drysdaledbbbe2e2021-12-02 07:44:23 +000078// Whether to check that BOOT_PATCHLEVEL is populated.
79bool check_boot_pl = true;
80
Seth Moore7a55ae32021-06-23 14:28:11 -070081// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000082// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070083// is a small (roughly 1/256) chance that corrupting ciphertext still results
84// in valid PKCS7 padding.
85constexpr size_t kMaxPaddingCorruptionRetries = 8;
86
Selene Huang31ab4042020-04-29 04:22:39 -070087template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000088bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
89 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070090 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080091 if (auto p = authorizationValue(ttag, param)) {
92 return *p == expected_value;
93 }
94 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070095 });
96 return (it != set.end());
97}
98
99template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000100bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -0700101 auto it = std::find_if(set.begin(), set.end(),
102 [&](const KeyParameter& param) { return param.tag == tag; });
103 return (it != set.end());
104}
105
106constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
109 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
110 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
112 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
115 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
120 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
121 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
122
123string hex2str(string a) {
124 string b;
125 size_t num = a.size() / 2;
126 b.resize(num);
127 for (size_t i = 0; i < num; i++) {
128 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
129 }
130 return b;
131}
132
David Drysdaled2cc8c22021-04-15 13:29:45 +0100133string rsa_key = hex2str(
134 // RFC 5208 s5
135 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
136 "020100" // INTEGER length 1 value 0x00 (version)
137 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
138 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
139 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
140 "0500" // NULL (parameters)
141 // } end SEQUENCE (AlgorithmIdentifier)
142 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
143 // RFC 8017 A.1.2
144 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
145 "020100" // INTEGER length 1 value 0x00 (version)
146 "028181" // INTEGER length 0x81 value (modulus) ...
147 "00c6095409047d8634812d5a218176e4"
148 "5c41d60a75b13901f234226cffe77652"
149 "1c5a77b9e389417b71c0b6a44d13afe4"
150 "e4a2805d46c9da2935adb1ff0c1f24ea"
151 "06e62b20d776430a4d435157233c6f91"
152 "6783c30e310fcbd89b85c2d567711697"
153 "85ac12bca244abda72bfb19fc44d27c8"
154 "1e1d92de284f4061edfd99280745ea6d"
155 "25"
156 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
157 "028180" // INTEGER length 0x80 (privateExponent) value...
158 "1be0f04d9cae3718691f035338308e91"
159 "564b55899ffb5084d2460e6630257e05"
160 "b3ceab02972dfabcd6ce5f6ee2589eb6"
161 "7911ed0fac16e43a444b8c861e544a05"
162 "93365772f8baf6b22fc9e3c5f1024b06"
163 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
164 "ace7240290bef16c0b3f7f3cdd64ce3a"
165 "b5912cf6e32f39ab188358afcccd8081"
166 "0241" // INTEGER length 0x41 (prime1)
167 "00e4b49ef50f765d3b24dde01aceaaf1"
168 "30f2c76670a91a61ae08af497b4a82be"
169 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
170 "8c92bfab137fba2285227b83c342ff7c"
171 "55"
172 "0241" // INTEGER length 0x41 (prime2)
173 "00ddabb5839c4c7f6bf3d4183231f005"
174 "b31aa58affdda5c79e4cce217f6bc930"
175 "dbe563d480706c24e9ebfcab28a6cdef"
176 "d324b77e1bf7251b709092c24ff501fd"
177 "91"
178 "0240" // INTEGER length 0x40 (exponent1)
179 "23d4340eda3445d8cd26c14411da6fdc"
180 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
181 "842c1d280405bc2f6c1bea214a1d742a"
182 "b996b35b63a82a5e470fa88dbf823cdd"
183 "0240" // INTEGER length 0x40 (exponent2)
184 "1b7b57449ad30d1518249a5f56bb9829"
185 "4d4b6ac12ffc86940497a5a5837a6cf9"
186 "46262b494526d328c11e1126380fde04"
187 "c24f916dec250892db09a6d77cdba351"
188 "0240" // INTEGER length 0x40 (coefficient)
189 "7762cd8f4d050da56bd591adb515d24d"
190 "7ccd32cca0d05f866d583514bd7324d5"
191 "f33645e8ed8b4a1cb3cc4a1d67987399"
192 "f2a09f5b3fb68c88d5e5d90ac33492d6"
193 // } end SEQUENCE (PrivateKey)
194 // } end SEQUENCE (PrivateKeyInfo)
195);
Selene Huang31ab4042020-04-29 04:22:39 -0700196
Selene Huange5727e62021-04-13 22:41:20 -0700197/*
198 * DER-encoded PKCS#8 format RSA key. Generated using:
199 *
200 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
201 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100202string rsa_2048_key = hex2str(
203 // RFC 5208 s5
204 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
205 "020100" // INTEGER length 1 value 0x00 (version)
206 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
207 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
208 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
209 "0500" // NULL (parameters)
210 // } end SEQUENCE (AlgorithmIdentifier)
211 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
212 // RFC 8017 A.1.2
213 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
214 "020100" // INTEGER length 1 value 0x00 (version)
215 "02820101" // INTEGER length 0x101 value (modulus) ...
216 "00BEBC342B56D443B1299F9A6A7056E8"
217 "0A897E318476A5A18029E63B2ED739A6"
218 "1791D339F58DC763D9D14911F2EDEC38"
219 "3DEE11F6319B44510E7A3ECD9B79B973"
220 "82E49500ACF8117DC89CAF0E621F7775"
221 "6554A2FD4664BFE7AB8B59AB48340DBF"
222 "A27B93B5A81F6ECDEB02D0759307128D"
223 "F3E3BAD4055C8B840216DFAA5700670E"
224 "6C5126F0962FCB70FF308F25049164CC"
225 "F76CC2DA66A7DD9A81A714C2809D6918"
226 "6133D29D84568E892B6FFBF3199BDB14"
227 "383EE224407F190358F111A949552ABA"
228 "6714227D1BD7F6B20DD0CB88F9467B71"
229 "9339F33BFF35B3870B3F62204E4286B0"
230 "948EA348B524544B5F9838F29EE643B0"
231 "79EEF8A713B220D7806924CDF7295070"
232 "C5"
233 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
234 "02820100" // INTEGER length 0x100 (privateExponent) value...
235 "69F377F35F2F584EF075353CCD1CA997"
236 "38DB3DBC7C7FF35F9366CE176DFD1B13"
237 "5AB10030344ABF5FBECF1D4659FDEF1C"
238 "0FC430834BE1BE3911951377BB3D563A"
239 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
240 "2686C7B4B3C09A7B8354133E6F93F790"
241 "D59EAEB92E84C9A4339302CCE28FDF04"
242 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
243 "6AB706645BF074A4E4090D06FB163124"
244 "365FD5EE7A20D350E9958CC30D91326E"
245 "1B292E9EF5DB408EC42DAF737D201497"
246 "04D0A678A0FB5B5446863B099228A352"
247 "D604BA8091A164D01D5AB05397C71EAD"
248 "20BE2A08FC528FE442817809C787FEE4"
249 "AB97F97B9130D022153EDC6EB6CBE7B0"
250 "F8E3473F2E901209B5DB10F93604DB01"
251 "028181" // INTEGER length 0x81 (prime1)
252 "00E83C0998214941EA4F9293F1B77E2E"
253 "99E6CF305FAF358238E126124FEAF2EB"
254 "9724B2EA7B78E6032343821A80E55D1D"
255 "88FB12D220C3F41A56142FEC85796D19"
256 "17F1E8C774F142B67D3D6E7B7E6B4383"
257 "E94DB5929089DBB346D5BDAB40CC2D96"
258 "EE0409475E175C63BF78CFD744136740"
259 "838127EA723FF3FE7FA368C1311B4A4E"
260 "05"
261 "028181" // INTEGER length 0x81 (prime2)
262 "00D240FCC0F5D7715CDE21CB2DC86EA1"
263 "46132EA3B06F61FF2AF54BF38473F59D"
264 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
265 "B1B58C39F95E4798CCBB43E83D0119AC"
266 "F532F359CA743C85199F0286610E2009"
267 "97D7312917179AC9B67558773212EC96"
268 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
269 "94D94E066A0900B7B70E82A44FB30053"
270 "C1"
271 "028181" // INTEGER length 0x81 (exponent1)
272 "00AD15DA1CBD6A492B66851BA8C316D3"
273 "8AB700E2CFDDD926A658003513C54BAA"
274 "152B30021D667D20078F500F8AD3E7F3"
275 "945D74A891ED1A28EAD0FEEAEC8C14A8"
276 "E834CF46A13D1378C99D18940823CFDD"
277 "27EC5810D59339E0C34198AC638E09C8"
278 "7CBB1B634A9864AE9F4D5EB2D53514F6"
279 "7B4CAEC048C8AB849A02E397618F3271"
280 "35"
281 "028180" // INTEGER length 0x80 (exponent2)
282 "1FA2C1A5331880A92D8F3E281C617108"
283 "BF38244F16E352E69ED417C7153F9EC3"
284 "18F211839C643DCF8B4DD67CE2AC312E"
285 "95178D5D952F06B1BF779F4916924B70"
286 "F582A23F11304E02A5E7565AE22A35E7"
287 "4FECC8B6FDC93F92A1A37703E4CF0E63"
288 "783BD02EB716A7ECBBFA606B10B74D01"
289 "579522E7EF84D91FC522292108D902C1"
290 "028180" // INTEGER length 0x80 (coefficient)
291 "796FE3825F9DCC85DF22D58690065D93"
292 "898ACD65C087BEA8DA3A63BF4549B795"
293 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
294 "0D74F40DED8E1102C52152A31B6165F8"
295 "3A6722AECFCC35A493D7634664B888A0"
296 "8D3EB034F12EA28BFEE346E205D33482"
297 "7F778B16ED40872BD29FCB36536B6E93"
298 "FFB06778696B4A9D81BB0A9423E63DE5"
299 // } end SEQUENCE (PrivateKey)
300 // } end SEQUENCE (PrivateKeyInfo)
301);
Selene Huange5727e62021-04-13 22:41:20 -0700302
David Drysdaled2cc8c22021-04-15 13:29:45 +0100303string ec_256_key = hex2str(
304 // RFC 5208 s5
305 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
306 "020100" // INTEGER length 1 value 0 (version)
307 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
308 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
309 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
310 "0608" // OBJECT IDENTIFIER length 8 (param)
311 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
312 // } end SEQUENCE (AlgorithmIdentifier)
313 "046d" // OCTET STRING length 0x6d (privateKey) holding...
314 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
315 "020101" // INTEGER length 1 value 1 (version)
316 "0420" // OCTET STRING length 0x20 (privateKey)
317 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
318 "941eed09366bc03299986481f3a4d859"
319 "a144" // TAG [1] len 0x44 (publicKey) {
320 "03420004bf85d7720d07c25461683bc6"
321 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
322 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
323 "bcc41c6eb00083cf3376d11fd44949e0"
324 "b2183bfe"
325 // } end SEQUENCE (ECPrivateKey)
326 // } end SEQUENCE (PrivateKeyInfo)
327);
Selene Huang31ab4042020-04-29 04:22:39 -0700328
David Drysdaled2cc8c22021-04-15 13:29:45 +0100329string ec_521_key = hex2str(
330 // RFC 5208 s5
331 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
332 "020100" // INTEGER length 1 value 0 (version)
333 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
334 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
335 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
336 "0605" // OBJECT IDENTIFIER length 5 (param)
337 "2B81040023" // 1.3.132.0.35 (secp521r1)
338 // } end SEQUENCE (AlgorithmIdentifier)
339 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
340 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
341 "020101" // INTEGER length 1 value 1 (version)
342 "0442" // OCTET STRING length 0x42 (privateKey)
343 "0011458C586DB5DAA92AFAB03F4FE46A"
344 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
345 "9D18D7D08B5BCFA0E53C75B064AD51C4"
346 "49BAE0258D54B94B1E885DED08ED4FB2"
347 "5CE9"
348 "A18189" // TAG [1] len 0x89 (publicKey) {
349 "03818600040149EC11C6DF0FA122C6A9"
350 "AFD9754A4FA9513A627CA329E349535A"
351 "5629875A8ADFBE27DCB932C051986377"
352 "108D054C28C6F39B6F2C9AF81802F9F3"
353 "26B842FF2E5F3C00AB7635CFB36157FC"
354 "0882D574A10D839C1A0C049DC5E0D775"
355 "E2EE50671A208431BB45E78E70BEFE93"
356 "0DB34818EE4D5C26259F5C6B8E28A652"
357 "950F9F88D7B4B2C9D9"
358 // } end SEQUENCE (ECPrivateKey)
359 // } end SEQUENCE (PrivateKeyInfo)
360);
Selene Huang31ab4042020-04-29 04:22:39 -0700361
David Drysdaled2cc8c22021-04-15 13:29:45 +0100362string ec_256_key_rfc5915 = hex2str(
363 // RFC 5208 s5
364 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
365 "020100" // INTEGER length 1 value 0 (version)
366 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
367 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
368 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
369 "0608" // OBJECT IDENTIFIER length 8 (param)
370 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
371 // } end SEQUENCE (AlgorithmIdentifier)
372 "0479" // OCTET STRING length 0x79 (privateKey) holding...
373 // RFC 5915 s3
374 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
375 "020101" // INTEGER length 1 value 1 (version)
376 "0420" // OCTET STRING length 0x42 (privateKey)
377 "782370a8c8ce5537baadd04dcff079c8"
378 "158cfa9c67b818b38e8d21c9fa750c1d"
379 "a00a" // TAG [0] length 0xa (parameters)
380 "0608" // OBJECT IDENTIFIER length 8
381 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
382 // } end TAG [0]
383 "a144" // TAG [1] length 0x44 (publicKey) {
384 "0342" // BIT STRING length 0x42
385 "00" // no pad bits
386 "04e2cc561ee701da0ad0ef0d176bb0c9"
387 "19d42e79c393fdc1bd6c4010d85cf2cf"
388 "8e68c905464666f98dad4f01573ba810"
389 "78b3428570a439ba3229fbc026c55068"
390 "2f"
391 // } end SEQUENCE (ECPrivateKey)
392 // } end SEQUENCE (PrivateKeyInfo)
393);
Selene Huang31ab4042020-04-29 04:22:39 -0700394
David Drysdaled2cc8c22021-04-15 13:29:45 +0100395string ec_256_key_sec1 = hex2str(
396 // RFC 5208 s5
397 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
398 "020100" // INTEGER length 1 value 0 (version)
399 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
400 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
401 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
402 "0608" // OBJECT IDENTIFIER length 8 (param)
403 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
404 // } end SEQUENCE (AlgorithmIdentifier)
405 "046d" // OCTET STRING length 0x6d (privateKey) holding...
406 // SEC1-v2 C.4
407 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
408 "020101" // INTEGER length 1 value 0x01 (version)
409 "0420" // OCTET STRING length 0x20 (privateKey)
410 "782370a8c8ce5537baadd04dcff079c8"
411 "158cfa9c67b818b38e8d21c9fa750c1d"
412 "a144" // TAG [1] length 0x44 (publicKey) {
413 "0342" // BIT STRING length 0x42
414 "00" // no pad bits
415 "04e2cc561ee701da0ad0ef0d176bb0c9"
416 "19d42e79c393fdc1bd6c4010d85cf2cf"
417 "8e68c905464666f98dad4f01573ba810"
418 "78b3428570a439ba3229fbc026c55068"
419 "2f"
420 // } end TAG [1] (publicKey)
421 // } end SEQUENCE (PrivateKeyInfo)
422);
Selene Huang31ab4042020-04-29 04:22:39 -0700423
David Drysdale42fe1892021-10-14 14:43:46 +0100424/**
425 * Ed25519 key pair generated as follows:
426 * ```
427 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
428 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
429 * Generating a ED25519 private key writing new private key to
430 * 'ed25519_priv.key'
431 * -----
432 * % cat ed25519_priv.key
433 * -----BEGIN PRIVATE KEY-----
434 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
435 * -----END PRIVATE KEY-----
436 * % der2ascii -pem -i ed25519_priv.key
437 * SEQUENCE {
438 * INTEGER { 0 }
439 * SEQUENCE {
440 * # ed25519
441 * OBJECT_IDENTIFIER { 1.3.101.112 }
442 * }
443 * OCTET_STRING {
444 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
445 * }
446 * }
447 * % cat ed25519.pem
448 * -----BEGIN CERTIFICATE-----
449 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
450 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
451 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
452 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
453 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
454 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
455 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
456 * -----END CERTIFICATE-----
457 * % openssl x509 -in ed25519.pem -text -noout
458 * Certificate:
459 * Data:
460 * Version: 3 (0x2)
461 * Serial Number:
462 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
463 * Signature Algorithm: ED25519
464 * Issuer: CN = fake.ed25519.com
465 * Validity
466 * Not Before: Oct 20 08:27:42 2021 GMT
467 * Not After : Sep 20 08:27:42 2023 GMT
468 * Subject: CN = fake.ed25519.com
469 * Subject Public Key Info:
470 * Public Key Algorithm: ED25519
471 * ED25519 Public-Key:
472 * pub:
473 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
474 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
475 * 56:91
476 * X509v3 extensions:
477 * X509v3 Subject Key Identifier:
478 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
479 * X509v3 Authority Key Identifier:
480 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
481 *
482 * X509v3 Basic Constraints: critical
483 * CA:TRUE
484 * Signature Algorithm: ED25519
485 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
486 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
487 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
488 * e7:07:32:60:32:8d:bb:eb:f6:0f
489 * ```
490 */
491string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
492string ed25519_pkcs8_key = hex2str(
493 // RFC 5208 s5
494 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
495 "0201" // INTEGER length 1 (Version)
496 "00" // version 0
497 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
498 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
499 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
500 // } end SEQUENCE (AlgorithmIdentifier)
501 "0422" // OCTET STRING length 0x22 (PrivateKey)
502 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
503 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
504 // } end SEQUENCE (PrivateKeyInfo)
505);
506string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
507
508/**
509 * X25519 key pair generated as follows:
510 * ```
511 * % openssl genpkey -algorithm X25519 > x25519_priv.key
512 * % cat x25519_priv.key
513 * -----BEGIN PRIVATE KEY-----
514 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
515 * -----END PRIVATE KEY-----
516 * % der2ascii -pem -i x25519_priv.key
517 * SEQUENCE {
518 * INTEGER { 0 }
519 * SEQUENCE {
520 * # x25519
521 * OBJECT_IDENTIFIER { 1.3.101.110 }
522 * }
523 * OCTET_STRING {
524 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
525 * }
526 * }
527 * ```
528 */
529
530string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
531string x25519_pkcs8_key = hex2str(
532 // RFC 5208 s5
533 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
534 "0201" // INTEGER length 1 (Version)
535 "00" // version 0
536 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
537 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
538 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
539 "0422" // OCTET STRING length 0x22 (PrivateKey)
540 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
541 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
542string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
543
Selene Huang31ab4042020-04-29 04:22:39 -0700544struct RSA_Delete {
545 void operator()(RSA* p) { RSA_free(p); }
546};
547
Selene Huang31ab4042020-04-29 04:22:39 -0700548std::string make_string(const uint8_t* data, size_t length) {
549 return std::string(reinterpret_cast<const char*>(data), length);
550}
551
552template <size_t N>
553std::string make_string(const uint8_t (&a)[N]) {
554 return make_string(a, N);
555}
556
557class AidlBuf : public vector<uint8_t> {
558 typedef vector<uint8_t> super;
559
560 public:
561 AidlBuf() {}
562 AidlBuf(const super& other) : super(other) {}
563 AidlBuf(super&& other) : super(std::move(other)) {}
564 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
565
566 AidlBuf& operator=(const super& other) {
567 super::operator=(other);
568 return *this;
569 }
570
571 AidlBuf& operator=(super&& other) {
572 super::operator=(std::move(other));
573 return *this;
574 }
575
576 AidlBuf& operator=(const string& other) {
577 resize(other.size());
578 for (size_t i = 0; i < other.size(); ++i) {
579 (*this)[i] = static_cast<uint8_t>(other[i]);
580 }
581 return *this;
582 }
583
584 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
585};
586
David Drysdale4dc01072021-04-01 12:17:35 +0100587string device_suffix(const string& name) {
588 size_t pos = name.find('/');
589 if (pos == string::npos) {
590 return name;
591 }
592 return name.substr(pos + 1);
593}
594
Seth Moore5a0320f2023-03-24 12:29:08 -0700595std::shared_ptr<IRemotelyProvisionedComponent> matching_rp_instance(const std::string& km_name) {
David Drysdale4dc01072021-04-01 12:17:35 +0100596 string km_suffix = device_suffix(km_name);
597
598 vector<string> rp_names =
599 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
600 for (const string& rp_name : rp_names) {
601 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
602 // KeyMint instance, assume they match.
603 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
604 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
Seth Moore5a0320f2023-03-24 12:29:08 -0700605 return IRemotelyProvisionedComponent::fromBinder(binder);
David Drysdale4dc01072021-04-01 12:17:35 +0100606 }
607 }
Seth Moore5a0320f2023-03-24 12:29:08 -0700608 return nullptr;
David Drysdale4dc01072021-04-01 12:17:35 +0100609}
610
Selene Huang31ab4042020-04-29 04:22:39 -0700611} // namespace
612
613class NewKeyGenerationTest : public KeyMintAidlTestBase {
614 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700615 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000616 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
Selene Huang31ab4042020-04-29 04:22:39 -0700617 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700618
Selene Huang31ab4042020-04-29 04:22:39 -0700619 // Check that some unexpected tags/values are NOT present.
620 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
621 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000622 }
623
624 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000625 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
David Drysdale7de9feb2021-03-05 14:56:19 +0000626 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
627 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
628
629 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000630 }
631
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000632 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics,
633 const KeyOrigin expectedKeyOrigin) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000634 // TODO(swillden): Distinguish which params should be in which auth list.
635 AuthorizationSet auths;
636 for (auto& entry : keyCharacteristics) {
637 auths.push_back(AuthorizationSet(entry.authorizations));
638 }
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000639 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, expectedKeyOrigin));
David Drysdale7de9feb2021-03-05 14:56:19 +0000640
641 // Verify that App data, ROT and auth timeout are NOT included.
642 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
643 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700644 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
645
David Drysdaled2cc8c22021-04-15 13:29:45 +0100646 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
647 // never adds it.
648 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
649
David Drysdale7de9feb2021-03-05 14:56:19 +0000650 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700651 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000652 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700653 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700654 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000655 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700656 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000657
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000658 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100659 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
660 EXPECT_TRUE(vendor_pl);
661 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000662
663 // Should include boot patchlevel (but there are some test scenarios where this is not
664 // possible).
665 if (check_boot_pl) {
666 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
667 EXPECT_TRUE(boot_pl);
668 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100669
David Drysdale7de9feb2021-03-05 14:56:19 +0000670 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700671 }
672};
673
674/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000675 * NewKeyGenerationTest.Aes
676 *
677 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
678 * have correct characteristics.
679 */
680TEST_P(NewKeyGenerationTest, Aes) {
681 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
682 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
683 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
684 SCOPED_TRACE(testing::Message()
685 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
686 vector<uint8_t> key_blob;
687 vector<KeyCharacteristics> key_characteristics;
688 auto builder = AuthorizationSetBuilder()
689 .AesEncryptionKey(key_size)
690 .BlockMode(block_mode)
691 .Padding(padding_mode)
692 .SetDefaultValidity();
693 if (block_mode == BlockMode::GCM) {
694 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
695 }
696 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100697 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000698
699 EXPECT_GT(key_blob.size(), 0U);
700 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100701 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000702
703 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
704
705 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
706 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
707 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000708 }
709 }
710 }
711}
712
713/*
714 * NewKeyGenerationTest.AesInvalidSize
715 *
716 * Verifies that specifying an invalid key size for AES key generation returns
717 * UNSUPPORTED_KEY_SIZE.
718 */
719TEST_P(NewKeyGenerationTest, AesInvalidSize) {
720 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
721 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
722 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
723 SCOPED_TRACE(testing::Message()
724 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
725 vector<uint8_t> key_blob;
726 vector<KeyCharacteristics> key_characteristics;
727 auto builder = AuthorizationSetBuilder()
728 .AesEncryptionKey(key_size)
729 .BlockMode(block_mode)
730 .Padding(padding_mode)
731 .SetDefaultValidity();
732 if (block_mode == BlockMode::GCM) {
733 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
734 }
735 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
736 GenerateKey(builder, &key_blob, &key_characteristics));
737 }
738 }
739 }
740
741 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
742 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100743 SCOPED_TRACE(testing::Message() << "AES-unknown-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000744 vector<uint8_t> key_blob;
745 vector<KeyCharacteristics> key_characteristics;
746 // No key size specified
747 auto builder = AuthorizationSetBuilder()
748 .Authorization(TAG_ALGORITHM, Algorithm::AES)
749 .BlockMode(block_mode)
750 .Padding(padding_mode)
751 .SetDefaultValidity();
752 if (block_mode == BlockMode::GCM) {
753 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
754 }
755 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
756 GenerateKey(builder, &key_blob, &key_characteristics));
757 }
758 }
759}
760
761/*
762 * NewKeyGenerationTest.AesInvalidPadding
763 *
764 * Verifies that specifying an invalid padding on AES keys gives a failure
765 * somewhere along the way.
766 */
767TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
768 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
769 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
770 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
771 SCOPED_TRACE(testing::Message()
772 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000773 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800774 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000775 .AesEncryptionKey(key_size)
776 .BlockMode(block_mode)
777 .Padding(padding_mode)
778 .SetDefaultValidity();
779 if (block_mode == BlockMode::GCM) {
780 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
781 }
782
Tommy Chiu3950b452021-05-03 22:01:46 +0800783 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000784 if (result == ErrorCode::OK) {
785 // Key creation was OK but has generated a key that cannot be used.
786 auto params =
787 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800788 if (block_mode == BlockMode::GCM) {
789 params.Authorization(TAG_MAC_LENGTH, 128);
790 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000791 auto result = Begin(KeyPurpose::ENCRYPT, params);
792 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100793 result == ErrorCode::INVALID_KEY_BLOB)
794 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000795 } else {
796 // The KeyMint implementation detected that the generated key
797 // is unusable.
798 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
799 }
800 }
801 }
802 }
803}
804
805/*
806 * NewKeyGenerationTest.AesGcmMissingMinMac
807 *
808 * Verifies that specifying an invalid key size for AES key generation returns
809 * UNSUPPORTED_KEY_SIZE.
810 */
811TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
812 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
813 BlockMode block_mode = BlockMode::GCM;
814 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
815 SCOPED_TRACE(testing::Message()
816 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
817 vector<uint8_t> key_blob;
818 vector<KeyCharacteristics> key_characteristics;
819 // No MIN_MAC_LENGTH provided.
820 auto builder = AuthorizationSetBuilder()
821 .AesEncryptionKey(key_size)
822 .BlockMode(block_mode)
823 .Padding(padding_mode)
824 .SetDefaultValidity();
825 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
826 GenerateKey(builder, &key_blob, &key_characteristics));
827 }
828 }
829}
830
831/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100832 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
833 *
834 * Verifies that specifying an invalid min MAC size for AES key generation returns
835 * UNSUPPORTED_MIN_MAC_LENGTH.
836 */
837TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
838 for (size_t min_mac_len : {88, 136}) {
839 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
840 BlockMode block_mode = BlockMode::GCM;
841 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
842 SCOPED_TRACE(testing::Message()
843 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
844 vector<uint8_t> key_blob;
845 vector<KeyCharacteristics> key_characteristics;
846 auto builder = AuthorizationSetBuilder()
847 .AesEncryptionKey(key_size)
848 .BlockMode(block_mode)
849 .Padding(padding_mode)
850 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
851 .SetDefaultValidity();
852 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
853 GenerateKey(builder, &key_blob, &key_characteristics));
854 }
855 }
856 }
857}
858
859/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000860 * NewKeyGenerationTest.TripleDes
861 *
862 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
863 * have correct characteristics.
864 */
865TEST_P(NewKeyGenerationTest, TripleDes) {
866 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
867 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
868 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
869 SCOPED_TRACE(testing::Message()
870 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
871 vector<uint8_t> key_blob;
872 vector<KeyCharacteristics> key_characteristics;
873 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
874 .TripleDesEncryptionKey(key_size)
875 .BlockMode(block_mode)
876 .Padding(padding_mode)
877 .Authorization(TAG_NO_AUTH_REQUIRED)
878 .SetDefaultValidity(),
879 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100880 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000881
882 EXPECT_GT(key_blob.size(), 0U);
883 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100884 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000885
886 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
887
888 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
889 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
890 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000891 }
892 }
893 }
894}
895
896/*
897 * NewKeyGenerationTest.TripleDesWithAttestation
898 *
899 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
900 * have correct characteristics.
901 *
902 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
903 * put in a certificate) but which isn't an error.
904 */
905TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
906 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
907 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
908 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
909 SCOPED_TRACE(testing::Message()
910 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
911
912 auto challenge = "hello";
913 auto app_id = "foo";
914
915 vector<uint8_t> key_blob;
916 vector<KeyCharacteristics> key_characteristics;
917 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
918 .TripleDesEncryptionKey(key_size)
919 .BlockMode(block_mode)
920 .Padding(padding_mode)
921 .Authorization(TAG_NO_AUTH_REQUIRED)
922 .AttestationChallenge(challenge)
923 .AttestationApplicationId(app_id)
924 .SetDefaultValidity(),
925 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100926 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000927
928 EXPECT_GT(key_blob.size(), 0U);
929 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100930 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000931
932 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
933
934 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
935 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
936 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000937 }
938 }
939 }
940}
941
942/*
943 * NewKeyGenerationTest.TripleDesInvalidSize
944 *
945 * Verifies that specifying an invalid key size for 3-DES key generation returns
946 * UNSUPPORTED_KEY_SIZE.
947 */
948TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
949 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
950 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
951 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
952 SCOPED_TRACE(testing::Message()
953 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
954 vector<uint8_t> key_blob;
955 vector<KeyCharacteristics> key_characteristics;
956 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
957 GenerateKey(AuthorizationSetBuilder()
958 .TripleDesEncryptionKey(key_size)
959 .BlockMode(block_mode)
960 .Padding(padding_mode)
961 .Authorization(TAG_NO_AUTH_REQUIRED)
962 .SetDefaultValidity(),
963 &key_blob, &key_characteristics));
964 }
965 }
966 }
967
968 // Omitting the key size fails.
969 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
970 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
971 SCOPED_TRACE(testing::Message()
972 << "3DES-default-" << block_mode << "-" << padding_mode);
973 vector<uint8_t> key_blob;
974 vector<KeyCharacteristics> key_characteristics;
975 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
976 GenerateKey(AuthorizationSetBuilder()
977 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
978 .BlockMode(block_mode)
979 .Padding(padding_mode)
980 .Authorization(TAG_NO_AUTH_REQUIRED)
981 .SetDefaultValidity(),
982 &key_blob, &key_characteristics));
983 }
984 }
985}
986
987/*
Selene Huang31ab4042020-04-29 04:22:39 -0700988 * NewKeyGenerationTest.Rsa
989 *
990 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
991 * have correct characteristics.
992 */
993TEST_P(NewKeyGenerationTest, Rsa) {
994 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100995 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -0700996 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700997 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700998 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
999 .RsaSigningKey(key_size, 65537)
1000 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001001 .Padding(PaddingMode::NONE)
1002 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001003 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001004 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07001005
1006 ASSERT_GT(key_blob.size(), 0U);
1007 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001008 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001009
Shawn Willden7f424372021-01-10 18:06:50 -07001010 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001011
1012 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1013 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1014 << "Key size " << key_size << "missing";
1015 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
Selene Huang31ab4042020-04-29 04:22:39 -07001016 }
1017}
1018
1019/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001020 * NewKeyGenerationTest.RsaWithMissingValidity
1021 *
1022 * Verifies that keymint returns an error while generating asymmetric key
1023 * without providing NOT_BEFORE and NOT_AFTER parameters.
1024 */
1025TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
Seth Moore7dc1fda2022-12-12 16:56:20 -08001026 if (AidlVersion() < 3) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001027 /*
1028 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1029 * specified for asymmetric key generation. However, this was not
1030 * checked at the time so we can only be strict about checking this for
Seth Mooreec10c482024-01-23 20:37:24 +00001031 * implementations of KeyMint version 3 and above.
Tommy Chiu7d22f602022-11-14 21:03:34 +08001032 */
Seth Mooreec10c482024-01-23 20:37:24 +00001033 GTEST_SKIP() << "Validity strict since KeyMint v3";
Tommy Chiu7d22f602022-11-14 21:03:34 +08001034 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001035 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1036 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1037 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1038
1039 vector<uint8_t> key_blob;
1040 vector<KeyCharacteristics> key_characteristics;
1041 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1042 GenerateKey(AuthorizationSetBuilder()
1043 .RsaSigningKey(2048, 65537)
1044 .Digest(Digest::NONE)
1045 .Padding(PaddingMode::NONE)
1046 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1047 kUndefinedExpirationDateTime),
1048 &key_blob, &key_characteristics));
1049
1050 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1051 GenerateKey(AuthorizationSetBuilder()
1052 .RsaSigningKey(2048, 65537)
1053 .Digest(Digest::NONE)
1054 .Padding(PaddingMode::NONE)
1055 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1056 &key_blob, &key_characteristics));
1057}
1058
1059/*
David Drysdalead785f52023-03-27 19:53:01 +01001060 * NewKeyGenerationTest.RsaWithSpecifiedValidity
1061 *
1062 * Verifies that KeyMint respects specified NOT_BEFORE and NOT_AFTER certificate dates.
1063 */
1064TEST_P(NewKeyGenerationTest, RsaWithSpecifiedValidity) {
1065 vector<uint8_t> key_blob;
1066 vector<KeyCharacteristics> key_characteristics;
Subrahmanyamane1560212023-05-09 04:40:33 +00001067 vector<uint64_t> test_vector_not_before_millis = {
1068 458046000000, /* 1984-07-07T11:00:00Z */
1069 1183806000000, /* 2007-07-07T11:00:00Z */
1070 1924991999000, /* 2030-12-31T23:59:59Z */
1071 3723753599000, /* 2087-12-31T23:59:59Z */
1072 26223868799000, /* 2800-12-31T23:59:59Z */
1073 45157996799000, /* 3400-12-31T23:59:59Z */
1074 60719587199000, /* 3894-02-15T23:59:59Z */
1075 95302051199000, /* 4989-12-31T23:59:59Z */
1076 86182012799000, /* 4700-12-31T23:59:59Z */
1077 111427574399000, /* 5500-12-31T23:59:59Z */
1078 136988668799000, /* 6310-12-31T23:59:59Z */
1079 139828895999000, /* 6400-12-31T23:59:59Z */
1080 169839503999000, /* 7351-12-31T23:59:59Z */
1081 171385804799000, /* 7400-12-31T23:59:59Z */
1082 190320019199000, /* 8000-12-31T23:59:59Z */
1083 193475692799000, /* 8100-12-31T23:59:59Z */
1084 242515209599000, /* 9654-12-31T23:59:59Z */
1085 250219065599000, /* 9899-02-15T23:59:59Z */
1086 };
1087 for (auto notBefore : test_vector_not_before_millis) {
1088 uint64_t notAfter = notBefore + 378691200000 /* 12 years milliseconds*/;
1089 ASSERT_EQ(ErrorCode::OK,
1090 GenerateKey(AuthorizationSetBuilder()
1091 .RsaSigningKey(2048, 65537)
1092 .Digest(Digest::NONE)
1093 .Padding(PaddingMode::NONE)
1094 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, notBefore)
1095 .Authorization(TAG_CERTIFICATE_NOT_AFTER, notAfter),
1096 &key_blob, &key_characteristics));
1097 ASSERT_GT(cert_chain_.size(), 0);
David Drysdalead785f52023-03-27 19:53:01 +01001098
Subrahmanyamane1560212023-05-09 04:40:33 +00001099 X509_Ptr cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1100 ASSERT_TRUE(!!cert.get());
David Drysdalead785f52023-03-27 19:53:01 +01001101
Subrahmanyamane1560212023-05-09 04:40:33 +00001102 const ASN1_TIME* not_before = X509_get0_notBefore(cert.get());
1103 ASSERT_NE(not_before, nullptr);
1104 time_t not_before_time;
1105 ASSERT_EQ(ASN1_TIME_to_time_t(not_before, &not_before_time), 1);
1106 EXPECT_EQ(not_before_time, (notBefore / 1000));
David Drysdalead785f52023-03-27 19:53:01 +01001107
Subrahmanyamane1560212023-05-09 04:40:33 +00001108 const ASN1_TIME* not_after = X509_get0_notAfter(cert.get());
1109 ASSERT_NE(not_after, nullptr);
1110 time_t not_after_time;
1111 ASSERT_EQ(ASN1_TIME_to_time_t(not_after, &not_after_time), 1);
1112 EXPECT_EQ(not_after_time, (notAfter / 1000));
1113 }
David Drysdalead785f52023-03-27 19:53:01 +01001114}
1115
1116/*
Qi Wud22ec842020-11-26 13:27:53 +08001117 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001118 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001119 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1120 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001121 */
1122TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001123 auto challenge = "hello";
1124 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001125
Selene Huang6e46f142021-04-20 19:20:11 -07001126 auto subject = "cert subj 2";
1127 vector<uint8_t> subject_der(make_name_from_str(subject));
1128
1129 uint64_t serial_int = 66;
1130 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1131
Selene Huang4f64c222021-04-13 19:54:36 -07001132 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001133 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001134 vector<uint8_t> key_blob;
1135 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001136 auto builder = AuthorizationSetBuilder()
1137 .RsaSigningKey(key_size, 65537)
1138 .Digest(Digest::NONE)
1139 .Padding(PaddingMode::NONE)
1140 .AttestationChallenge(challenge)
1141 .AttestationApplicationId(app_id)
1142 .Authorization(TAG_NO_AUTH_REQUIRED)
1143 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1144 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1145 .SetDefaultValidity();
1146
1147 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001148 // Strongbox may not support factory provisioned attestation key.
1149 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001150 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1151 result = GenerateKeyWithSelfSignedAttestKey(
1152 AuthorizationSetBuilder()
1153 .RsaKey(key_size, 65537)
1154 .AttestKey()
1155 .SetDefaultValidity(), /* attest key params */
1156 builder, &key_blob, &key_characteristics);
1157 }
subrahmanyaman05642492022-02-05 07:10:56 +00001158 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001159 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001160 KeyBlobDeleter deleter(keymint_, key_blob);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001161 ASSERT_GT(key_blob.size(), 0U);
1162 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001163 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001164
1165 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1166
1167 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1168 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1169 << "Key size " << key_size << "missing";
1170 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1171
David Drysdalea8a888e2022-06-08 12:43:56 +01001172 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001173 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001174 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001175
1176 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1177 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001178 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001179 sw_enforced, hw_enforced, SecLevel(),
1180 cert_chain_[0].encodedCertificate));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001181 }
1182}
1183
1184/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001185 * NewKeyGenerationTest.RsaWithRkpAttestation
David Drysdale4dc01072021-04-01 12:17:35 +01001186 *
Seth Moore7dc1fda2022-12-12 16:56:20 -08001187 * Verifies that keymint can generate all required RSA key sizes using an attestation key
David Drysdale4dc01072021-04-01 12:17:35 +01001188 * that has been generated using an associate IRemotelyProvisionedComponent.
1189 */
Seth Moore7dc1fda2022-12-12 16:56:20 -08001190TEST_P(NewKeyGenerationTest, RsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001191 if (!IsRkpSupportRequired()) {
1192 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001193 }
1194
Seth Moore5a0320f2023-03-24 12:29:08 -07001195 // Check for an IRemotelyProvisionedComponent instance associated with the
1196 // KeyMint instance.
1197 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1198 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1199 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1200 }
1201 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1202 << GetParam();
David Drysdale4dc01072021-04-01 12:17:35 +01001203
1204 // Generate a P-256 keypair to use as an attestation key.
1205 MacedPublicKey macedPubKey;
1206 std::vector<uint8_t> privateKeyBlob;
1207 auto status =
1208 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1209 ASSERT_TRUE(status.isOk());
1210 vector<uint8_t> coseKeyData;
1211 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1212
1213 AttestationKey attestation_key;
1214 attestation_key.keyBlob = std::move(privateKeyBlob);
1215 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1216
1217 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001218 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdale4dc01072021-04-01 12:17:35 +01001219 auto challenge = "hello";
1220 auto app_id = "foo";
1221
1222 vector<uint8_t> key_blob;
1223 vector<KeyCharacteristics> key_characteristics;
1224 ASSERT_EQ(ErrorCode::OK,
1225 GenerateKey(AuthorizationSetBuilder()
1226 .RsaSigningKey(key_size, 65537)
1227 .Digest(Digest::NONE)
1228 .Padding(PaddingMode::NONE)
1229 .AttestationChallenge(challenge)
1230 .AttestationApplicationId(app_id)
1231 .Authorization(TAG_NO_AUTH_REQUIRED)
1232 .SetDefaultValidity(),
1233 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
David Drysdale1b9febc2023-06-07 13:43:24 +01001234 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale4dc01072021-04-01 12:17:35 +01001235
1236 ASSERT_GT(key_blob.size(), 0U);
1237 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001238 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001239
1240 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1241
1242 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1243 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1244 << "Key size " << key_size << "missing";
1245 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1246
1247 // Attestation by itself is not valid (last entry is not self-signed).
1248 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1249
1250 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001251 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001252 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1253 ASSERT_TRUE(key_cert.get());
1254 EVP_PKEY_Ptr signing_pubkey;
1255 p256_pub_key(coseKeyData, &signing_pubkey);
1256 ASSERT_TRUE(signing_pubkey.get());
1257
1258 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1259 << "Verification of attested certificate failed "
1260 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
David Drysdale4dc01072021-04-01 12:17:35 +01001261 }
1262}
1263
1264/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001265 * NewKeyGenerationTest.EcdsaWithRkpAttestation
1266 *
1267 * Verifies that keymint can generate all required ECDSA key sizes using an attestation key
1268 * that has been generated using an associate IRemotelyProvisionedComponent.
1269 */
1270TEST_P(NewKeyGenerationTest, EcdsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001271 if (!IsRkpSupportRequired()) {
1272 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001273 }
1274
Seth Moore5a0320f2023-03-24 12:29:08 -07001275 // Check for an IRemotelyProvisionedComponent instance associated with the
1276 // KeyMint instance.
1277 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1278 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1279 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1280 }
1281 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1282 << GetParam();
Seth Moore7dc1fda2022-12-12 16:56:20 -08001283
1284 // Generate a P-256 keypair to use as an attestation key.
1285 MacedPublicKey macedPubKey;
1286 std::vector<uint8_t> privateKeyBlob;
1287 auto status =
1288 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1289 ASSERT_TRUE(status.isOk());
1290 vector<uint8_t> coseKeyData;
1291 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1292
1293 AttestationKey attestation_key;
1294 attestation_key.keyBlob = std::move(privateKeyBlob);
1295 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1296
1297 for (auto curve : ValidCurves()) {
1298 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
1299 auto challenge = "hello";
1300 auto app_id = "foo";
1301
1302 vector<uint8_t> key_blob;
1303 vector<KeyCharacteristics> key_characteristics;
1304 ASSERT_EQ(ErrorCode::OK,
1305 GenerateKey(AuthorizationSetBuilder()
1306 .EcdsaSigningKey(curve)
1307 .Digest(Digest::NONE)
1308 .AttestationChallenge(challenge)
1309 .AttestationApplicationId(app_id)
1310 .Authorization(TAG_NO_AUTH_REQUIRED)
1311 .SetDefaultValidity(),
1312 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
David Drysdale1b9febc2023-06-07 13:43:24 +01001313 KeyBlobDeleter deleter(keymint_, key_blob);
Seth Moore7dc1fda2022-12-12 16:56:20 -08001314
1315 ASSERT_GT(key_blob.size(), 0U);
1316 CheckBaseParams(key_characteristics);
1317 CheckCharacteristics(key_blob, key_characteristics);
1318
1319 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1320
1321 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1322 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1323
1324 // Attestation by itself is not valid (last entry is not self-signed).
1325 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1326
1327 // The signature over the attested key should correspond to the P256 public key.
1328 ASSERT_GT(cert_chain_.size(), 0);
1329 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1330 ASSERT_TRUE(key_cert.get());
1331 EVP_PKEY_Ptr signing_pubkey;
1332 p256_pub_key(coseKeyData, &signing_pubkey);
1333 ASSERT_TRUE(signing_pubkey.get());
1334
1335 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1336 << "Verification of attested certificate failed "
1337 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Seth Moore7dc1fda2022-12-12 16:56:20 -08001338 }
1339}
1340
1341/*
Selene Huang4f64c222021-04-13 19:54:36 -07001342 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1343 *
1344 * Verifies that keymint attestation for RSA encryption keys with challenge and
1345 * app id is also successful.
1346 */
1347TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1348 auto key_size = 2048;
1349 auto challenge = "hello";
1350 auto app_id = "foo";
1351
Selene Huang6e46f142021-04-20 19:20:11 -07001352 auto subject = "subj 2";
1353 vector<uint8_t> subject_der(make_name_from_str(subject));
1354
1355 uint64_t serial_int = 111166;
1356 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1357
Selene Huang4f64c222021-04-13 19:54:36 -07001358 vector<uint8_t> key_blob;
1359 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001360 auto builder = AuthorizationSetBuilder()
1361 .RsaEncryptionKey(key_size, 65537)
1362 .Padding(PaddingMode::NONE)
1363 .AttestationChallenge(challenge)
1364 .AttestationApplicationId(app_id)
1365 .Authorization(TAG_NO_AUTH_REQUIRED)
1366 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1367 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1368 .SetDefaultValidity();
1369
1370 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001371 // Strongbox may not support factory provisioned attestation key.
1372 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001373 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1374 result = GenerateKeyWithSelfSignedAttestKey(
1375 AuthorizationSetBuilder()
1376 .RsaKey(key_size, 65537)
1377 .AttestKey()
1378 .SetDefaultValidity(), /* attest key params */
1379 builder, &key_blob, &key_characteristics);
1380 }
subrahmanyaman05642492022-02-05 07:10:56 +00001381 }
1382 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001383 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001384
1385 ASSERT_GT(key_blob.size(), 0U);
1386 AuthorizationSet auths;
1387 for (auto& entry : key_characteristics) {
1388 auths.push_back(AuthorizationSet(entry.authorizations));
1389 }
1390
1391 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1392 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1393
1394 // Verify that App data and ROT are NOT included.
1395 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1396 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1397
1398 // Check that some unexpected tags/values are NOT present.
1399 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1400 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1401
1402 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1403
1404 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1405 ASSERT_TRUE(os_ver);
1406 EXPECT_EQ(*os_ver, os_version());
1407
1408 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1409
1410 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1411 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1412 << "Key size " << key_size << "missing";
1413 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1414
David Drysdalea8a888e2022-06-08 12:43:56 +01001415 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001416 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001417 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001418
1419 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1420 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001421 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001422 sw_enforced, hw_enforced, SecLevel(),
1423 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07001424}
1425
1426/*
1427 * NewKeyGenerationTest.RsaWithSelfSign
1428 *
1429 * Verifies that attesting to RSA key generation is successful, and returns
1430 * self signed certificate if no challenge is provided. And signing etc
1431 * works as expected.
1432 */
1433TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001434 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1435 vector<uint8_t> subject_der(make_name_from_str(subject));
1436
1437 uint64_t serial_int = 0;
1438 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1439
Selene Huang4f64c222021-04-13 19:54:36 -07001440 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001441 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang4f64c222021-04-13 19:54:36 -07001442 vector<uint8_t> key_blob;
1443 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001444 ASSERT_EQ(ErrorCode::OK,
1445 GenerateKey(AuthorizationSetBuilder()
1446 .RsaSigningKey(key_size, 65537)
1447 .Digest(Digest::NONE)
1448 .Padding(PaddingMode::NONE)
1449 .Authorization(TAG_NO_AUTH_REQUIRED)
1450 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1451 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1452 .SetDefaultValidity(),
1453 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001454 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001455
1456 ASSERT_GT(key_blob.size(), 0U);
1457 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001458 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001459
1460 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1461
1462 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1463 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1464 << "Key size " << key_size << "missing";
1465 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1466
David Drysdalea8a888e2022-06-08 12:43:56 +01001467 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001468 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001469 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001470 }
1471}
1472
1473/*
1474 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1475 *
1476 * Verifies that attesting to RSA checks for missing app ID.
1477 */
1478TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1479 auto challenge = "hello";
1480 vector<uint8_t> key_blob;
1481 vector<KeyCharacteristics> key_characteristics;
1482
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001483 auto builder = AuthorizationSetBuilder()
1484 .RsaSigningKey(2048, 65537)
1485 .Digest(Digest::NONE)
1486 .Padding(PaddingMode::NONE)
1487 .AttestationChallenge(challenge)
1488 .Authorization(TAG_NO_AUTH_REQUIRED)
1489 .SetDefaultValidity();
1490
1491 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001492 // Strongbox may not support factory provisioned attestation key.
1493 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001494 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1495 result = GenerateKeyWithSelfSignedAttestKey(
1496 AuthorizationSetBuilder()
1497 .RsaKey(2048, 65537)
1498 .AttestKey()
1499 .SetDefaultValidity(), /* attest key params */
1500 builder, &key_blob, &key_characteristics);
1501 }
subrahmanyaman05642492022-02-05 07:10:56 +00001502 }
1503 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001504}
1505
1506/*
1507 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1508 *
1509 * Verifies that attesting to RSA ignores app id if challenge is missing.
1510 */
1511TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1512 auto key_size = 2048;
1513 auto app_id = "foo";
1514
Selene Huang6e46f142021-04-20 19:20:11 -07001515 auto subject = "cert subj 2";
1516 vector<uint8_t> subject_der(make_name_from_str(subject));
1517
1518 uint64_t serial_int = 1;
1519 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1520
Selene Huang4f64c222021-04-13 19:54:36 -07001521 vector<uint8_t> key_blob;
1522 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001523 ASSERT_EQ(ErrorCode::OK,
1524 GenerateKey(AuthorizationSetBuilder()
1525 .RsaSigningKey(key_size, 65537)
1526 .Digest(Digest::NONE)
1527 .Padding(PaddingMode::NONE)
1528 .AttestationApplicationId(app_id)
1529 .Authorization(TAG_NO_AUTH_REQUIRED)
1530 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1531 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1532 .SetDefaultValidity(),
1533 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001534 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001535
1536 ASSERT_GT(key_blob.size(), 0U);
1537 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001538 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001539
1540 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1541
1542 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1543 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1544 << "Key size " << key_size << "missing";
1545 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1546
David Drysdalea8a888e2022-06-08 12:43:56 +01001547 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001548 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001549 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1550 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang4f64c222021-04-13 19:54:36 -07001551}
1552
1553/*
Qi Wud22ec842020-11-26 13:27:53 +08001554 * NewKeyGenerationTest.LimitedUsageRsa
1555 *
1556 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1557 * resulting keys have correct characteristics.
1558 */
1559TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1560 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001561 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wud22ec842020-11-26 13:27:53 +08001562 vector<uint8_t> key_blob;
1563 vector<KeyCharacteristics> key_characteristics;
1564 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1565 .RsaSigningKey(key_size, 65537)
1566 .Digest(Digest::NONE)
1567 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001568 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1569 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001570 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001571 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08001572
1573 ASSERT_GT(key_blob.size(), 0U);
1574 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001575 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001576
1577 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1578
1579 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1580 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1581 << "Key size " << key_size << "missing";
1582 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1583
1584 // Check the usage count limit tag appears in the authorizations.
1585 AuthorizationSet auths;
1586 for (auto& entry : key_characteristics) {
1587 auths.push_back(AuthorizationSet(entry.authorizations));
1588 }
1589 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1590 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08001591 }
1592}
1593
1594/*
Qi Wubeefae42021-01-28 23:16:37 +08001595 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1596 *
1597 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1598 * resulting keys have correct characteristics and attestation.
1599 */
1600TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001601 auto challenge = "hello";
1602 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001603
Selene Huang6e46f142021-04-20 19:20:11 -07001604 auto subject = "cert subj 2";
1605 vector<uint8_t> subject_der(make_name_from_str(subject));
1606
1607 uint64_t serial_int = 66;
1608 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1609
Selene Huang4f64c222021-04-13 19:54:36 -07001610 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001611 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wubeefae42021-01-28 23:16:37 +08001612 vector<uint8_t> key_blob;
1613 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001614 auto builder = AuthorizationSetBuilder()
1615 .RsaSigningKey(key_size, 65537)
1616 .Digest(Digest::NONE)
1617 .Padding(PaddingMode::NONE)
1618 .AttestationChallenge(challenge)
1619 .AttestationApplicationId(app_id)
1620 .Authorization(TAG_NO_AUTH_REQUIRED)
1621 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1622 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1623 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1624 .SetDefaultValidity();
1625
1626 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001627 // Strongbox may not support factory provisioned attestation key.
1628 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001629 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1630 result = GenerateKeyWithSelfSignedAttestKey(
1631 AuthorizationSetBuilder()
1632 .RsaKey(key_size, 65537)
1633 .AttestKey()
1634 .SetDefaultValidity(), /* attest key params */
1635 builder, &key_blob, &key_characteristics);
1636 }
subrahmanyaman05642492022-02-05 07:10:56 +00001637 }
1638 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001639 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wubeefae42021-01-28 23:16:37 +08001640
1641 ASSERT_GT(key_blob.size(), 0U);
1642 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001643 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001644
1645 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1646
1647 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1648 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1649 << "Key size " << key_size << "missing";
1650 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1651
1652 // Check the usage count limit tag appears in the authorizations.
1653 AuthorizationSet auths;
1654 for (auto& entry : key_characteristics) {
1655 auths.push_back(AuthorizationSet(entry.authorizations));
1656 }
1657 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1658 << "key usage count limit " << 1U << " missing";
1659
1660 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001661 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001662 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001663 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001664
1665 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1666 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001667 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001668 sw_enforced, hw_enforced, SecLevel(),
1669 cert_chain_[0].encodedCertificate));
Qi Wubeefae42021-01-28 23:16:37 +08001670 }
1671}
1672
1673/*
Selene Huang31ab4042020-04-29 04:22:39 -07001674 * NewKeyGenerationTest.NoInvalidRsaSizes
1675 *
1676 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1677 */
1678TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1679 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001680 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07001681 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001682 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001683 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1684 GenerateKey(AuthorizationSetBuilder()
1685 .RsaSigningKey(key_size, 65537)
1686 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001687 .Padding(PaddingMode::NONE)
1688 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001689 &key_blob, &key_characteristics));
1690 }
1691}
1692
1693/*
1694 * NewKeyGenerationTest.RsaNoDefaultSize
1695 *
1696 * Verifies that failing to specify a key size for RSA key generation returns
1697 * UNSUPPORTED_KEY_SIZE.
1698 */
1699TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1700 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1701 GenerateKey(AuthorizationSetBuilder()
1702 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1703 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001704 .SigningKey()
1705 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001706}
1707
1708/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001709 * NewKeyGenerationTest.RsaMissingParams
1710 *
1711 * Verifies that omitting optional tags works.
1712 */
1713TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1714 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001715 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdaled2cc8c22021-04-15 13:29:45 +01001716 ASSERT_EQ(ErrorCode::OK,
1717 GenerateKey(
1718 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1719 CheckedDeleteKey();
1720 }
1721}
1722
1723/*
Selene Huang31ab4042020-04-29 04:22:39 -07001724 * NewKeyGenerationTest.Ecdsa
1725 *
David Drysdale42fe1892021-10-14 14:43:46 +01001726 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001727 * have correct characteristics.
1728 */
1729TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001730 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001731 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07001732 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001733 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001734 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001735 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001736 .Digest(Digest::NONE)
1737 .SetDefaultValidity(),
1738 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001739 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07001740 ASSERT_GT(key_blob.size(), 0U);
1741 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001742 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001743
Shawn Willden7f424372021-01-10 18:06:50 -07001744 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001745
1746 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001747 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001748 }
1749}
1750
1751/*
David Drysdale42fe1892021-10-14 14:43:46 +01001752 * NewKeyGenerationTest.EcdsaCurve25519
1753 *
1754 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1755 * has correct characteristics.
1756 */
1757TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1758 if (!Curve25519Supported()) {
1759 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1760 }
1761
1762 EcCurve curve = EcCurve::CURVE_25519;
1763 vector<uint8_t> key_blob;
1764 vector<KeyCharacteristics> key_characteristics;
1765 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1766 .EcdsaSigningKey(curve)
1767 .Digest(Digest::NONE)
1768 .SetDefaultValidity(),
1769 &key_blob, &key_characteristics);
1770 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01001771 KeyBlobDeleter deleter(keymint_, key_blob);
1772
David Drysdale42fe1892021-10-14 14:43:46 +01001773 ASSERT_GT(key_blob.size(), 0U);
1774
1775 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1776 ASSERT_GT(cert_chain_.size(), 0);
1777
1778 CheckBaseParams(key_characteristics);
1779 CheckCharacteristics(key_blob, key_characteristics);
1780
1781 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1782
1783 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1784 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
David Drysdale42fe1892021-10-14 14:43:46 +01001785}
1786
1787/*
1788 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1789 *
1790 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1791 * SIGN and AGREE_KEY.
1792 */
1793TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1794 if (!Curve25519Supported()) {
1795 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1796 }
1797
1798 EcCurve curve = EcCurve::CURVE_25519;
1799 vector<uint8_t> key_blob;
1800 vector<KeyCharacteristics> key_characteristics;
1801 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1802 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1803 .EcdsaSigningKey(curve)
1804 .Digest(Digest::NONE)
1805 .SetDefaultValidity(),
1806 &key_blob, &key_characteristics);
1807 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1808}
1809
1810/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001811 * NewKeyGenerationTest.EcdsaWithMissingValidity
1812 *
1813 * Verifies that keymint returns an error while generating asymmetric key
1814 * without providing NOT_BEFORE and NOT_AFTER parameters.
1815 */
1816TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001817 if (AidlVersion() < 2) {
1818 /*
1819 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1820 * specified for asymmetric key generation. However, this was not
1821 * checked at the time so we can only be strict about checking this for
1822 * implementations of KeyMint version 2 and above.
1823 */
1824 GTEST_SKIP() << "Validity strict since KeyMint v2";
1825 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001826 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1827 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1828 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1829
1830 vector<uint8_t> key_blob;
1831 vector<KeyCharacteristics> key_characteristics;
1832 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1833 GenerateKey(AuthorizationSetBuilder()
1834 .EcdsaSigningKey(EcCurve::P_256)
1835 .Digest(Digest::NONE)
1836 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1837 kUndefinedExpirationDateTime),
1838 &key_blob, &key_characteristics));
1839
1840 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1841 GenerateKey(AuthorizationSetBuilder()
1842 .EcdsaSigningKey(EcCurve::P_256)
1843 .Digest(Digest::NONE)
1844 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1845 &key_blob, &key_characteristics));
1846}
1847
1848/*
Selene Huang4f64c222021-04-13 19:54:36 -07001849 * NewKeyGenerationTest.EcdsaAttestation
1850 *
1851 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1852 * an attestation will be generated.
1853 */
1854TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1855 auto challenge = "hello";
1856 auto app_id = "foo";
1857
Selene Huang6e46f142021-04-20 19:20:11 -07001858 auto subject = "cert subj 2";
1859 vector<uint8_t> subject_der(make_name_from_str(subject));
1860
1861 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1862 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1863
David Drysdaledf09e542021-06-08 15:46:11 +01001864 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001865 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07001866 vector<uint8_t> key_blob;
1867 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001868 auto builder = AuthorizationSetBuilder()
1869 .Authorization(TAG_NO_AUTH_REQUIRED)
1870 .EcdsaSigningKey(curve)
1871 .Digest(Digest::NONE)
1872 .AttestationChallenge(challenge)
1873 .AttestationApplicationId(app_id)
1874 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1875 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1876 .SetDefaultValidity();
1877
1878 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001879 // Strongbox may not support factory provisioned attestation key.
1880 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001881 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1882 result = GenerateKeyWithSelfSignedAttestKey(
1883 AuthorizationSetBuilder()
1884 .EcdsaKey(curve)
1885 .AttestKey()
1886 .SetDefaultValidity(), /* attest key params */
1887 builder, &key_blob, &key_characteristics);
1888 }
subrahmanyaman05642492022-02-05 07:10:56 +00001889 }
1890 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001891 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001892 ASSERT_GT(key_blob.size(), 0U);
1893 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001894 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001895
1896 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1897
1898 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001899 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001900
1901 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1902 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001903 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001904
1905 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1906 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001907 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001908 sw_enforced, hw_enforced, SecLevel(),
1909 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07001910 }
1911}
1912
1913/*
David Drysdale42fe1892021-10-14 14:43:46 +01001914 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1915 *
1916 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1917 * an attestation will be generated.
1918 */
1919TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1920 if (!Curve25519Supported()) {
1921 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1922 }
1923
1924 EcCurve curve = EcCurve::CURVE_25519;
1925 auto challenge = "hello";
1926 auto app_id = "foo";
1927
1928 auto subject = "cert subj 2";
1929 vector<uint8_t> subject_der(make_name_from_str(subject));
1930
1931 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1932 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1933
1934 vector<uint8_t> key_blob;
1935 vector<KeyCharacteristics> key_characteristics;
1936 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1937 .Authorization(TAG_NO_AUTH_REQUIRED)
1938 .EcdsaSigningKey(curve)
1939 .Digest(Digest::NONE)
1940 .AttestationChallenge(challenge)
1941 .AttestationApplicationId(app_id)
1942 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1943 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1944 .SetDefaultValidity(),
1945 &key_blob, &key_characteristics);
1946 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001947 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale42fe1892021-10-14 14:43:46 +01001948 ASSERT_GT(key_blob.size(), 0U);
1949 CheckBaseParams(key_characteristics);
1950 CheckCharacteristics(key_blob, key_characteristics);
1951
1952 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1953
1954 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1955 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1956
1957 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1958 ASSERT_GT(cert_chain_.size(), 0);
1959 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1960
1961 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1962 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1963 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1964 sw_enforced, hw_enforced, SecLevel(),
1965 cert_chain_[0].encodedCertificate));
David Drysdale42fe1892021-10-14 14:43:46 +01001966}
1967
1968/*
David Drysdale37af4b32021-05-14 16:46:59 +01001969 * NewKeyGenerationTest.EcdsaAttestationTags
1970 *
1971 * Verifies that creation of an attested ECDSA key includes various tags in the
1972 * attestation extension.
1973 */
1974TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1975 auto challenge = "hello";
1976 auto app_id = "foo";
1977 auto subject = "cert subj 2";
1978 vector<uint8_t> subject_der(make_name_from_str(subject));
1979 uint64_t serial_int = 0x1010;
1980 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1981 const AuthorizationSetBuilder base_builder =
1982 AuthorizationSetBuilder()
1983 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001984 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001985 .Digest(Digest::NONE)
1986 .AttestationChallenge(challenge)
1987 .AttestationApplicationId(app_id)
1988 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1989 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1990 .SetDefaultValidity();
1991
1992 // Various tags that map to fields in the attestation extension ASN.1 schema.
1993 auto extra_tags = AuthorizationSetBuilder()
1994 .Authorization(TAG_ROLLBACK_RESISTANCE)
1995 .Authorization(TAG_EARLY_BOOT_ONLY)
1996 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1997 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1998 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1999 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
2000 .Authorization(TAG_AUTH_TIMEOUT, 100000)
2001 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
2002 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
2003 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2004 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
2005 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01002006
David Drysdale37af4b32021-05-14 16:46:59 +01002007 for (const KeyParameter& tag : extra_tags) {
2008 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2009 vector<uint8_t> key_blob;
2010 vector<KeyCharacteristics> key_characteristics;
2011 AuthorizationSetBuilder builder = base_builder;
2012 builder.push_back(tag);
2013 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
2014 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
2015 tag.tag == TAG_ROLLBACK_RESISTANCE) {
2016 continue;
2017 }
Seth Mooreb393b082021-07-12 14:18:28 -07002018 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
2019 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01002020 continue;
2021 }
subrahmanyaman05642492022-02-05 07:10:56 +00002022 // Strongbox may not support factory provisioned attestation key.
2023 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002024 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2025 result = GenerateKeyWithSelfSignedAttestKey(
2026 AuthorizationSetBuilder()
2027 .EcdsaKey(EcCurve::P_256)
2028 .AttestKey()
2029 .SetDefaultValidity(), /* attest key params */
2030 builder, &key_blob, &key_characteristics);
2031 }
subrahmanyaman05642492022-02-05 07:10:56 +00002032 }
David Drysdale37af4b32021-05-14 16:46:59 +01002033 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002034 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale37af4b32021-05-14 16:46:59 +01002035 ASSERT_GT(key_blob.size(), 0U);
2036
2037 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2038 ASSERT_GT(cert_chain_.size(), 0);
2039 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2040
2041 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2042 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07002043 // Some tags are optional, so don't require them to be in the enforcements.
2044 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01002045 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
2046 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
2047 }
2048
2049 // Verifying the attestation record will check for the specific tag because
2050 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002051 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2052 hw_enforced, SecLevel(),
2053 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002054 }
2055
David Drysdalec53b7d92021-10-11 12:35:58 +01002056 // Collection of invalid attestation ID tags.
2057 auto invalid_tags =
2058 AuthorizationSetBuilder()
2059 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
2060 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
2061 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
2062 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
2063 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
2064 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
2065 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
2066 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01002067 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01002068 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01002069 vector<uint8_t> key_blob;
2070 vector<KeyCharacteristics> key_characteristics;
2071 AuthorizationSetBuilder builder =
2072 AuthorizationSetBuilder()
2073 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002074 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01002075 .Digest(Digest::NONE)
2076 .AttestationChallenge(challenge)
2077 .AttestationApplicationId(app_id)
2078 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2079 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2080 .SetDefaultValidity();
2081 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002082
2083 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
2084 // Strongbox may not support factory provisioned attestation key.
2085 if (SecLevel() == SecurityLevel::STRONGBOX) {
2086 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2087 error = GenerateKeyWithSelfSignedAttestKey(
2088 AuthorizationSetBuilder()
2089 .EcdsaKey(EcCurve::P_256)
2090 .AttestKey()
2091 .SetDefaultValidity(), /* attest key params */
2092 builder, &key_blob, &key_characteristics);
2093 }
2094 }
David Drysdalec68dc932023-07-06 10:05:12 +01002095
2096 device_id_attestation_check_acceptable_error(tag.tag, error);
David Drysdale37af4b32021-05-14 16:46:59 +01002097 }
2098}
2099
2100/*
David Drysdalec53b7d92021-10-11 12:35:58 +01002101 * NewKeyGenerationTest.EcdsaAttestationIdTags
2102 *
2103 * Verifies that creation of an attested ECDSA key includes various ID tags in the
2104 * attestation extension.
2105 */
2106TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
2107 auto challenge = "hello";
2108 auto app_id = "foo";
2109 auto subject = "cert subj 2";
2110 vector<uint8_t> subject_der(make_name_from_str(subject));
2111 uint64_t serial_int = 0x1010;
2112 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2113 const AuthorizationSetBuilder base_builder =
2114 AuthorizationSetBuilder()
2115 .Authorization(TAG_NO_AUTH_REQUIRED)
2116 .EcdsaSigningKey(EcCurve::P_256)
2117 .Digest(Digest::NONE)
2118 .AttestationChallenge(challenge)
2119 .AttestationApplicationId(app_id)
2120 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2121 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2122 .SetDefaultValidity();
2123
2124 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2125 auto extra_tags = AuthorizationSetBuilder();
Prashant Patil24f75792023-09-07 15:25:14 +00002126 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_BRAND, "brand");
2127 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "device");
2128 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "name");
2129 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer");
2130 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MODEL, "model");
Tri Vo799e4352022-11-07 17:23:50 -08002131 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
David Drysdalec53b7d92021-10-11 12:35:58 +01002132
2133 for (const KeyParameter& tag : extra_tags) {
2134 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2135 vector<uint8_t> key_blob;
2136 vector<KeyCharacteristics> key_characteristics;
2137 AuthorizationSetBuilder builder = base_builder;
2138 builder.push_back(tag);
2139 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002140 // Strongbox may not support factory provisioned attestation key.
2141 if (SecLevel() == SecurityLevel::STRONGBOX) {
2142 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2143 }
Prashant Patil88ad1892022-03-15 16:31:02 +00002144 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2145 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002146 continue;
2147 }
2148 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002149 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdalec53b7d92021-10-11 12:35:58 +01002150 ASSERT_GT(key_blob.size(), 0U);
2151
2152 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2153 ASSERT_GT(cert_chain_.size(), 0);
2154 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2155
2156 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2157 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2158
2159 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2160 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2161 // attestation extension should contain them, so make sure the extra tag is added.
2162 hw_enforced.push_back(tag);
2163
2164 // Verifying the attestation record will check for the specific tag because
2165 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002166 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2167 hw_enforced, SecLevel(),
2168 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002169 }
2170}
2171
2172/*
David Drysdale565ccc72021-10-11 12:49:50 +01002173 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2174 *
2175 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2176 */
2177TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2178 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002179 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002180 auto challenge = "hello";
2181 auto subject = "cert subj 2";
2182 vector<uint8_t> subject_der(make_name_from_str(subject));
2183 uint64_t serial_int = 0x1010;
2184 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002185 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002186 AuthorizationSetBuilder()
2187 .Authorization(TAG_NO_AUTH_REQUIRED)
2188 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2189 .EcdsaSigningKey(EcCurve::P_256)
2190 .Digest(Digest::NONE)
2191 .AttestationChallenge(challenge)
2192 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2193 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2194 .AttestationApplicationId(app_id)
2195 .Authorization(TAG_CREATION_DATETIME, datetime)
2196 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002197 if (reset) {
2198 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2199 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002200 auto result = GenerateKey(builder);
2201 if (SecLevel() == SecurityLevel::STRONGBOX) {
2202 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2203 result = GenerateKeyWithSelfSignedAttestKey(
2204 AuthorizationSetBuilder()
2205 .EcdsaKey(EcCurve::P_256)
2206 .AttestKey()
2207 .SetDefaultValidity(), /* attest key params */
2208 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2209 }
2210 }
2211 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002212 ASSERT_GT(key_blob_.size(), 0U);
2213
2214 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2215 ASSERT_GT(cert_chain_.size(), 0);
2216 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2217
2218 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2219 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2220
2221 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002222 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2223 hw_enforced, SecLevel(),
2224 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002225 EXPECT_GT(unique_id->size(), 0);
2226 CheckedDeleteKey();
2227 };
2228
2229 // Generate unique ID
2230 auto app_id = "foo";
2231 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2232 vector<uint8_t> unique_id;
2233 get_unique_id(app_id, cert_date, &unique_id);
2234
2235 // Generating a new key with the same parameters should give the same unique ID.
2236 vector<uint8_t> unique_id2;
2237 get_unique_id(app_id, cert_date, &unique_id2);
2238 EXPECT_EQ(unique_id, unique_id2);
2239
2240 // Generating a new key with a slightly different date should give the same unique ID.
2241 uint64_t rounded_date = cert_date / 2592000000LLU;
2242 uint64_t min_date = rounded_date * 2592000000LLU;
2243 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2244
2245 vector<uint8_t> unique_id3;
2246 get_unique_id(app_id, min_date, &unique_id3);
2247 EXPECT_EQ(unique_id, unique_id3);
2248
2249 vector<uint8_t> unique_id4;
2250 get_unique_id(app_id, max_date, &unique_id4);
2251 EXPECT_EQ(unique_id, unique_id4);
2252
2253 // A different attestation application ID should yield a different unique ID.
2254 auto app_id2 = "different_foo";
2255 vector<uint8_t> unique_id5;
2256 get_unique_id(app_id2, cert_date, &unique_id5);
2257 EXPECT_NE(unique_id, unique_id5);
2258
2259 // A radically different date should yield a different unique ID.
2260 vector<uint8_t> unique_id6;
2261 get_unique_id(app_id, 1611621648000, &unique_id6);
2262 EXPECT_NE(unique_id, unique_id6);
2263
2264 vector<uint8_t> unique_id7;
2265 get_unique_id(app_id, max_date + 1, &unique_id7);
2266 EXPECT_NE(unique_id, unique_id7);
2267
2268 vector<uint8_t> unique_id8;
2269 get_unique_id(app_id, min_date - 1, &unique_id8);
2270 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002271
2272 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2273 vector<uint8_t> unique_id9;
2274 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2275 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002276}
2277
2278/*
David Drysdale37af4b32021-05-14 16:46:59 +01002279 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2280 *
2281 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2282 */
2283TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2284 auto challenge = "hello";
2285 auto attest_app_id = "foo";
2286 auto subject = "cert subj 2";
2287 vector<uint8_t> subject_der(make_name_from_str(subject));
2288 uint64_t serial_int = 0x1010;
2289 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2290
2291 // Earlier versions of the attestation extension schema included a slot:
2292 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2293 // This should never have been included, and should never be filled in.
2294 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2295 // to confirm that this field never makes it into the attestation extension.
2296 vector<uint8_t> key_blob;
2297 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002298 auto builder = AuthorizationSetBuilder()
2299 .Authorization(TAG_NO_AUTH_REQUIRED)
2300 .EcdsaSigningKey(EcCurve::P_256)
2301 .Digest(Digest::NONE)
2302 .AttestationChallenge(challenge)
2303 .AttestationApplicationId(attest_app_id)
2304 .Authorization(TAG_APPLICATION_ID, "client_id")
2305 .Authorization(TAG_APPLICATION_DATA, "appdata")
2306 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2307 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2308 .SetDefaultValidity();
2309
2310 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002311 // Strongbox may not support factory provisioned attestation key.
2312 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002313 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2314 result = GenerateKeyWithSelfSignedAttestKey(
2315 AuthorizationSetBuilder()
2316 .EcdsaKey(EcCurve::P_256)
2317 .AttestKey()
2318 .SetDefaultValidity(), /* attest key params */
2319 builder, &key_blob, &key_characteristics);
2320 }
subrahmanyaman05642492022-02-05 07:10:56 +00002321 }
David Drysdale37af4b32021-05-14 16:46:59 +01002322 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002323 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale37af4b32021-05-14 16:46:59 +01002324 ASSERT_GT(key_blob.size(), 0U);
2325
2326 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2327 ASSERT_GT(cert_chain_.size(), 0);
2328 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2329
2330 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2331 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002332 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2333 hw_enforced, SecLevel(),
2334 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002335
2336 // Check that the app id is not in the cert.
2337 string app_id = "clientid";
2338 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2339 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2340 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2341 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2342 cert_chain_[0].encodedCertificate.end());
David Drysdale37af4b32021-05-14 16:46:59 +01002343}
2344
2345/*
Selene Huang4f64c222021-04-13 19:54:36 -07002346 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2347 *
2348 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2349 * the key will generate a self signed attestation.
2350 */
2351TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002352 auto subject = "cert subj 2";
2353 vector<uint8_t> subject_der(make_name_from_str(subject));
2354
2355 uint64_t serial_int = 0x123456FFF1234;
2356 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2357
David Drysdaledf09e542021-06-08 15:46:11 +01002358 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002359 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002360 vector<uint8_t> key_blob;
2361 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002362 ASSERT_EQ(ErrorCode::OK,
2363 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002364 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002365 .Digest(Digest::NONE)
2366 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2367 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2368 .SetDefaultValidity(),
2369 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002370 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002371 ASSERT_GT(key_blob.size(), 0U);
2372 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002373 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002374
2375 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2376
2377 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002378 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002379
2380 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2381 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002382 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002383
2384 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2385 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002386 }
2387}
2388
2389/*
2390 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2391 *
2392 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2393 * app id must also be provided or else it will fail.
2394 */
2395TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2396 auto challenge = "hello";
2397 vector<uint8_t> key_blob;
2398 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002399 auto builder = AuthorizationSetBuilder()
2400 .EcdsaSigningKey(EcCurve::P_256)
2401 .Digest(Digest::NONE)
2402 .AttestationChallenge(challenge)
2403 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002404
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002405 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002406 // Strongbox may not support factory provisioned attestation key.
2407 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002408 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2409 result = GenerateKeyWithSelfSignedAttestKey(
2410 AuthorizationSetBuilder()
2411 .EcdsaKey(EcCurve::P_256)
2412 .AttestKey()
2413 .SetDefaultValidity(), /* attest key params */
2414 builder, &key_blob, &key_characteristics);
2415 }
subrahmanyaman05642492022-02-05 07:10:56 +00002416 }
2417 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002418}
2419
2420/*
2421 * NewKeyGenerationTest.EcdsaIgnoreAppId
2422 *
2423 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2424 * any appid will be ignored, and keymint will generate a self sign certificate.
2425 */
2426TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2427 auto app_id = "foo";
2428
David Drysdaledf09e542021-06-08 15:46:11 +01002429 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002430 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002431 vector<uint8_t> key_blob;
2432 vector<KeyCharacteristics> key_characteristics;
2433 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002434 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002435 .Digest(Digest::NONE)
2436 .AttestationApplicationId(app_id)
2437 .SetDefaultValidity(),
2438 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002439 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002440
2441 ASSERT_GT(key_blob.size(), 0U);
2442 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002443 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002444
2445 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2446
2447 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002448 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002449
2450 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2451 ASSERT_EQ(cert_chain_.size(), 1);
2452
2453 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2454 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002455 }
2456}
2457
2458/*
2459 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2460 *
2461 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2462 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2463 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2464 * to specify how many following bytes will be used to encode the length.
2465 */
2466TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2467 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002468 std::vector<uint32_t> app_id_lengths{143, 258};
2469
2470 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002471 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002472 const string app_id(length, 'a');
2473 vector<uint8_t> key_blob;
2474 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002475 auto builder = AuthorizationSetBuilder()
2476 .Authorization(TAG_NO_AUTH_REQUIRED)
2477 .EcdsaSigningKey(EcCurve::P_256)
2478 .Digest(Digest::NONE)
2479 .AttestationChallenge(challenge)
2480 .AttestationApplicationId(app_id)
2481 .SetDefaultValidity();
2482
2483 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002484 // Strongbox may not support factory provisioned attestation key.
2485 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002486 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2487 result = GenerateKeyWithSelfSignedAttestKey(
2488 AuthorizationSetBuilder()
2489 .EcdsaKey(EcCurve::P_256)
2490 .AttestKey()
2491 .SetDefaultValidity(), /* attest key params */
2492 builder, &key_blob, &key_characteristics);
2493 }
subrahmanyaman05642492022-02-05 07:10:56 +00002494 }
2495 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01002496 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002497 ASSERT_GT(key_blob.size(), 0U);
2498 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002499 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002500
2501 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2502
2503 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002504 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002505
2506 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2507 ASSERT_GT(cert_chain_.size(), 0);
2508
2509 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2510 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002511 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002512 sw_enforced, hw_enforced, SecLevel(),
2513 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07002514 }
2515}
2516
2517/*
Qi Wud22ec842020-11-26 13:27:53 +08002518 * NewKeyGenerationTest.LimitedUsageEcdsa
2519 *
2520 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2521 * resulting keys have correct characteristics.
2522 */
2523TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002524 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002525 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002526 vector<uint8_t> key_blob;
2527 vector<KeyCharacteristics> key_characteristics;
2528 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002529 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002530 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002531 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2532 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002533 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002534 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002535
2536 ASSERT_GT(key_blob.size(), 0U);
2537 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002538 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002539
2540 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2541
2542 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002543 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002544
2545 // Check the usage count limit tag appears in the authorizations.
2546 AuthorizationSet auths;
2547 for (auto& entry : key_characteristics) {
2548 auths.push_back(AuthorizationSet(entry.authorizations));
2549 }
2550 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2551 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002552 }
2553}
2554
2555/*
Selene Huang31ab4042020-04-29 04:22:39 -07002556 * NewKeyGenerationTest.EcdsaDefaultSize
2557 *
David Drysdaledf09e542021-06-08 15:46:11 +01002558 * Verifies that failing to specify a curve for EC key generation returns
David Drysdale84b685a2023-08-09 07:00:34 +01002559 * UNSUPPORTED_KEY_SIZE or UNSUPPORTED_EC_CURVE.
Selene Huang31ab4042020-04-29 04:22:39 -07002560 */
2561TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
David Drysdale84b685a2023-08-09 07:00:34 +01002562 auto result = GenerateKey(AuthorizationSetBuilder()
2563 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2564 .SigningKey()
2565 .Digest(Digest::NONE)
2566 .SetDefaultValidity());
2567 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2568 result == ErrorCode::UNSUPPORTED_EC_CURVE)
2569 << "unexpected result " << result;
Selene Huang31ab4042020-04-29 04:22:39 -07002570}
2571
2572/*
David Drysdale42fe1892021-10-14 14:43:46 +01002573 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002574 *
David Drysdale42fe1892021-10-14 14:43:46 +01002575 * Verifies that specifying an invalid curve for EC key generation returns
David Drysdale84b685a2023-08-09 07:00:34 +01002576 * UNSUPPORTED_KEY_SIZE or UNSUPPORTED_EC_CURVE.
Selene Huang31ab4042020-04-29 04:22:39 -07002577 */
David Drysdale42fe1892021-10-14 14:43:46 +01002578TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002579 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002580 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002581 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002582 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002583 auto result = GenerateKey(AuthorizationSetBuilder()
2584 .EcdsaSigningKey(curve)
2585 .Digest(Digest::NONE)
2586 .SetDefaultValidity(),
2587 &key_blob, &key_characteristics);
2588 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
David Drysdale84b685a2023-08-09 07:00:34 +01002589 result == ErrorCode::UNSUPPORTED_EC_CURVE)
2590 << "unexpected result " << result;
Selene Huang31ab4042020-04-29 04:22:39 -07002591 }
2592
David Drysdaledf09e542021-06-08 15:46:11 +01002593 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2594 GenerateKey(AuthorizationSetBuilder()
2595 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2596 .Authorization(TAG_KEY_SIZE, 190)
2597 .SigningKey()
2598 .Digest(Digest::NONE)
2599 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002600}
2601
2602/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002603 * NewKeyGenerationTest.EcdsaMissingCurve
2604 *
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002605 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V3.
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002606 */
2607TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002608 if (AidlVersion() < 3) {
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002609 /*
2610 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2611 * However, this was not checked at the time so we can only be strict about checking this
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002612 * for implementations of KeyMint version 3 and above.
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002613 */
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002614 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v3";
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002615 }
2616 /* If EC_CURVE not provided, generateKey
2617 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2618 */
2619 auto result = GenerateKey(
2620 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2621 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2622 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2623}
2624
2625/*
Selene Huang31ab4042020-04-29 04:22:39 -07002626 * NewKeyGenerationTest.EcdsaMismatchKeySize
2627 *
2628 * Verifies that specifying mismatched key size and curve for EC key generation returns
2629 * INVALID_ARGUMENT.
2630 */
2631TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002632 if (SecLevel() == SecurityLevel::STRONGBOX) {
2633 GTEST_SKIP() << "Test not applicable to StrongBox device";
2634 }
Selene Huang31ab4042020-04-29 04:22:39 -07002635
David Drysdaledf09e542021-06-08 15:46:11 +01002636 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002637 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002638 .Authorization(TAG_KEY_SIZE, 224)
2639 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002640 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002641 .Digest(Digest::NONE)
2642 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002643 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002644}
2645
2646/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002647 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002648 *
2649 * Verifies that keymint does not support any curve designated as unsupported.
2650 */
2651TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2652 Digest digest;
2653 if (SecLevel() == SecurityLevel::STRONGBOX) {
2654 digest = Digest::SHA_2_256;
2655 } else {
2656 digest = Digest::SHA_2_512;
2657 }
2658 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002659 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002660 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2661 .EcdsaSigningKey(curve)
2662 .Digest(digest)
2663 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002664 << "Failed to generate key on curve: " << curve;
2665 CheckedDeleteKey();
2666 }
2667}
2668
2669/*
2670 * NewKeyGenerationTest.Hmac
2671 *
2672 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2673 * characteristics.
2674 */
2675TEST_P(NewKeyGenerationTest, Hmac) {
2676 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002677 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002678 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002679 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002680 constexpr size_t key_size = 128;
2681 ASSERT_EQ(ErrorCode::OK,
2682 GenerateKey(
2683 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2684 TAG_MIN_MAC_LENGTH, 128),
2685 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002686 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07002687
2688 ASSERT_GT(key_blob.size(), 0U);
2689 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002690 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002691
Shawn Willden7f424372021-01-10 18:06:50 -07002692 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2693 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2694 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2695 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002696 }
2697}
2698
2699/*
Selene Huang4f64c222021-04-13 19:54:36 -07002700 * NewKeyGenerationTest.HmacNoAttestation
2701 *
2702 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2703 * and app id are provided.
2704 */
2705TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2706 auto challenge = "hello";
2707 auto app_id = "foo";
2708
2709 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002710 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002711 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 .AttestationChallenge(challenge)
2718 .AttestationApplicationId(app_id)
2719 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2720 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002721 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002722
2723 ASSERT_GT(key_blob.size(), 0U);
2724 ASSERT_EQ(cert_chain_.size(), 0);
2725 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002726 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002727
2728 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2729 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2730 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2731 << "Key size " << key_size << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002732 }
2733}
2734
2735/*
Qi Wud22ec842020-11-26 13:27:53 +08002736 * NewKeyGenerationTest.LimitedUsageHmac
2737 *
2738 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2739 * resulting keys have correct characteristics.
2740 */
2741TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2742 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002743 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002744 vector<uint8_t> key_blob;
2745 vector<KeyCharacteristics> key_characteristics;
2746 constexpr size_t key_size = 128;
2747 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2748 .HmacKey(key_size)
2749 .Digest(digest)
2750 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2751 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2752 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002753 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002754
2755 ASSERT_GT(key_blob.size(), 0U);
2756 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002757 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002758
2759 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2760 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2761 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2762 << "Key size " << key_size << "missing";
2763
2764 // Check the usage count limit tag appears in the authorizations.
2765 AuthorizationSet auths;
2766 for (auto& entry : key_characteristics) {
2767 auths.push_back(AuthorizationSet(entry.authorizations));
2768 }
2769 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2770 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002771 }
2772}
2773
2774/*
Selene Huang31ab4042020-04-29 04:22:39 -07002775 * NewKeyGenerationTest.HmacCheckKeySizes
2776 *
2777 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2778 */
2779TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2780 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002781 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002782 if (key_size < 64 || key_size % 8 != 0) {
2783 // To keep this test from being very slow, we only test a random fraction of
2784 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2785 // them, we expect to run ~40 of them in each run.
2786 if (key_size % 8 == 0 || random() % 10 == 0) {
2787 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2788 GenerateKey(AuthorizationSetBuilder()
2789 .HmacKey(key_size)
2790 .Digest(Digest::SHA_2_256)
2791 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2792 << "HMAC key size " << key_size << " invalid";
2793 }
2794 } else {
2795 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2796 .HmacKey(key_size)
2797 .Digest(Digest::SHA_2_256)
2798 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2799 << "Failed to generate HMAC key of size " << key_size;
2800 CheckedDeleteKey();
2801 }
2802 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002803 if (SecLevel() == SecurityLevel::STRONGBOX) {
2804 // STRONGBOX devices must not support keys larger than 512 bits.
2805 size_t key_size = 520;
2806 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2807 GenerateKey(AuthorizationSetBuilder()
2808 .HmacKey(key_size)
2809 .Digest(Digest::SHA_2_256)
2810 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2811 << "HMAC key size " << key_size << " unexpectedly valid";
2812 }
Selene Huang31ab4042020-04-29 04:22:39 -07002813}
2814
2815/*
2816 * NewKeyGenerationTest.HmacCheckMinMacLengths
2817 *
2818 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2819 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2820 * specific MAC length that failed, so reproducing a failed run will be easy.
2821 */
2822TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2823 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002824 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002825 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2826 // To keep this test from being very long, we only test a random fraction of
2827 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2828 // we expect to run ~17 of them in each run.
2829 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2830 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2831 GenerateKey(AuthorizationSetBuilder()
2832 .HmacKey(128)
2833 .Digest(Digest::SHA_2_256)
2834 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2835 << "HMAC min mac length " << min_mac_length << " invalid.";
2836 }
2837 } else {
2838 EXPECT_EQ(ErrorCode::OK,
2839 GenerateKey(AuthorizationSetBuilder()
2840 .HmacKey(128)
2841 .Digest(Digest::SHA_2_256)
2842 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2843 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2844 CheckedDeleteKey();
2845 }
2846 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002847
2848 // Minimum MAC length must be no more than 512 bits.
2849 size_t min_mac_length = 520;
2850 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2851 GenerateKey(AuthorizationSetBuilder()
2852 .HmacKey(128)
2853 .Digest(Digest::SHA_2_256)
2854 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2855 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002856}
2857
2858/*
2859 * NewKeyGenerationTest.HmacMultipleDigests
2860 *
2861 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2862 */
2863TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002864 if (SecLevel() == SecurityLevel::STRONGBOX) {
2865 GTEST_SKIP() << "Test not applicable to StrongBox device";
2866 }
Selene Huang31ab4042020-04-29 04:22:39 -07002867
2868 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2869 GenerateKey(AuthorizationSetBuilder()
2870 .HmacKey(128)
2871 .Digest(Digest::SHA1)
2872 .Digest(Digest::SHA_2_256)
2873 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2874}
2875
2876/*
2877 * NewKeyGenerationTest.HmacDigestNone
2878 *
2879 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2880 */
2881TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2882 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2883 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2884 128)));
2885
2886 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2887 GenerateKey(AuthorizationSetBuilder()
2888 .HmacKey(128)
2889 .Digest(Digest::NONE)
2890 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2891}
2892
Selene Huang4f64c222021-04-13 19:54:36 -07002893/*
2894 * NewKeyGenerationTest.AesNoAttestation
2895 *
2896 * Verifies that attestation parameters to AES keys are ignored and generateKey
2897 * will succeed.
2898 */
2899TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2900 auto challenge = "hello";
2901 auto app_id = "foo";
2902
2903 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2904 .Authorization(TAG_NO_AUTH_REQUIRED)
2905 .AesEncryptionKey(128)
2906 .EcbMode()
2907 .Padding(PaddingMode::PKCS7)
2908 .AttestationChallenge(challenge)
2909 .AttestationApplicationId(app_id)));
2910
2911 ASSERT_EQ(cert_chain_.size(), 0);
2912}
2913
2914/*
2915 * NewKeyGenerationTest.TripleDesNoAttestation
2916 *
2917 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2918 * will be successful. No attestation should be generated.
2919 */
2920TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2921 auto challenge = "hello";
2922 auto app_id = "foo";
2923
2924 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2925 .TripleDesEncryptionKey(168)
2926 .BlockMode(BlockMode::ECB)
2927 .Authorization(TAG_NO_AUTH_REQUIRED)
2928 .Padding(PaddingMode::NONE)
2929 .AttestationChallenge(challenge)
2930 .AttestationApplicationId(app_id)));
2931 ASSERT_EQ(cert_chain_.size(), 0);
2932}
2933
Selene Huang31ab4042020-04-29 04:22:39 -07002934INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2935
2936typedef KeyMintAidlTestBase SigningOperationsTest;
2937
2938/*
2939 * SigningOperationsTest.RsaSuccess
2940 *
2941 * Verifies that raw RSA signature operations succeed.
2942 */
2943TEST_P(SigningOperationsTest, RsaSuccess) {
2944 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2945 .RsaSigningKey(2048, 65537)
2946 .Digest(Digest::NONE)
2947 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002948 .Authorization(TAG_NO_AUTH_REQUIRED)
2949 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002950 string message = "12345678901234567890123456789012";
2951 string signature = SignMessage(
2952 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002953 LocalVerifyMessage(message, signature,
2954 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2955}
2956
2957/*
2958 * SigningOperationsTest.RsaAllPaddingsAndDigests
2959 *
2960 * Verifies RSA signature/verification for all padding modes and digests.
2961 */
2962TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2963 auto authorizations = AuthorizationSetBuilder()
2964 .Authorization(TAG_NO_AUTH_REQUIRED)
2965 .RsaSigningKey(2048, 65537)
2966 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2967 .Padding(PaddingMode::NONE)
2968 .Padding(PaddingMode::RSA_PSS)
2969 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2970 .SetDefaultValidity();
2971
2972 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2973
2974 string message(128, 'a');
2975 string corrupt_message(message);
2976 ++corrupt_message[corrupt_message.size() / 2];
2977
2978 for (auto padding :
2979 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2980 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002981 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002982 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2983 // Digesting only makes sense with padding.
2984 continue;
2985 }
2986
2987 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2988 // PSS requires digesting.
2989 continue;
2990 }
2991
2992 string signature =
2993 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2994 LocalVerifyMessage(message, signature,
2995 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2996 }
2997 }
Selene Huang31ab4042020-04-29 04:22:39 -07002998}
2999
3000/*
3001 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
3002 *
Shawn Willden7f424372021-01-10 18:06:50 -07003003 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07003004 */
3005TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
3006 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3007 .Authorization(TAG_NO_AUTH_REQUIRED)
3008 .RsaSigningKey(2048, 65537)
3009 .Digest(Digest::NONE)
3010 .Padding(PaddingMode::NONE)
3011 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003012 .Authorization(TAG_APPLICATION_DATA, "appdata")
3013 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003014
3015 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3016
Selene Huang31ab4042020-04-29 04:22:39 -07003017 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3018 Begin(KeyPurpose::SIGN,
3019 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3020 AbortIfNeeded();
3021 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3022 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3023 .Digest(Digest::NONE)
3024 .Padding(PaddingMode::NONE)
3025 .Authorization(TAG_APPLICATION_ID, "clientid")));
3026 AbortIfNeeded();
3027 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3028 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3029 .Digest(Digest::NONE)
3030 .Padding(PaddingMode::NONE)
3031 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3032 AbortIfNeeded();
3033 EXPECT_EQ(ErrorCode::OK,
3034 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3035 .Digest(Digest::NONE)
3036 .Padding(PaddingMode::NONE)
3037 .Authorization(TAG_APPLICATION_DATA, "appdata")
3038 .Authorization(TAG_APPLICATION_ID, "clientid")));
3039 AbortIfNeeded();
3040}
3041
3042/*
3043 * SigningOperationsTest.RsaPssSha256Success
3044 *
3045 * Verifies that RSA-PSS signature operations succeed.
3046 */
3047TEST_P(SigningOperationsTest, RsaPssSha256Success) {
3048 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3049 .RsaSigningKey(2048, 65537)
3050 .Digest(Digest::SHA_2_256)
3051 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003052 .Authorization(TAG_NO_AUTH_REQUIRED)
3053 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003054 // Use large message, which won't work without digesting.
3055 string message(1024, 'a');
3056 string signature = SignMessage(
3057 message,
3058 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
3059}
3060
3061/*
3062 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
3063 *
3064 * Verifies that keymint rejects signature operations that specify a padding mode when the key
3065 * supports only unpadded operations.
3066 */
3067TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
3068 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3069 .RsaSigningKey(2048, 65537)
3070 .Digest(Digest::NONE)
3071 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003072 .Padding(PaddingMode::NONE)
3073 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003074 string message = "12345678901234567890123456789012";
3075 string signature;
3076
3077 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3078 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3079 .Digest(Digest::NONE)
3080 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3081}
3082
3083/*
3084 * SigningOperationsTest.NoUserConfirmation
3085 *
3086 * Verifies that keymint rejects signing operations for keys with
3087 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
3088 * presented.
3089 */
3090TEST_P(SigningOperationsTest, NoUserConfirmation) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08003091 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Subrahmanyamance2bebd2023-04-28 23:37:02 +00003092 .RsaSigningKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003093 .Digest(Digest::NONE)
3094 .Padding(PaddingMode::NONE)
3095 .Authorization(TAG_NO_AUTH_REQUIRED)
3096 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3097 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003098
3099 const string message = "12345678901234567890123456789012";
3100 EXPECT_EQ(ErrorCode::OK,
3101 Begin(KeyPurpose::SIGN,
3102 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3103 string signature;
3104 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3105}
3106
3107/*
3108 * SigningOperationsTest.RsaPkcs1Sha256Success
3109 *
3110 * Verifies that digested RSA-PKCS1 signature operations succeed.
3111 */
3112TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3113 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3114 .RsaSigningKey(2048, 65537)
3115 .Digest(Digest::SHA_2_256)
3116 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003117 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3118 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003119 string message(1024, 'a');
3120 string signature = SignMessage(message, AuthorizationSetBuilder()
3121 .Digest(Digest::SHA_2_256)
3122 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3123}
3124
3125/*
3126 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3127 *
3128 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3129 */
3130TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3131 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3132 .RsaSigningKey(2048, 65537)
3133 .Digest(Digest::NONE)
3134 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003135 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3136 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003137 string message(53, 'a');
3138 string signature = SignMessage(message, AuthorizationSetBuilder()
3139 .Digest(Digest::NONE)
3140 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3141}
3142
3143/*
3144 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3145 *
3146 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3147 * given a too-long message.
3148 */
3149TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3150 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3151 .RsaSigningKey(2048, 65537)
3152 .Digest(Digest::NONE)
3153 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003154 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3155 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003156 string message(257, 'a');
3157
3158 EXPECT_EQ(ErrorCode::OK,
3159 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3160 .Digest(Digest::NONE)
3161 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3162 string signature;
3163 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3164}
3165
3166/*
3167 * SigningOperationsTest.RsaPssSha512TooSmallKey
3168 *
3169 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3170 * used with a key that is too small for the message.
3171 *
3172 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3173 * keymint specification requires that salt_size == digest_size, so the message will be
3174 * digest_size * 2 +
3175 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3176 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3177 * for a 1024-bit key.
3178 */
3179TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003180 if (SecLevel() == SecurityLevel::STRONGBOX) {
3181 GTEST_SKIP() << "Test not applicable to StrongBox device";
3182 }
Selene Huang31ab4042020-04-29 04:22:39 -07003183 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3184 .RsaSigningKey(1024, 65537)
3185 .Digest(Digest::SHA_2_512)
3186 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003187 .Padding(PaddingMode::RSA_PSS)
3188 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003189 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3190 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3191 .Digest(Digest::SHA_2_512)
3192 .Padding(PaddingMode::RSA_PSS)));
3193}
3194
3195/*
3196 * SigningOperationsTest.RsaNoPaddingTooLong
3197 *
3198 * Verifies that raw RSA signature operations fail with the correct error code when
3199 * given a too-long message.
3200 */
3201TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3202 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3203 .RsaSigningKey(2048, 65537)
3204 .Digest(Digest::NONE)
3205 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003206 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3207 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003208 // One byte too long
3209 string message(2048 / 8 + 1, 'a');
3210 ASSERT_EQ(ErrorCode::OK,
3211 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3212 .Digest(Digest::NONE)
3213 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3214 string result;
3215 ErrorCode finish_error_code = Finish(message, &result);
3216 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3217 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3218
3219 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3220 message = string(128 * 1024, 'a');
3221 ASSERT_EQ(ErrorCode::OK,
3222 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3223 .Digest(Digest::NONE)
3224 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3225 finish_error_code = Finish(message, &result);
3226 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3227 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3228}
3229
3230/*
3231 * SigningOperationsTest.RsaAbort
3232 *
3233 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3234 * test, but the behavior should be algorithm and purpose-independent.
3235 */
3236TEST_P(SigningOperationsTest, RsaAbort) {
3237 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3238 .RsaSigningKey(2048, 65537)
3239 .Digest(Digest::NONE)
3240 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003241 .Padding(PaddingMode::NONE)
3242 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003243
3244 ASSERT_EQ(ErrorCode::OK,
3245 Begin(KeyPurpose::SIGN,
3246 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3247 EXPECT_EQ(ErrorCode::OK, Abort());
3248
3249 // Another abort should fail
3250 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3251
3252 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003253 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003254}
3255
3256/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003257 * SigningOperationsTest.RsaNonUniqueParams
3258 *
3259 * Verifies that an operation with multiple padding modes is rejected.
3260 */
3261TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3262 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3263 .RsaSigningKey(2048, 65537)
3264 .Digest(Digest::NONE)
3265 .Digest(Digest::SHA1)
3266 .Authorization(TAG_NO_AUTH_REQUIRED)
3267 .Padding(PaddingMode::NONE)
3268 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3269 .SetDefaultValidity()));
3270
3271 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3272 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3273 .Digest(Digest::NONE)
3274 .Padding(PaddingMode::NONE)
3275 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3276
Tommy Chiuc93c4392021-05-11 18:36:50 +08003277 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3278 .Digest(Digest::NONE)
3279 .Digest(Digest::SHA1)
3280 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3281 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003282
3283 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3284 Begin(KeyPurpose::SIGN,
3285 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3286}
3287
3288/*
Selene Huang31ab4042020-04-29 04:22:39 -07003289 * SigningOperationsTest.RsaUnsupportedPadding
3290 *
3291 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3292 * with a padding mode inappropriate for RSA.
3293 */
3294TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3295 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3296 .RsaSigningKey(2048, 65537)
3297 .Authorization(TAG_NO_AUTH_REQUIRED)
3298 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003299 .Padding(PaddingMode::PKCS7)
3300 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003301 ASSERT_EQ(
3302 ErrorCode::UNSUPPORTED_PADDING_MODE,
3303 Begin(KeyPurpose::SIGN,
3304 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003305 CheckedDeleteKey();
3306
3307 ASSERT_EQ(ErrorCode::OK,
3308 GenerateKey(
3309 AuthorizationSetBuilder()
3310 .RsaSigningKey(2048, 65537)
3311 .Authorization(TAG_NO_AUTH_REQUIRED)
3312 .Digest(Digest::SHA_2_256 /* supported digest */)
3313 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3314 .SetDefaultValidity()));
3315 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3316 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3317 .Digest(Digest::SHA_2_256)
3318 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003319}
3320
3321/*
3322 * SigningOperationsTest.RsaPssNoDigest
3323 *
3324 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3325 */
3326TEST_P(SigningOperationsTest, RsaNoDigest) {
3327 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3328 .RsaSigningKey(2048, 65537)
3329 .Authorization(TAG_NO_AUTH_REQUIRED)
3330 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003331 .Padding(PaddingMode::RSA_PSS)
3332 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003333 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3334 Begin(KeyPurpose::SIGN,
3335 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3336
3337 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3338 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3339}
3340
3341/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003342 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003343 *
3344 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3345 * supported in some cases (as validated in other tests), but a mode must be specified.
3346 */
3347TEST_P(SigningOperationsTest, RsaNoPadding) {
3348 // Padding must be specified
3349 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3350 .RsaKey(2048, 65537)
3351 .Authorization(TAG_NO_AUTH_REQUIRED)
3352 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003353 .Digest(Digest::NONE)
3354 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003355 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3356 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3357}
3358
3359/*
3360 * SigningOperationsTest.RsaShortMessage
3361 *
3362 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3363 */
3364TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3365 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3366 .Authorization(TAG_NO_AUTH_REQUIRED)
3367 .RsaSigningKey(2048, 65537)
3368 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003369 .Padding(PaddingMode::NONE)
3370 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003371
3372 // Barely shorter
3373 string message(2048 / 8 - 1, 'a');
3374 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3375
3376 // Much shorter
3377 message = "a";
3378 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3379}
3380
3381/*
3382 * SigningOperationsTest.RsaSignWithEncryptionKey
3383 *
3384 * Verifies that RSA encryption keys cannot be used to sign.
3385 */
3386TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3387 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3388 .Authorization(TAG_NO_AUTH_REQUIRED)
3389 .RsaEncryptionKey(2048, 65537)
3390 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003391 .Padding(PaddingMode::NONE)
3392 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003393 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3394 Begin(KeyPurpose::SIGN,
3395 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3396}
3397
3398/*
3399 * SigningOperationsTest.RsaSignTooLargeMessage
3400 *
3401 * Verifies that attempting a raw signature of a message which is the same length as the key,
3402 * but numerically larger than the public modulus, fails with the correct error.
3403 */
3404TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3405 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3406 .Authorization(TAG_NO_AUTH_REQUIRED)
3407 .RsaSigningKey(2048, 65537)
3408 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003409 .Padding(PaddingMode::NONE)
3410 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003411
3412 // Largest possible message will always be larger than the public modulus.
3413 string message(2048 / 8, static_cast<char>(0xff));
3414 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3415 .Authorization(TAG_NO_AUTH_REQUIRED)
3416 .Digest(Digest::NONE)
3417 .Padding(PaddingMode::NONE)));
3418 string signature;
3419 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3420}
3421
3422/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003423 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3424 *
David Drysdale42fe1892021-10-14 14:43:46 +01003425 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003426 */
3427TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003428 string message = "1234567890";
3429 string corrupt_message = "2234567890";
3430 for (auto curve : ValidCurves()) {
3431 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003432 // Ed25519 only allows Digest::NONE.
3433 auto digests = (curve == EcCurve::CURVE_25519)
3434 ? std::vector<Digest>(1, Digest::NONE)
3435 : ValidDigests(true /* withNone */, false /* withMD5 */);
3436
David Drysdaledf8f52e2021-05-06 08:10:58 +01003437 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3438 .Authorization(TAG_NO_AUTH_REQUIRED)
3439 .EcdsaSigningKey(curve)
3440 .Digest(digests)
3441 .SetDefaultValidity());
3442 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3443 if (error != ErrorCode::OK) {
3444 continue;
3445 }
3446
3447 for (auto digest : digests) {
3448 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3449 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3450 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3451 }
3452
3453 auto rc = DeleteKey();
3454 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3455 }
3456}
3457
3458/*
Selene Huang31ab4042020-04-29 04:22:39 -07003459 * SigningOperationsTest.EcdsaAllCurves
3460 *
David Drysdale42fe1892021-10-14 14:43:46 +01003461 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003462 */
3463TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3464 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003465 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3466 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003467 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3468 .Authorization(TAG_NO_AUTH_REQUIRED)
3469 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003470 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003471 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003472 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3473 if (error != ErrorCode::OK) continue;
3474
3475 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003476 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003477 CheckedDeleteKey();
3478 }
3479}
3480
3481/*
David Drysdale42fe1892021-10-14 14:43:46 +01003482 * SigningOperationsTest.EcdsaCurve25519
3483 *
3484 * Verifies that ECDSA operations succeed with curve25519.
3485 */
3486TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3487 if (!Curve25519Supported()) {
3488 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3489 }
3490
3491 EcCurve curve = EcCurve::CURVE_25519;
3492 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3493 .Authorization(TAG_NO_AUTH_REQUIRED)
3494 .EcdsaSigningKey(curve)
3495 .Digest(Digest::NONE)
3496 .SetDefaultValidity());
3497 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3498
3499 string message(1024, 'a');
3500 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3501 CheckedDeleteKey();
3502}
3503
3504/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003505 * SigningOperationsTest.EcdsaCurve25519MaxSize
3506 *
3507 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3508 */
3509TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3510 if (!Curve25519Supported()) {
3511 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3512 }
3513
3514 EcCurve curve = EcCurve::CURVE_25519;
3515 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3516 .Authorization(TAG_NO_AUTH_REQUIRED)
3517 .EcdsaSigningKey(curve)
3518 .Digest(Digest::NONE)
3519 .SetDefaultValidity());
3520 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3521
3522 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3523
3524 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3525 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3526 string message(msg_size, 'a');
3527
3528 // Attempt to sign via Begin+Finish.
3529 AuthorizationSet out_params;
3530 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3531 EXPECT_TRUE(out_params.empty());
3532 string signature;
3533 auto result = Finish(message, &signature);
3534 EXPECT_EQ(result, ErrorCode::OK);
3535 LocalVerifyMessage(message, signature, params);
3536
3537 // Attempt to sign via Begin+Update+Finish
3538 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3539 EXPECT_TRUE(out_params.empty());
3540 string output;
3541 result = Update(message, &output);
3542 EXPECT_EQ(result, ErrorCode::OK);
3543 EXPECT_EQ(output.size(), 0);
3544 string signature2;
3545 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3546 LocalVerifyMessage(message, signature2, params);
3547 }
3548
3549 CheckedDeleteKey();
3550}
3551
3552/*
3553 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3554 *
3555 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3556 */
3557TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3558 if (!Curve25519Supported()) {
3559 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3560 }
3561
3562 EcCurve curve = EcCurve::CURVE_25519;
3563 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3564 .Authorization(TAG_NO_AUTH_REQUIRED)
3565 .EcdsaSigningKey(curve)
3566 .Digest(Digest::NONE)
3567 .SetDefaultValidity());
3568 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3569
3570 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3571
3572 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3573 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3574 string message(msg_size, 'a');
3575
3576 // Attempt to sign via Begin+Finish.
3577 AuthorizationSet out_params;
3578 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3579 EXPECT_TRUE(out_params.empty());
3580 string signature;
3581 auto result = Finish(message, &signature);
3582 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3583
3584 // Attempt to sign via Begin+Update (but never get to Finish)
3585 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3586 EXPECT_TRUE(out_params.empty());
3587 string output;
3588 result = Update(message, &output);
3589 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3590 }
3591
3592 CheckedDeleteKey();
3593}
3594
3595/*
Selene Huang31ab4042020-04-29 04:22:39 -07003596 * SigningOperationsTest.EcdsaNoDigestHugeData
3597 *
3598 * Verifies that ECDSA operations support very large messages, even without digesting. This
3599 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3600 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3601 * the framework.
3602 */
3603TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3604 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3605 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003606 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003607 .Digest(Digest::NONE)
3608 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003609 string message(1 * 1024, 'a');
3610 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3611}
3612
3613/*
3614 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3615 *
3616 * Verifies that using an EC key requires the correct app ID/data.
3617 */
3618TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3619 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3620 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003621 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003622 .Digest(Digest::NONE)
3623 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003624 .Authorization(TAG_APPLICATION_DATA, "appdata")
3625 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003626
3627 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3628
Selene Huang31ab4042020-04-29 04:22:39 -07003629 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3630 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3631 AbortIfNeeded();
3632 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3633 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3634 .Digest(Digest::NONE)
3635 .Authorization(TAG_APPLICATION_ID, "clientid")));
3636 AbortIfNeeded();
3637 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3638 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3639 .Digest(Digest::NONE)
3640 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3641 AbortIfNeeded();
3642 EXPECT_EQ(ErrorCode::OK,
3643 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3644 .Digest(Digest::NONE)
3645 .Authorization(TAG_APPLICATION_DATA, "appdata")
3646 .Authorization(TAG_APPLICATION_ID, "clientid")));
3647 AbortIfNeeded();
3648}
3649
3650/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003651 * SigningOperationsTest.EcdsaIncompatibleDigest
3652 *
3653 * Verifies that using an EC key requires compatible digest.
3654 */
3655TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3656 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3657 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003658 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003659 .Digest(Digest::NONE)
3660 .Digest(Digest::SHA1)
3661 .SetDefaultValidity()));
3662 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3663 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3664 AbortIfNeeded();
3665}
3666
3667/*
Selene Huang31ab4042020-04-29 04:22:39 -07003668 * SigningOperationsTest.AesEcbSign
3669 *
3670 * Verifies that attempts to use AES keys to sign fail in the correct way.
3671 */
3672TEST_P(SigningOperationsTest, AesEcbSign) {
3673 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3674 .Authorization(TAG_NO_AUTH_REQUIRED)
3675 .SigningKey()
3676 .AesEncryptionKey(128)
3677 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3678
3679 AuthorizationSet out_params;
3680 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3681 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3682 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3683 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3684}
3685
3686/*
3687 * SigningOperationsTest.HmacAllDigests
3688 *
3689 * Verifies that HMAC works with all digests.
3690 */
3691TEST_P(SigningOperationsTest, HmacAllDigests) {
3692 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003693 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003694 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3695 .Authorization(TAG_NO_AUTH_REQUIRED)
3696 .HmacKey(128)
3697 .Digest(digest)
3698 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3699 << "Failed to create HMAC key with digest " << digest;
3700 string message = "12345678901234567890123456789012";
3701 string signature = MacMessage(message, digest, 160);
3702 EXPECT_EQ(160U / 8U, signature.size())
3703 << "Failed to sign with HMAC key with digest " << digest;
3704 CheckedDeleteKey();
3705 }
3706}
3707
3708/*
3709 * SigningOperationsTest.HmacSha256TooLargeMacLength
3710 *
3711 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3712 * digest size.
3713 */
3714TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3715 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3716 .Authorization(TAG_NO_AUTH_REQUIRED)
3717 .HmacKey(128)
3718 .Digest(Digest::SHA_2_256)
3719 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3720 AuthorizationSet output_params;
3721 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3722 AuthorizationSetBuilder()
3723 .Digest(Digest::SHA_2_256)
3724 .Authorization(TAG_MAC_LENGTH, 264),
3725 &output_params));
3726}
3727
3728/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003729 * SigningOperationsTest.HmacSha256InvalidMacLength
3730 *
3731 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3732 * not a multiple of 8.
3733 */
3734TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3735 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3736 .Authorization(TAG_NO_AUTH_REQUIRED)
3737 .HmacKey(128)
3738 .Digest(Digest::SHA_2_256)
3739 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3740 AuthorizationSet output_params;
3741 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3742 AuthorizationSetBuilder()
3743 .Digest(Digest::SHA_2_256)
3744 .Authorization(TAG_MAC_LENGTH, 161),
3745 &output_params));
3746}
3747
3748/*
Selene Huang31ab4042020-04-29 04:22:39 -07003749 * SigningOperationsTest.HmacSha256TooSmallMacLength
3750 *
3751 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3752 * specified minimum MAC length.
3753 */
3754TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3755 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3756 .Authorization(TAG_NO_AUTH_REQUIRED)
3757 .HmacKey(128)
3758 .Digest(Digest::SHA_2_256)
3759 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3760 AuthorizationSet output_params;
3761 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3762 AuthorizationSetBuilder()
3763 .Digest(Digest::SHA_2_256)
3764 .Authorization(TAG_MAC_LENGTH, 120),
3765 &output_params));
3766}
3767
3768/*
3769 * SigningOperationsTest.HmacRfc4231TestCase3
3770 *
3771 * Validates against the test vectors from RFC 4231 test case 3.
3772 */
3773TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3774 string key(20, 0xaa);
3775 string message(50, 0xdd);
3776 uint8_t sha_224_expected[] = {
3777 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3778 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3779 };
3780 uint8_t sha_256_expected[] = {
3781 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3782 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3783 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3784 };
3785 uint8_t sha_384_expected[] = {
3786 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3787 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3788 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3789 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3790 };
3791 uint8_t sha_512_expected[] = {
3792 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3793 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3794 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3795 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3796 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3797 };
3798
3799 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3800 if (SecLevel() != SecurityLevel::STRONGBOX) {
3801 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3802 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3803 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3804 }
3805}
3806
3807/*
3808 * SigningOperationsTest.HmacRfc4231TestCase5
3809 *
3810 * Validates against the test vectors from RFC 4231 test case 5.
3811 */
3812TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3813 string key(20, 0x0c);
3814 string message = "Test With Truncation";
3815
3816 uint8_t sha_224_expected[] = {
3817 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3818 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3819 };
3820 uint8_t sha_256_expected[] = {
3821 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3822 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3823 };
3824 uint8_t sha_384_expected[] = {
3825 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3826 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3827 };
3828 uint8_t sha_512_expected[] = {
3829 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3830 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3831 };
3832
3833 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3834 if (SecLevel() != SecurityLevel::STRONGBOX) {
3835 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3836 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3837 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3838 }
3839}
3840
3841INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3842
3843typedef KeyMintAidlTestBase VerificationOperationsTest;
3844
3845/*
Selene Huang31ab4042020-04-29 04:22:39 -07003846 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3847 *
3848 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3849 */
3850TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3851 string key_material = "HelloThisIsAKey";
3852
3853 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003854 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003855 EXPECT_EQ(ErrorCode::OK,
3856 ImportKey(AuthorizationSetBuilder()
3857 .Authorization(TAG_NO_AUTH_REQUIRED)
3858 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3859 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3860 .Digest(Digest::SHA_2_256)
3861 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3862 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003863 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003864 EXPECT_EQ(ErrorCode::OK,
3865 ImportKey(AuthorizationSetBuilder()
3866 .Authorization(TAG_NO_AUTH_REQUIRED)
3867 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3868 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3869 .Digest(Digest::SHA_2_256)
3870 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3871 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003872 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003873
3874 string message = "This is a message.";
3875 string signature = SignMessage(
3876 signing_key, message,
3877 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3878
3879 // Signing key should not work.
3880 AuthorizationSet out_params;
3881 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3882 Begin(KeyPurpose::VERIFY, signing_key,
3883 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3884
3885 // Verification key should work.
3886 VerifyMessage(verification_key, message, signature,
3887 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Selene Huang31ab4042020-04-29 04:22:39 -07003888}
3889
Prashant Patildec9fdc2021-12-08 15:25:47 +00003890/*
3891 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3892 *
3893 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3894 */
3895TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3896 string key_material = "HelloThisIsAKey";
3897
3898 vector<uint8_t> signing_key, verification_key;
3899 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3900 EXPECT_EQ(ErrorCode::OK,
3901 ImportKey(AuthorizationSetBuilder()
3902 .Authorization(TAG_NO_AUTH_REQUIRED)
3903 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3904 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3905 .Digest(Digest::SHA_2_256)
3906 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3907 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003908 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003909 EXPECT_EQ(ErrorCode::OK,
3910 ImportKey(AuthorizationSetBuilder()
3911 .Authorization(TAG_NO_AUTH_REQUIRED)
3912 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3913 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3914 .Digest(Digest::SHA_2_256)
3915 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3916 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003917 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003918
3919 string message = "This is a message.";
3920 string signature = SignMessage(
3921 signing_key, message,
3922 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3923
3924 AuthorizationSet begin_out_params;
3925 ASSERT_EQ(ErrorCode::OK,
3926 Begin(KeyPurpose::VERIFY, verification_key,
3927 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3928
3929 string corruptMessage = "This is b message."; // Corrupted message
3930 string output;
3931 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3932
3933 ASSERT_EQ(ErrorCode::OK,
3934 Begin(KeyPurpose::VERIFY, verification_key,
3935 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3936
3937 signature[0] += 1; // Corrupt a signature
3938 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
Prashant Patildec9fdc2021-12-08 15:25:47 +00003939}
3940
Selene Huang31ab4042020-04-29 04:22:39 -07003941INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3942
3943typedef KeyMintAidlTestBase ExportKeyTest;
3944
3945/*
3946 * ExportKeyTest.RsaUnsupportedKeyFormat
3947 *
3948 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3949 */
3950// TODO(seleneh) add ExportKey to GenerateKey
3951// check result
3952
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003953class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003954 public:
3955 template <TagType tag_type, Tag tag, typename ValueT>
3956 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3957 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003958 for (auto& entry : key_characteristics_) {
3959 if (entry.securityLevel == SecLevel()) {
3960 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3961 << "Tag " << tag << " with value " << expected
3962 << " not found at security level" << entry.securityLevel;
3963 } else {
3964 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3965 << "Tag " << tag << " found at security level " << entry.securityLevel;
3966 }
Selene Huang31ab4042020-04-29 04:22:39 -07003967 }
3968 }
3969
3970 void CheckOrigin() {
3971 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003972 // Origin isn't a crypto param, but it always lives with them.
3973 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003974 }
3975};
3976
3977/*
3978 * ImportKeyTest.RsaSuccess
3979 *
3980 * Verifies that importing and using an RSA key pair works correctly.
3981 */
3982TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003983 uint32_t key_size;
3984 string key;
3985
3986 if (SecLevel() == SecurityLevel::STRONGBOX) {
3987 key_size = 2048;
3988 key = rsa_2048_key;
3989 } else {
3990 key_size = 1024;
3991 key = rsa_key;
3992 }
3993
Selene Huang31ab4042020-04-29 04:22:39 -07003994 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3995 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003996 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003997 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003998 .Padding(PaddingMode::RSA_PSS)
3999 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07004000 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07004001
4002 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07004003 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07004004 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4005 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4006 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4007 CheckOrigin();
4008
4009 string message(1024 / 8, 'a');
4010 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4011 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004012 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004013}
4014
4015/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004016 * ImportKeyTest.RsaSuccessWithoutParams
4017 *
4018 * Verifies that importing and using an RSA key pair without specifying parameters
4019 * works correctly.
4020 */
4021TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
4022 uint32_t key_size;
4023 string key;
4024
4025 if (SecLevel() == SecurityLevel::STRONGBOX) {
4026 key_size = 2048;
4027 key = rsa_2048_key;
4028 } else {
4029 key_size = 1024;
4030 key = rsa_key;
4031 }
4032
4033 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4034 .Authorization(TAG_NO_AUTH_REQUIRED)
4035 .SigningKey()
4036 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4037 .Digest(Digest::SHA_2_256)
4038 .Padding(PaddingMode::RSA_PSS)
4039 .SetDefaultValidity(),
4040 KeyFormat::PKCS8, key));
4041
4042 // Key size and public exponent are determined from the imported key material.
4043 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4044 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4045
4046 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4047 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4048 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4049 CheckOrigin();
4050
4051 string message(1024 / 8, 'a');
4052 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4053 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004054 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004055}
4056
4057/*
Selene Huang31ab4042020-04-29 04:22:39 -07004058 * ImportKeyTest.RsaKeySizeMismatch
4059 *
4060 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4061 * correct way.
4062 */
4063TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4064 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4065 ImportKey(AuthorizationSetBuilder()
4066 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4067 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004068 .Padding(PaddingMode::NONE)
4069 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004070 KeyFormat::PKCS8, rsa_key));
4071}
4072
4073/*
4074 * ImportKeyTest.RsaPublicExponentMismatch
4075 *
4076 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4077 * fails in the correct way.
4078 */
4079TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4080 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4081 ImportKey(AuthorizationSetBuilder()
4082 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4083 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004084 .Padding(PaddingMode::NONE)
4085 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004086 KeyFormat::PKCS8, rsa_key));
4087}
4088
4089/*
David Drysdalee60248c2021-10-04 12:54:13 +01004090 * ImportKeyTest.RsaAttestMultiPurposeFail
4091 *
4092 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4093 */
4094TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004095 if (AidlVersion() < 2) {
4096 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4097 // with other key purposes. However, this was not checked at the time
4098 // so we can only be strict about checking this for implementations of KeyMint
4099 // version 2 and above.
4100 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4101 }
David Drysdalee60248c2021-10-04 12:54:13 +01004102 uint32_t key_size = 2048;
4103 string key = rsa_2048_key;
4104
4105 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4106 ImportKey(AuthorizationSetBuilder()
4107 .Authorization(TAG_NO_AUTH_REQUIRED)
4108 .RsaSigningKey(key_size, 65537)
4109 .AttestKey()
4110 .Digest(Digest::SHA_2_256)
4111 .Padding(PaddingMode::RSA_PSS)
4112 .SetDefaultValidity(),
4113 KeyFormat::PKCS8, key));
4114}
4115
4116/*
Selene Huang31ab4042020-04-29 04:22:39 -07004117 * ImportKeyTest.EcdsaSuccess
4118 *
4119 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4120 */
4121TEST_P(ImportKeyTest, EcdsaSuccess) {
4122 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4123 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004124 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004125 .Digest(Digest::SHA_2_256)
4126 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004127 KeyFormat::PKCS8, ec_256_key));
4128
4129 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004130 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4131 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4132
4133 CheckOrigin();
4134
4135 string message(32, 'a');
4136 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4137 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004138 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004139}
4140
4141/*
David Drysdale9b8d75e2023-09-05 15:16:47 +01004142 * ImportKeyTest.EcdsaSuccessCurveNotSpecified
4143 *
4144 * Verifies that importing and using an ECDSA P-256 key pair works correctly
4145 * when the EC_CURVE is not explicitly specified.
4146 */
4147TEST_P(ImportKeyTest, EcdsaSuccessCurveNotSpecified) {
David Drysdale1405dbc2023-11-02 09:26:44 +00004148 if (get_vsr_api_level() < __ANDROID_API_V__) {
David Drysdale9b8d75e2023-09-05 15:16:47 +01004149 /*
David Drysdale1405dbc2023-11-02 09:26:44 +00004150 * The KeyMint spec was previously not clear as to whether EC_CURVE was optional on import
4151 * of EC keys. However, this was not checked at the time so we can only be strict about
4152 * checking this for implementations at VSR-V or later.
David Drysdale9b8d75e2023-09-05 15:16:47 +01004153 */
David Drysdale1405dbc2023-11-02 09:26:44 +00004154 GTEST_SKIP() << "Skipping EC_CURVE on import only strict >= VSR-V";
David Drysdale9b8d75e2023-09-05 15:16:47 +01004155 }
4156
4157 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4158 .Authorization(TAG_NO_AUTH_REQUIRED)
4159 .Authorization(TAG_ALGORITHM, Algorithm::EC)
4160 .SigningKey()
4161 .Digest(Digest::SHA_2_256)
4162 .SetDefaultValidity(),
4163 KeyFormat::PKCS8, ec_256_key));
4164
4165 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4166 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4167 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4168
4169 CheckOrigin();
4170
4171 string message(32, 'a');
4172 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4173 string signature = SignMessage(message, params);
4174 LocalVerifyMessage(message, signature, params);
4175}
4176
4177/*
Selene Huang31ab4042020-04-29 04:22:39 -07004178 * ImportKeyTest.EcdsaP256RFC5915Success
4179 *
4180 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4181 * correctly.
4182 */
4183TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4184 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4185 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004186 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004187 .Digest(Digest::SHA_2_256)
4188 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004189 KeyFormat::PKCS8, ec_256_key_rfc5915));
4190
4191 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004192 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4193 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4194
4195 CheckOrigin();
4196
4197 string message(32, 'a');
4198 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4199 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004200 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004201}
4202
4203/*
4204 * ImportKeyTest.EcdsaP256SEC1Success
4205 *
4206 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4207 */
4208TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4209 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4210 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004211 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004212 .Digest(Digest::SHA_2_256)
4213 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004214 KeyFormat::PKCS8, ec_256_key_sec1));
4215
4216 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004217 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4218 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4219
4220 CheckOrigin();
4221
4222 string message(32, 'a');
4223 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4224 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004225 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004226}
4227
4228/*
4229 * ImportKeyTest.Ecdsa521Success
4230 *
4231 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4232 */
4233TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004234 if (SecLevel() == SecurityLevel::STRONGBOX) {
4235 GTEST_SKIP() << "Test not applicable to StrongBox device";
4236 }
Selene Huang31ab4042020-04-29 04:22:39 -07004237 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4238 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004239 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004240 .Digest(Digest::SHA_2_256)
4241 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004242 KeyFormat::PKCS8, ec_521_key));
4243
4244 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004245 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4246 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4247 CheckOrigin();
4248
4249 string message(32, 'a');
4250 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4251 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004252 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004253}
4254
4255/*
Selene Huang31ab4042020-04-29 04:22:39 -07004256 * ImportKeyTest.EcdsaCurveMismatch
4257 *
4258 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4259 * the correct way.
4260 */
4261TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4262 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4263 ImportKey(AuthorizationSetBuilder()
4264 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004265 .Digest(Digest::NONE)
4266 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004267 KeyFormat::PKCS8, ec_256_key));
4268}
4269
4270/*
David Drysdalee60248c2021-10-04 12:54:13 +01004271 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4272 *
4273 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4274 */
4275TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004276 if (AidlVersion() < 2) {
4277 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4278 // with other key purposes. However, this was not checked at the time
4279 // so we can only be strict about checking this for implementations of KeyMint
4280 // version 2 and above.
4281 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4282 }
David Drysdalee60248c2021-10-04 12:54:13 +01004283 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4284 ImportKey(AuthorizationSetBuilder()
4285 .Authorization(TAG_NO_AUTH_REQUIRED)
4286 .EcdsaSigningKey(EcCurve::P_256)
4287 .AttestKey()
4288 .Digest(Digest::SHA_2_256)
4289 .SetDefaultValidity(),
4290 KeyFormat::PKCS8, ec_256_key));
4291}
4292
4293/*
David Drysdale42fe1892021-10-14 14:43:46 +01004294 * ImportKeyTest.Ed25519RawSuccess
4295 *
4296 * Verifies that importing and using a raw Ed25519 private key works correctly.
4297 */
4298TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4299 if (!Curve25519Supported()) {
4300 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4301 }
4302
4303 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4304 .Authorization(TAG_NO_AUTH_REQUIRED)
4305 .EcdsaSigningKey(EcCurve::CURVE_25519)
4306 .Digest(Digest::NONE)
4307 .SetDefaultValidity(),
4308 KeyFormat::RAW, ed25519_key));
4309 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4310 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4311 CheckOrigin();
4312
4313 // The returned cert should hold the correct public key.
4314 ASSERT_GT(cert_chain_.size(), 0);
4315 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4316 ASSERT_NE(kmKeyCert, nullptr);
4317 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4318 ASSERT_NE(kmPubKey.get(), nullptr);
4319 size_t kmPubKeySize = 32;
4320 uint8_t kmPubKeyData[32];
4321 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4322 ASSERT_EQ(kmPubKeySize, 32);
4323 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4324
4325 string message(32, 'a');
4326 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4327 string signature = SignMessage(message, params);
4328 LocalVerifyMessage(message, signature, params);
4329}
4330
4331/*
4332 * ImportKeyTest.Ed25519Pkcs8Success
4333 *
4334 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4335 */
4336TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4337 if (!Curve25519Supported()) {
4338 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4339 }
4340
4341 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4342 .Authorization(TAG_NO_AUTH_REQUIRED)
4343 .EcdsaSigningKey(EcCurve::CURVE_25519)
4344 .Digest(Digest::NONE)
4345 .SetDefaultValidity(),
4346 KeyFormat::PKCS8, ed25519_pkcs8_key));
4347 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4348 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4349 CheckOrigin();
4350
4351 // The returned cert should hold the correct public key.
4352 ASSERT_GT(cert_chain_.size(), 0);
4353 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4354 ASSERT_NE(kmKeyCert, nullptr);
4355 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4356 ASSERT_NE(kmPubKey.get(), nullptr);
4357 size_t kmPubKeySize = 32;
4358 uint8_t kmPubKeyData[32];
4359 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4360 ASSERT_EQ(kmPubKeySize, 32);
4361 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4362
4363 string message(32, 'a');
4364 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4365 string signature = SignMessage(message, params);
4366 LocalVerifyMessage(message, signature, params);
4367}
4368
4369/*
4370 * ImportKeyTest.Ed25519CurveMismatch
4371 *
4372 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4373 * the correct way.
4374 */
4375TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4376 if (!Curve25519Supported()) {
4377 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4378 }
4379
4380 ASSERT_NE(ErrorCode::OK,
4381 ImportKey(AuthorizationSetBuilder()
4382 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4383 .Digest(Digest::NONE)
4384 .SetDefaultValidity(),
4385 KeyFormat::RAW, ed25519_key));
4386}
4387
4388/*
4389 * ImportKeyTest.Ed25519FormatMismatch
4390 *
4391 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4392 */
4393TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4394 if (!Curve25519Supported()) {
4395 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4396 }
4397
4398 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4399 .EcdsaSigningKey(EcCurve::CURVE_25519)
4400 .Digest(Digest::NONE)
4401 .SetDefaultValidity(),
4402 KeyFormat::PKCS8, ed25519_key));
4403 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4404 .EcdsaSigningKey(EcCurve::CURVE_25519)
4405 .Digest(Digest::NONE)
4406 .SetDefaultValidity(),
4407 KeyFormat::RAW, ed25519_pkcs8_key));
4408}
4409
4410/*
4411 * ImportKeyTest.Ed25519PurposeMismatch
4412 *
4413 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4414 */
4415TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4416 if (!Curve25519Supported()) {
4417 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4418 }
4419
4420 // Can't have both SIGN and ATTEST_KEY
4421 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4422 .EcdsaSigningKey(EcCurve::CURVE_25519)
4423 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4424 .Digest(Digest::NONE)
4425 .SetDefaultValidity(),
4426 KeyFormat::RAW, ed25519_key));
4427 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4428 // PKCS#8 format and so includes an OID).
4429 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4430 .EcdsaKey(EcCurve::CURVE_25519)
4431 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4432 .Digest(Digest::NONE)
4433 .SetDefaultValidity(),
4434 KeyFormat::PKCS8, ed25519_pkcs8_key));
4435}
4436
4437/*
4438 * ImportKeyTest.X25519RawSuccess
4439 *
4440 * Verifies that importing and using a raw X25519 private key works correctly.
4441 */
4442TEST_P(ImportKeyTest, X25519RawSuccess) {
4443 if (!Curve25519Supported()) {
4444 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4445 }
4446
4447 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4448 .Authorization(TAG_NO_AUTH_REQUIRED)
4449 .EcdsaKey(EcCurve::CURVE_25519)
4450 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4451 .SetDefaultValidity(),
4452 KeyFormat::RAW, x25519_key));
4453
4454 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4455 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4456 CheckOrigin();
4457}
4458
4459/*
4460 * ImportKeyTest.X25519Pkcs8Success
4461 *
4462 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4463 */
4464TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4465 if (!Curve25519Supported()) {
4466 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4467 }
4468
4469 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4470 .Authorization(TAG_NO_AUTH_REQUIRED)
4471 .EcdsaKey(EcCurve::CURVE_25519)
4472 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4473 .SetDefaultValidity(),
4474 KeyFormat::PKCS8, x25519_pkcs8_key));
4475
4476 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4477 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4478 CheckOrigin();
4479}
4480
4481/*
4482 * ImportKeyTest.X25519CurveMismatch
4483 *
4484 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4485 * the correct way.
4486 */
4487TEST_P(ImportKeyTest, X25519CurveMismatch) {
4488 if (!Curve25519Supported()) {
4489 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4490 }
4491
4492 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4493 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4494 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4495 .SetDefaultValidity(),
4496 KeyFormat::RAW, x25519_key));
4497}
4498
4499/*
4500 * ImportKeyTest.X25519FormatMismatch
4501 *
4502 * Verifies that importing an X25519 key with an invalid format fails.
4503 */
4504TEST_P(ImportKeyTest, X25519FormatMismatch) {
4505 if (!Curve25519Supported()) {
4506 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4507 }
4508
4509 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4510 .EcdsaKey(EcCurve::CURVE_25519)
4511 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4512 .SetDefaultValidity(),
4513 KeyFormat::PKCS8, x25519_key));
4514 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4515 .EcdsaKey(EcCurve::CURVE_25519)
4516 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4517 .SetDefaultValidity(),
4518 KeyFormat::RAW, x25519_pkcs8_key));
4519}
4520
4521/*
4522 * ImportKeyTest.X25519PurposeMismatch
4523 *
4524 * Verifies that importing an X25519 key pair with an invalid format fails.
4525 */
4526TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4527 if (!Curve25519Supported()) {
4528 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4529 }
4530
4531 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4532 .EcdsaKey(EcCurve::CURVE_25519)
4533 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4534 .SetDefaultValidity(),
4535 KeyFormat::PKCS8, x25519_pkcs8_key));
4536 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4537 .EcdsaSigningKey(EcCurve::CURVE_25519)
4538 .SetDefaultValidity(),
4539 KeyFormat::PKCS8, x25519_pkcs8_key));
4540}
4541
4542/*
Selene Huang31ab4042020-04-29 04:22:39 -07004543 * ImportKeyTest.AesSuccess
4544 *
4545 * Verifies that importing and using an AES key works.
4546 */
4547TEST_P(ImportKeyTest, AesSuccess) {
4548 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4549 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4550 .Authorization(TAG_NO_AUTH_REQUIRED)
4551 .AesEncryptionKey(key.size() * 8)
4552 .EcbMode()
4553 .Padding(PaddingMode::PKCS7),
4554 KeyFormat::RAW, key));
4555
4556 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4557 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4558 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4559 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4560 CheckOrigin();
4561
4562 string message = "Hello World!";
4563 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4564 string ciphertext = EncryptMessage(message, params);
4565 string plaintext = DecryptMessage(ciphertext, params);
4566 EXPECT_EQ(message, plaintext);
4567}
4568
4569/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004570 * ImportKeyTest.AesFailure
4571 *
4572 * Verifies that importing an invalid AES key fails.
4573 */
4574TEST_P(ImportKeyTest, AesFailure) {
4575 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4576 uint32_t bitlen = key.size() * 8;
4577 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004578 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004579 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004580 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004581 .Authorization(TAG_NO_AUTH_REQUIRED)
4582 .AesEncryptionKey(key_size)
4583 .EcbMode()
4584 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004585 KeyFormat::RAW, key);
4586 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004587 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4588 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004589 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004590
4591 // Explicit key size matches that of the provided key, but it's not a valid size.
4592 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4593 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4594 ImportKey(AuthorizationSetBuilder()
4595 .Authorization(TAG_NO_AUTH_REQUIRED)
4596 .AesEncryptionKey(long_key.size() * 8)
4597 .EcbMode()
4598 .Padding(PaddingMode::PKCS7),
4599 KeyFormat::RAW, long_key));
4600 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4601 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4602 ImportKey(AuthorizationSetBuilder()
4603 .Authorization(TAG_NO_AUTH_REQUIRED)
4604 .AesEncryptionKey(short_key.size() * 8)
4605 .EcbMode()
4606 .Padding(PaddingMode::PKCS7),
4607 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004608}
4609
4610/*
4611 * ImportKeyTest.TripleDesSuccess
4612 *
4613 * Verifies that importing and using a 3DES key works.
4614 */
4615TEST_P(ImportKeyTest, TripleDesSuccess) {
4616 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4617 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4618 .Authorization(TAG_NO_AUTH_REQUIRED)
4619 .TripleDesEncryptionKey(168)
4620 .EcbMode()
4621 .Padding(PaddingMode::PKCS7),
4622 KeyFormat::RAW, key));
4623
4624 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4625 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4626 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4627 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4628 CheckOrigin();
4629
4630 string message = "Hello World!";
4631 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4632 string ciphertext = EncryptMessage(message, params);
4633 string plaintext = DecryptMessage(ciphertext, params);
4634 EXPECT_EQ(message, plaintext);
4635}
4636
4637/*
4638 * ImportKeyTest.TripleDesFailure
4639 *
4640 * Verifies that importing an invalid 3DES key fails.
4641 */
4642TEST_P(ImportKeyTest, TripleDesFailure) {
4643 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004644 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004645 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004646 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004647 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004648 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004649 .Authorization(TAG_NO_AUTH_REQUIRED)
4650 .TripleDesEncryptionKey(key_size)
4651 .EcbMode()
4652 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004653 KeyFormat::RAW, key);
4654 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004655 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4656 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004657 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004658 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004659 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004660 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4661 ImportKey(AuthorizationSetBuilder()
4662 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004663 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004664 .EcbMode()
4665 .Padding(PaddingMode::PKCS7),
4666 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004667 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004668 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4669 ImportKey(AuthorizationSetBuilder()
4670 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004671 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004672 .EcbMode()
4673 .Padding(PaddingMode::PKCS7),
4674 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004675}
4676
4677/*
4678 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004679 *
4680 * Verifies that importing and using an HMAC key works.
4681 */
4682TEST_P(ImportKeyTest, HmacKeySuccess) {
4683 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4684 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4685 .Authorization(TAG_NO_AUTH_REQUIRED)
4686 .HmacKey(key.size() * 8)
4687 .Digest(Digest::SHA_2_256)
4688 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4689 KeyFormat::RAW, key));
4690
4691 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4692 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4693 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4694 CheckOrigin();
4695
4696 string message = "Hello World!";
4697 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4698 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4699}
4700
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004701/*
4702 * ImportKeyTest.GetKeyCharacteristics
4703 *
4704 * Verifies that imported keys have the correct characteristics.
4705 */
4706TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4707 vector<uint8_t> key_blob;
4708 vector<KeyCharacteristics> key_characteristics;
4709 auto base_builder = AuthorizationSetBuilder()
4710 .Padding(PaddingMode::NONE)
4711 .Authorization(TAG_NO_AUTH_REQUIRED)
4712 .SetDefaultValidity();
4713 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4714 Algorithm::TRIPLE_DES};
4715 ErrorCode result;
4716 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4717 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4718 for (auto alg : algorithms) {
4719 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4720 AuthorizationSetBuilder builder(base_builder);
4721 switch (alg) {
4722 case Algorithm::RSA:
4723 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4724
4725 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4726 &key_characteristics);
4727 break;
4728 case Algorithm::EC:
4729 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4730 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4731 &key_characteristics);
4732 break;
4733 case Algorithm::HMAC:
4734 builder.HmacKey(128)
4735 .Digest(Digest::SHA_2_256)
4736 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4737 result =
4738 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4739 break;
4740 case Algorithm::AES:
4741 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4742 result =
4743 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4744 break;
4745 case Algorithm::TRIPLE_DES:
4746 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4747 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4748 &key_characteristics);
4749 break;
4750 default:
4751 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4752 continue;
4753 }
4754 ASSERT_EQ(ErrorCode::OK, result);
4755 CheckCharacteristics(key_blob, key_characteristics);
4756 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4757 }
4758}
4759
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004760/*
4761 * ImportKeyTest.RsaOaepMGFDigestSuccess
4762 *
4763 * Include MGF-Digest explicitly in import key authorization list.
4764 * Test should import RSA key with OAEP padding and mgf-digests and verify that imported key
4765 * should have the correct characteristics.
4766 */
4767TEST_P(ImportKeyTest, RsaOaepMGFDigestSuccess) {
Prashant Patil2114dca2023-09-21 14:57:10 +00004768 // There was no test to assert that MGF1 digest was present in generated/imported key
4769 // characteristics before Keymint V3, so there are some Keymint implementations where
4770 // this test case fails(b/297306437), hence this test is skipped for Keymint < 3.
4771 if (AidlVersion() < 3) {
4772 GTEST_SKIP() << "Test not applicable to Keymint < V3";
4773 }
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004774 auto mgf_digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4775 size_t key_size = 2048;
4776
4777 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4778 .OaepMGFDigest(mgf_digests)
4779 .Authorization(TAG_NO_AUTH_REQUIRED)
4780 .RsaEncryptionKey(key_size, 65537)
4781 .Digest(Digest::SHA_2_256)
4782 .Padding(PaddingMode::RSA_OAEP)
4783 .SetDefaultValidity(),
4784 KeyFormat::PKCS8, rsa_2048_key));
4785
4786 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4787 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4788 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4789 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4790 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4791 CheckOrigin();
4792
4793 // Make sure explicitly specified mgf-digests exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00004794 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digests, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004795
4796 string message = "Hello";
4797
4798 for (auto digest : mgf_digests) {
4799 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4800 auto params = AuthorizationSetBuilder()
4801 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4802 .Digest(Digest::SHA_2_256)
4803 .Padding(PaddingMode::RSA_OAEP);
4804 string ciphertext1 = LocalRsaEncryptMessage(message, params);
4805 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4806 EXPECT_EQ(key_size / 8, ciphertext1.size());
4807
4808 string ciphertext2 = LocalRsaEncryptMessage(message, params);
4809 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4810 EXPECT_EQ(key_size / 8, ciphertext2.size());
4811
4812 // OAEP randomizes padding so every result should be different (with astronomically high
4813 // probability).
4814 EXPECT_NE(ciphertext1, ciphertext2);
4815
4816 string plaintext1 = DecryptMessage(ciphertext1, params);
4817 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4818 string plaintext2 = DecryptMessage(ciphertext2, params);
4819 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4820
4821 // Decrypting corrupted ciphertext should fail.
4822 size_t offset_to_corrupt = ciphertext1.size() - 1;
4823 char corrupt_byte = ~ciphertext1[offset_to_corrupt];
4824 ciphertext1[offset_to_corrupt] = corrupt_byte;
4825
4826 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4827 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04004828 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004829 EXPECT_EQ(0U, result.size());
4830 }
4831}
4832
4833/*
4834 * ImportKeyTest.RsaOaepMGFDigestDefaultSuccess
4835 *
4836 * Don't specify MGF-Digest explicitly in import key authorization list.
4837 * Test should import RSA key with OAEP padding and default mgf-digest (SHA1) and
4838 * verify that imported key should have the correct characteristics. Default
4839 * mgf-digest shouldn't be included in key charecteristics.
4840 */
4841TEST_P(ImportKeyTest, RsaOaepMGFDigestDefaultSuccess) {
4842 size_t key_size = 2048;
4843 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4844 .Authorization(TAG_NO_AUTH_REQUIRED)
4845 .RsaEncryptionKey(key_size, 65537)
4846 .Digest(Digest::SHA_2_256)
4847 .Padding(PaddingMode::RSA_OAEP)
4848 .SetDefaultValidity(),
4849 KeyFormat::PKCS8, rsa_2048_key));
4850
4851 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4852 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4853 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4854 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4855 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4856 CheckOrigin();
4857
Prashant Patil2114dca2023-09-21 14:57:10 +00004858 vector defaultDigest = {Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004859 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00004860 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004861}
4862
Selene Huang31ab4042020-04-29 04:22:39 -07004863INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4864
4865auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004866 // IKeyMintDevice.aidl
4867 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4868 "020100" // INTEGER length 1 value 0x00 (version)
4869 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4870 "934bf94e2aa28a3f83c9f79297250262"
4871 "fbe3276b5a1c91159bbfa3ef8957aac8"
4872 "4b59b30b455a79c2973480823d8b3863"
4873 "c3deef4a8e243590268d80e18751a0e1"
4874 "30f67ce6a1ace9f79b95e097474febc9"
4875 "81195b1d13a69086c0863f66a7b7fdb4"
4876 "8792227b1ac5e2489febdf087ab54864"
4877 "83033a6f001ca5d1ec1e27f5c30f4cec"
4878 "2642074a39ae68aee552e196627a8e3d"
4879 "867e67a8c01b11e75f13cca0a97ab668"
4880 "b50cda07a8ecb7cd8e3dd7009c963653"
4881 "4f6f239cffe1fc8daa466f78b676c711"
4882 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4883 "99b801597d5220e307eaa5bee507fb94"
4884 "d1fa69f9e519b2de315bac92c36f2ea1"
4885 "fa1df4478c0ddedeae8c70e0233cd098"
4886 "040c" // OCTET STRING length 0x0c (initializationVector)
4887 "d796b02c370f1fa4cc0124f1"
4888 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4889 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4890 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4891 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4892 "3106" // SET length 0x06
4893 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4894 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4895 // } end SET
4896 // } end [1]
4897 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4898 "020120" // INTEGER length 1 value 0x20 (AES)
4899 // } end [2]
4900 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4901 "02020100" // INTEGER length 2 value 0x100
4902 // } end [3]
4903 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4904 "3103" // SET length 0x03 {
4905 "020101" // INTEGER length 1 value 0x01 (ECB)
4906 // } end SET
4907 // } end [4]
4908 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4909 "3103" // SET length 0x03 {
4910 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4911 // } end SET
4912 // } end [5]
4913 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4914 // (noAuthRequired)
4915 "0500" // NULL
4916 // } end [503]
4917 // } end SEQUENCE (AuthorizationList)
4918 // } end SEQUENCE (KeyDescription)
4919 "0420" // OCTET STRING length 0x20 (encryptedKey)
4920 "ccd540855f833a5e1480bfd2d36faf3a"
4921 "eee15df5beabe2691bc82dde2a7aa910"
4922 "0410" // OCTET STRING length 0x10 (tag)
4923 "64c9f689c60ff6223ab6e6999e0eb6e5"
4924 // } SEQUENCE (SecureKeyWrapper)
4925);
Selene Huang31ab4042020-04-29 04:22:39 -07004926
4927auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004928 // IKeyMintDevice.aidl
4929 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4930 "020100" // INTEGER length 1 value 0x00 (version)
4931 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4932 "aad93ed5924f283b4bb5526fbe7a1412"
4933 "f9d9749ec30db9062b29e574a8546f33"
4934 "c88732452f5b8e6a391ee76c39ed1712"
4935 "c61d8df6213dec1cffbc17a8c6d04c7b"
4936 "30893d8daa9b2015213e219468215532"
4937 "07f8f9931c4caba23ed3bee28b36947e"
4938 "47f10e0a5c3dc51c988a628daad3e5e1"
4939 "f4005e79c2d5a96c284b4b8d7e4948f3"
4940 "31e5b85dd5a236f85579f3ea1d1b8484"
4941 "87470bdb0ab4f81a12bee42c99fe0df4"
4942 "bee3759453e69ad1d68a809ce06b949f"
4943 "7694a990429b2fe81e066ff43e56a216"
4944 "02db70757922a4bcc23ab89f1e35da77"
4945 "586775f423e519c2ea394caf48a28d0c"
4946 "8020f1dcf6b3a68ec246f615ae96dae9"
4947 "a079b1f6eb959033c1af5c125fd94168"
4948 "040c" // OCTET STRING length 0x0c (initializationVector)
4949 "6d9721d08589581ab49204a3"
4950 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4951 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4952 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4953 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4954 "3106" // SET length 0x06
4955 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4956 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4957 // } end SET
4958 // } end [1]
4959 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4960 "020120" // INTEGER length 1 value 0x20 (AES)
4961 // } end [2]
4962 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4963 "02020100" // INTEGER length 2 value 0x100
4964 // } end [3]
4965 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4966 "3103" // SET length 0x03 {
4967 "020101" // INTEGER length 1 value 0x01 (ECB)
4968 // } end SET
4969 // } end [4]
4970 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4971 "3103" // SET length 0x03 {
4972 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4973 // } end SET
4974 // } end [5]
4975 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4976 // (noAuthRequired)
4977 "0500" // NULL
4978 // } end [503]
4979 // } end SEQUENCE (AuthorizationList)
4980 // } end SEQUENCE (KeyDescription)
4981 "0420" // OCTET STRING length 0x20 (encryptedKey)
4982 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4983 "c20d1f99a9a024a76f35c8e2cab9b68d"
4984 "0410" // OCTET STRING length 0x10 (tag)
4985 "2560c70109ae67c030f00b98b512a670"
4986 // } SEQUENCE (SecureKeyWrapper)
4987);
Selene Huang31ab4042020-04-29 04:22:39 -07004988
4989auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004990 // RFC 5208 s5
4991 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4992 "020100" // INTEGER length 1 value 0x00 (version)
4993 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4994 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4995 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4996 "0500" // NULL (parameters)
4997 // } SEQUENCE (AlgorithmIdentifier)
4998 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4999 // RFC 8017 A.1.2
5000 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
5001 "020100" // INTEGER length 1 value 0x00 (version)
5002 "02820101" // INTEGER length 0x0101 (modulus) value...
5003 "00aec367931d8900ce56b0067f7d70e1" // 0x10
5004 "fc653f3f34d194c1fed50018fb43db93" // 0x20
5005 "7b06e673a837313d56b1c725150a3fef" // 0x30
5006 "86acbddc41bb759c2854eae32d35841e" // 0x40
5007 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
5008 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
5009 "312d7bd5921ffaea1347c157406fef71" // 0x70
5010 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
5011 "f4645c11f5c1374c3886427411c44979" // 0x90
5012 "6792e0bef75dec858a2123c36753e02a" // 0xa0
5013 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
5014 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
5015 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
5016 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
5017 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
5018 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
5019 "55" // 0x101
5020 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
5021 "02820100" // INTEGER length 0x100 (privateExponent) value...
5022 "431447b6251908112b1ee76f99f3711a" // 0x10
5023 "52b6630960046c2de70de188d833f8b8" // 0x20
5024 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
5025 "641f7fe24f14c67a88959bdb27766df9" // 0x40
5026 "e710b630a03adc683b5d2c43080e52be" // 0x50
5027 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
5028 "822bccff087d63c940ba8a45f670feb2" // 0x70
5029 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
5030 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
5031 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
5032 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
5033 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
5034 "52659d5a5ba05b663737a8696281865b" // 0xd0
5035 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
5036 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
5037 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
5038 "028181" // INTEGER length 0x81 (prime1) value...
5039 "00de392e18d682c829266cc3454e1d61" // 0x10
5040 "66242f32d9a1d10577753e904ea7d08b" // 0x20
5041 "ff841be5bac82a164c5970007047b8c5" // 0x30
5042 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
5043 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
5044 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
5045 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
5046 "9e91346130748a6e3c124f9149d71c74" // 0x80
5047 "35"
5048 "028181" // INTEGER length 0x81 (prime2) value...
5049 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
5050 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
5051 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
5052 "7349db6c4a95affdae0dae612e1afac9" // 0x40
5053 "9ed39a2d934c880440aed8832f984316" // 0x50
5054 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
5055 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
5056 "b880677c068e1be936e81288815252a8" // 0x80
5057 "a1"
5058 "028180" // INTEGER length 0x80 (exponent1) value...
5059 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
5060 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
5061 "5a063212a4f105a3764743e53281988a" // 0x30
5062 "ba073f6e0027298e1c4378556e0efca0" // 0x40
5063 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
5064 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
5065 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
5066 "4719d6e2b9439823719cd08bcd031781" // 0x80
5067 "028181" // INTEGER length 0x81 (exponent2) value...
5068 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
5069 "1241acc607976c4ddccc90e65b6556ca" // 0x20
5070 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
5071 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
5072 "1254186af30b22c10582a8a43e34fe94" // 0x50
5073 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
5074 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
5075 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
5076 "61"
5077 "028181" // INTEGER length 0x81 (coefficient) value...
5078 "00c931617c77829dfb1270502be9195c" // 0x10
5079 "8f2830885f57dba869536811e6864236" // 0x20
5080 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
5081 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
5082 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
5083 "959356210723287b0affcc9f727044d4" // 0x60
5084 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
5085 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
5086 "22"
5087 // } SEQUENCE
5088 // } SEQUENCE ()
5089);
Selene Huang31ab4042020-04-29 04:22:39 -07005090
5091string zero_masking_key =
5092 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
5093string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
5094
5095class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
5096
5097TEST_P(ImportWrappedKeyTest, Success) {
5098 auto wrapping_key_desc = AuthorizationSetBuilder()
5099 .RsaEncryptionKey(2048, 65537)
5100 .Digest(Digest::SHA_2_256)
5101 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005102 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5103 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005104
5105 ASSERT_EQ(ErrorCode::OK,
5106 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5107 AuthorizationSetBuilder()
5108 .Digest(Digest::SHA_2_256)
5109 .Padding(PaddingMode::RSA_OAEP)));
5110
5111 string message = "Hello World!";
5112 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5113 string ciphertext = EncryptMessage(message, params);
5114 string plaintext = DecryptMessage(ciphertext, params);
5115 EXPECT_EQ(message, plaintext);
5116}
5117
David Drysdaled2cc8c22021-04-15 13:29:45 +01005118/*
5119 * ImportWrappedKeyTest.SuccessSidsIgnored
5120 *
5121 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
5122 * include Tag:USER_SECURE_ID.
5123 */
5124TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
5125 auto wrapping_key_desc = AuthorizationSetBuilder()
5126 .RsaEncryptionKey(2048, 65537)
5127 .Digest(Digest::SHA_2_256)
5128 .Padding(PaddingMode::RSA_OAEP)
5129 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5130 .SetDefaultValidity();
5131
5132 int64_t password_sid = 42;
5133 int64_t biometric_sid = 24;
5134 ASSERT_EQ(ErrorCode::OK,
5135 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5136 AuthorizationSetBuilder()
5137 .Digest(Digest::SHA_2_256)
5138 .Padding(PaddingMode::RSA_OAEP),
5139 password_sid, biometric_sid));
5140
5141 string message = "Hello World!";
5142 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5143 string ciphertext = EncryptMessage(message, params);
5144 string plaintext = DecryptMessage(ciphertext, params);
5145 EXPECT_EQ(message, plaintext);
5146}
5147
Selene Huang31ab4042020-04-29 04:22:39 -07005148TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5149 auto wrapping_key_desc = AuthorizationSetBuilder()
5150 .RsaEncryptionKey(2048, 65537)
5151 .Digest(Digest::SHA_2_256)
5152 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005153 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5154 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005155
5156 ASSERT_EQ(ErrorCode::OK,
5157 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5158 AuthorizationSetBuilder()
5159 .Digest(Digest::SHA_2_256)
5160 .Padding(PaddingMode::RSA_OAEP)));
5161}
5162
5163TEST_P(ImportWrappedKeyTest, WrongMask) {
5164 auto wrapping_key_desc = AuthorizationSetBuilder()
5165 .RsaEncryptionKey(2048, 65537)
5166 .Digest(Digest::SHA_2_256)
5167 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005168 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5169 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005170
5171 ASSERT_EQ(
5172 ErrorCode::VERIFICATION_FAILED,
5173 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5174 AuthorizationSetBuilder()
5175 .Digest(Digest::SHA_2_256)
5176 .Padding(PaddingMode::RSA_OAEP)));
5177}
5178
5179TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5180 auto wrapping_key_desc = AuthorizationSetBuilder()
5181 .RsaEncryptionKey(2048, 65537)
5182 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005183 .Padding(PaddingMode::RSA_OAEP)
5184 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005185
5186 ASSERT_EQ(
5187 ErrorCode::INCOMPATIBLE_PURPOSE,
5188 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5189 AuthorizationSetBuilder()
5190 .Digest(Digest::SHA_2_256)
5191 .Padding(PaddingMode::RSA_OAEP)));
5192}
5193
David Drysdaled2cc8c22021-04-15 13:29:45 +01005194TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5195 auto wrapping_key_desc = AuthorizationSetBuilder()
5196 .RsaEncryptionKey(2048, 65537)
5197 .Digest(Digest::SHA_2_256)
5198 .Padding(PaddingMode::RSA_PSS)
5199 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5200 .SetDefaultValidity();
5201
5202 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5203 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5204 AuthorizationSetBuilder()
5205 .Digest(Digest::SHA_2_256)
5206 .Padding(PaddingMode::RSA_OAEP)));
5207}
5208
5209TEST_P(ImportWrappedKeyTest, WrongDigest) {
5210 auto wrapping_key_desc = AuthorizationSetBuilder()
5211 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005212 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005213 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005214 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5215 .SetDefaultValidity();
5216
5217 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5218 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5219 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005220 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005221 .Padding(PaddingMode::RSA_OAEP)));
5222}
5223
Selene Huang31ab4042020-04-29 04:22:39 -07005224INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5225
5226typedef KeyMintAidlTestBase EncryptionOperationsTest;
5227
5228/*
5229 * EncryptionOperationsTest.RsaNoPaddingSuccess
5230 *
David Drysdale59cae642021-05-12 13:52:03 +01005231 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005232 */
5233TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005234 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005235 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005236 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5237 .Authorization(TAG_NO_AUTH_REQUIRED)
5238 .RsaEncryptionKey(2048, exponent)
5239 .Padding(PaddingMode::NONE)
5240 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005241
David Drysdaled2cc8c22021-04-15 13:29:45 +01005242 string message = string(2048 / 8, 'a');
5243 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005244 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005245 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005246
David Drysdale59cae642021-05-12 13:52:03 +01005247 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005248 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005249
David Drysdaled2cc8c22021-04-15 13:29:45 +01005250 // Unpadded RSA is deterministic
5251 EXPECT_EQ(ciphertext1, ciphertext2);
5252
5253 CheckedDeleteKey();
5254 }
Selene Huang31ab4042020-04-29 04:22:39 -07005255}
5256
5257/*
5258 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5259 *
David Drysdale59cae642021-05-12 13:52:03 +01005260 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005261 */
5262TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5263 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5264 .Authorization(TAG_NO_AUTH_REQUIRED)
5265 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005266 .Padding(PaddingMode::NONE)
5267 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005268
5269 string message = "1";
5270 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5271
David Drysdale59cae642021-05-12 13:52:03 +01005272 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005273 EXPECT_EQ(2048U / 8, ciphertext.size());
5274
5275 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5276 string plaintext = DecryptMessage(ciphertext, params);
5277
5278 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005279}
5280
5281/*
Selene Huang31ab4042020-04-29 04:22:39 -07005282 * EncryptionOperationsTest.RsaOaepSuccess
5283 *
David Drysdale59cae642021-05-12 13:52:03 +01005284 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005285 */
5286TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5287 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
Prashant Patil2114dca2023-09-21 14:57:10 +00005288 auto mgf_digest = vector{Digest::SHA1};
Selene Huang31ab4042020-04-29 04:22:39 -07005289
5290 size_t key_size = 2048; // Need largish key for SHA-512 test.
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005291 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5292 .Authorization(TAG_NO_AUTH_REQUIRED)
5293 .RsaEncryptionKey(key_size, 65537)
5294 .Padding(PaddingMode::RSA_OAEP)
5295 .Digest(digests)
Prashant Patil2114dca2023-09-21 14:57:10 +00005296 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005297 .SetDefaultValidity()));
5298
5299 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005300 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Selene Huang31ab4042020-04-29 04:22:39 -07005301
5302 string message = "Hello";
5303
5304 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005305 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5306
5307 auto params = AuthorizationSetBuilder()
5308 .Digest(digest)
5309 .Padding(PaddingMode::RSA_OAEP)
5310 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5311 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005312 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5313 EXPECT_EQ(key_size / 8, ciphertext1.size());
5314
David Drysdale59cae642021-05-12 13:52:03 +01005315 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005316 EXPECT_EQ(key_size / 8, ciphertext2.size());
5317
5318 // OAEP randomizes padding so every result should be different (with astronomically high
5319 // probability).
5320 EXPECT_NE(ciphertext1, ciphertext2);
5321
5322 string plaintext1 = DecryptMessage(ciphertext1, params);
5323 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5324 string plaintext2 = DecryptMessage(ciphertext2, params);
5325 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5326
5327 // Decrypting corrupted ciphertext should fail.
5328 size_t offset_to_corrupt = random() % ciphertext1.size();
5329 char corrupt_byte;
5330 do {
5331 corrupt_byte = static_cast<char>(random() % 256);
5332 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5333 ciphertext1[offset_to_corrupt] = corrupt_byte;
5334
5335 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5336 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005337 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005338 EXPECT_EQ(0U, result.size());
5339 }
5340}
5341
5342/*
5343 * EncryptionOperationsTest.RsaOaepInvalidDigest
5344 *
David Drysdale59cae642021-05-12 13:52:03 +01005345 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005346 * without a digest.
5347 */
5348TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5349 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5350 .Authorization(TAG_NO_AUTH_REQUIRED)
5351 .RsaEncryptionKey(2048, 65537)
5352 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005353 .Digest(Digest::NONE)
5354 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005355
5356 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005357 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005358}
5359
5360/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005361 * EncryptionOperationsTest.RsaOaepInvalidPadding
5362 *
David Drysdale59cae642021-05-12 13:52:03 +01005363 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005364 * with a padding value that is only suitable for signing/verifying.
5365 */
5366TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5367 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5368 .Authorization(TAG_NO_AUTH_REQUIRED)
5369 .RsaEncryptionKey(2048, 65537)
5370 .Padding(PaddingMode::RSA_PSS)
5371 .Digest(Digest::NONE)
5372 .SetDefaultValidity()));
5373
5374 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005375 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005376}
5377
5378/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005379 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005380 *
David Drysdale59cae642021-05-12 13:52:03 +01005381 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005382 * with a different digest than was used to encrypt.
5383 */
5384TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005385 if (SecLevel() == SecurityLevel::STRONGBOX) {
5386 GTEST_SKIP() << "Test not applicable to StrongBox device";
5387 }
Selene Huang31ab4042020-04-29 04:22:39 -07005388
5389 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5390 .Authorization(TAG_NO_AUTH_REQUIRED)
5391 .RsaEncryptionKey(1024, 65537)
5392 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005393 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5394 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005395 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005396 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005397 message,
5398 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5399
5400 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5401 .Digest(Digest::SHA_2_256)
5402 .Padding(PaddingMode::RSA_OAEP)));
5403 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005404 EXPECT_NE(ErrorCode::OK, Finish(ciphertext, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005405 EXPECT_EQ(0U, result.size());
5406}
5407
5408/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005409 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5410 *
David Drysdale59cae642021-05-12 13:52:03 +01005411 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005412 * digests.
5413 */
5414TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5415 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5416
5417 size_t key_size = 2048; // Need largish key for SHA-512 test.
5418 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5419 .OaepMGFDigest(digests)
5420 .Authorization(TAG_NO_AUTH_REQUIRED)
5421 .RsaEncryptionKey(key_size, 65537)
5422 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005423 .Digest(Digest::SHA_2_256)
5424 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005425 if (AidlVersion() >= 3) {
5426 std::vector<Digest> mgf1DigestsInAuths;
5427 mgf1DigestsInAuths.reserve(digests.size());
5428 const auto& hw_auths = SecLevelAuthorizations(key_characteristics_);
5429 std::for_each(hw_auths.begin(), hw_auths.end(), [&](auto& param) {
5430 if (param.tag == Tag::RSA_OAEP_MGF_DIGEST) {
5431 KeyParameterValue value = param.value;
5432 mgf1DigestsInAuths.push_back(param.value.template get<KeyParameterValue::digest>());
5433 }
5434 });
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005435
Prashant Patil2114dca2023-09-21 14:57:10 +00005436 std::sort(digests.begin(), digests.end());
5437 std::sort(mgf1DigestsInAuths.begin(), mgf1DigestsInAuths.end());
5438 EXPECT_EQ(digests, mgf1DigestsInAuths);
5439 }
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005440 string message = "Hello";
5441
5442 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005443 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005444 auto params = AuthorizationSetBuilder()
5445 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5446 .Digest(Digest::SHA_2_256)
5447 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005448 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005449 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5450 EXPECT_EQ(key_size / 8, ciphertext1.size());
5451
David Drysdale59cae642021-05-12 13:52:03 +01005452 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005453 EXPECT_EQ(key_size / 8, ciphertext2.size());
5454
5455 // OAEP randomizes padding so every result should be different (with astronomically high
5456 // probability).
5457 EXPECT_NE(ciphertext1, ciphertext2);
5458
5459 string plaintext1 = DecryptMessage(ciphertext1, params);
5460 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5461 string plaintext2 = DecryptMessage(ciphertext2, params);
5462 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5463
5464 // Decrypting corrupted ciphertext should fail.
5465 size_t offset_to_corrupt = random() % ciphertext1.size();
5466 char corrupt_byte;
5467 do {
5468 corrupt_byte = static_cast<char>(random() % 256);
5469 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5470 ciphertext1[offset_to_corrupt] = corrupt_byte;
5471
5472 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5473 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005474 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005475 EXPECT_EQ(0U, result.size());
5476 }
5477}
5478
5479/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005480 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5481 *
5482 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5483 * specified, defaulting to SHA-1.
5484 */
5485TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5486 size_t key_size = 2048;
5487 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5488 .Authorization(TAG_NO_AUTH_REQUIRED)
5489 .RsaEncryptionKey(key_size, 65537)
5490 .Padding(PaddingMode::RSA_OAEP)
5491 .Digest(Digest::SHA_2_256)
5492 .SetDefaultValidity()));
5493
Prashant Patil2114dca2023-09-21 14:57:10 +00005494 vector defaultDigest = vector{Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005495 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005496 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005497
David Drysdaleae3727b2021-11-11 09:00:14 +00005498 // Do local RSA encryption using the default MGF digest of SHA-1.
5499 string message = "Hello";
5500 auto params =
5501 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5502 string ciphertext = LocalRsaEncryptMessage(message, params);
5503 EXPECT_EQ(key_size / 8, ciphertext.size());
5504
5505 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5506 string plaintext = DecryptMessage(ciphertext, params);
5507 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5508
5509 // Decrypting corrupted ciphertext should fail.
5510 size_t offset_to_corrupt = random() % ciphertext.size();
5511 char corrupt_byte;
5512 do {
5513 corrupt_byte = static_cast<char>(random() % 256);
5514 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5515 ciphertext[offset_to_corrupt] = corrupt_byte;
5516
5517 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5518 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005519 EXPECT_NE(ErrorCode::OK, Finish(ciphertext, &result));
David Drysdaleae3727b2021-11-11 09:00:14 +00005520 EXPECT_EQ(0U, result.size());
5521}
5522
5523/*
5524 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5525 *
5526 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5527 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5528 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5529 */
5530TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5531 size_t key_size = 2048;
Prashant Patil2114dca2023-09-21 14:57:10 +00005532 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005533 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5534 .Authorization(TAG_NO_AUTH_REQUIRED)
Prashant Patil2114dca2023-09-21 14:57:10 +00005535 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005536 .RsaEncryptionKey(key_size, 65537)
5537 .Padding(PaddingMode::RSA_OAEP)
5538 .Digest(Digest::SHA_2_256)
5539 .SetDefaultValidity()));
5540
5541 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005542 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
5543 vector defaultDigest = vector{Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005544 // Make sure default mgf-digest is not included in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005545 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
David Drysdaleae3727b2021-11-11 09:00:14 +00005546
5547 // Do local RSA encryption using the default MGF digest of SHA-1.
5548 string message = "Hello";
5549 auto params =
5550 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5551 string ciphertext = LocalRsaEncryptMessage(message, params);
5552 EXPECT_EQ(key_size / 8, ciphertext.size());
5553
5554 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5555 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5556 // is checked against those values, and found absent.
5557 auto result = Begin(KeyPurpose::DECRYPT, params);
5558 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5559 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5560}
5561
5562/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005563 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5564 *
David Drysdale59cae642021-05-12 13:52:03 +01005565 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005566 * with incompatible MGF digest.
5567 */
5568TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
Prashant Patil2114dca2023-09-21 14:57:10 +00005569 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005570 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Prashant Patil2114dca2023-09-21 14:57:10 +00005571 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005572 .Authorization(TAG_NO_AUTH_REQUIRED)
5573 .RsaEncryptionKey(2048, 65537)
5574 .Padding(PaddingMode::RSA_OAEP)
5575 .Digest(Digest::SHA_2_256)
5576 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005577
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005578 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005579 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005580
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005581 string message = "Hello World!";
5582
5583 auto params = AuthorizationSetBuilder()
5584 .Padding(PaddingMode::RSA_OAEP)
5585 .Digest(Digest::SHA_2_256)
5586 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005587 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005588}
5589
5590/*
5591 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5592 *
5593 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5594 * with unsupported MGF digest.
5595 */
5596TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
Prashant Patil2114dca2023-09-21 14:57:10 +00005597 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005598 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Prashant Patil2114dca2023-09-21 14:57:10 +00005599 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005600 .Authorization(TAG_NO_AUTH_REQUIRED)
5601 .RsaEncryptionKey(2048, 65537)
5602 .Padding(PaddingMode::RSA_OAEP)
5603 .Digest(Digest::SHA_2_256)
5604 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005605
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005606 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005607 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005608
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005609 string message = "Hello World!";
5610
5611 auto params = AuthorizationSetBuilder()
5612 .Padding(PaddingMode::RSA_OAEP)
5613 .Digest(Digest::SHA_2_256)
5614 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005615 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005616}
5617
5618/*
Selene Huang31ab4042020-04-29 04:22:39 -07005619 * EncryptionOperationsTest.RsaPkcs1Success
5620 *
5621 * Verifies that RSA PKCS encryption/decrypts works.
5622 */
5623TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5624 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5625 .Authorization(TAG_NO_AUTH_REQUIRED)
5626 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005627 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5628 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005629
5630 string message = "Hello World!";
5631 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005632 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005633 EXPECT_EQ(2048U / 8, ciphertext1.size());
5634
David Drysdale59cae642021-05-12 13:52:03 +01005635 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005636 EXPECT_EQ(2048U / 8, ciphertext2.size());
5637
5638 // PKCS1 v1.5 randomizes padding so every result should be different.
5639 EXPECT_NE(ciphertext1, ciphertext2);
5640
5641 string plaintext = DecryptMessage(ciphertext1, params);
5642 EXPECT_EQ(message, plaintext);
5643
5644 // Decrypting corrupted ciphertext should fail.
5645 size_t offset_to_corrupt = random() % ciphertext1.size();
5646 char corrupt_byte;
5647 do {
5648 corrupt_byte = static_cast<char>(random() % 256);
5649 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5650 ciphertext1[offset_to_corrupt] = corrupt_byte;
5651
5652 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5653 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005654 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005655 EXPECT_EQ(0U, result.size());
5656}
5657
5658/*
Selene Huang31ab4042020-04-29 04:22:39 -07005659 * EncryptionOperationsTest.EcdsaEncrypt
5660 *
5661 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5662 */
5663TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5664 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5665 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005666 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005667 .Digest(Digest::NONE)
5668 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005669 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5670 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5671 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5672}
5673
5674/*
5675 * EncryptionOperationsTest.HmacEncrypt
5676 *
5677 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5678 */
5679TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5680 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5681 .Authorization(TAG_NO_AUTH_REQUIRED)
5682 .HmacKey(128)
5683 .Digest(Digest::SHA_2_256)
5684 .Padding(PaddingMode::NONE)
5685 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5686 auto params = AuthorizationSetBuilder()
5687 .Digest(Digest::SHA_2_256)
5688 .Padding(PaddingMode::NONE)
5689 .Authorization(TAG_MAC_LENGTH, 128);
5690 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5691 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5692}
5693
5694/*
5695 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5696 *
5697 * Verifies that AES ECB mode works.
5698 */
5699TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5700 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5701 .Authorization(TAG_NO_AUTH_REQUIRED)
5702 .AesEncryptionKey(128)
5703 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5704 .Padding(PaddingMode::NONE)));
5705
5706 ASSERT_GT(key_blob_.size(), 0U);
5707 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5708
5709 // Two-block message.
5710 string message = "12345678901234567890123456789012";
5711 string ciphertext1 = EncryptMessage(message, params);
5712 EXPECT_EQ(message.size(), ciphertext1.size());
5713
5714 string ciphertext2 = EncryptMessage(string(message), params);
5715 EXPECT_EQ(message.size(), ciphertext2.size());
5716
5717 // ECB is deterministic.
5718 EXPECT_EQ(ciphertext1, ciphertext2);
5719
5720 string plaintext = DecryptMessage(ciphertext1, params);
5721 EXPECT_EQ(message, plaintext);
5722}
5723
5724/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005725 * EncryptionOperationsTest.AesEcbUnknownTag
5726 *
5727 * Verifies that AES ECB operations ignore unknown tags.
5728 */
5729TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5730 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5731 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5732 KeyParameter unknown_param;
5733 unknown_param.tag = unknown_tag;
5734
5735 vector<KeyCharacteristics> key_characteristics;
5736 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5737 .Authorization(TAG_NO_AUTH_REQUIRED)
5738 .AesEncryptionKey(128)
5739 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5740 .Padding(PaddingMode::NONE)
5741 .Authorization(unknown_param),
5742 &key_blob_, &key_characteristics));
5743 ASSERT_GT(key_blob_.size(), 0U);
5744
5745 // Unknown tags should not be returned in key characteristics.
5746 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5747 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5748 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5749 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5750
5751 // Encrypt without mentioning the unknown parameter.
5752 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5753 string message = "12345678901234567890123456789012";
5754 string ciphertext = EncryptMessage(message, params);
5755 EXPECT_EQ(message.size(), ciphertext.size());
5756
5757 // Decrypt including the unknown parameter.
5758 auto decrypt_params = AuthorizationSetBuilder()
5759 .BlockMode(BlockMode::ECB)
5760 .Padding(PaddingMode::NONE)
5761 .Authorization(unknown_param);
5762 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5763 EXPECT_EQ(message, plaintext);
5764}
5765
5766/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005767 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005768 *
5769 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5770 */
5771TEST_P(EncryptionOperationsTest, AesWrongMode) {
5772 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5773 .Authorization(TAG_NO_AUTH_REQUIRED)
5774 .AesEncryptionKey(128)
5775 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5776 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005777 ASSERT_GT(key_blob_.size(), 0U);
5778
Selene Huang31ab4042020-04-29 04:22:39 -07005779 EXPECT_EQ(
5780 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5781 Begin(KeyPurpose::ENCRYPT,
5782 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5783}
5784
5785/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005786 * EncryptionOperationsTest.AesWrongPadding
5787 *
5788 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5789 */
5790TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5791 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5792 .Authorization(TAG_NO_AUTH_REQUIRED)
5793 .AesEncryptionKey(128)
5794 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5795 .Padding(PaddingMode::NONE)));
5796 ASSERT_GT(key_blob_.size(), 0U);
5797
5798 EXPECT_EQ(
5799 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5800 Begin(KeyPurpose::ENCRYPT,
5801 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5802}
5803
5804/*
5805 * EncryptionOperationsTest.AesInvalidParams
5806 *
5807 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5808 */
5809TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5810 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5811 .Authorization(TAG_NO_AUTH_REQUIRED)
5812 .AesEncryptionKey(128)
5813 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5814 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5815 .Padding(PaddingMode::NONE)
5816 .Padding(PaddingMode::PKCS7)));
5817 ASSERT_GT(key_blob_.size(), 0U);
5818
5819 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5820 .BlockMode(BlockMode::CBC)
5821 .BlockMode(BlockMode::ECB)
5822 .Padding(PaddingMode::NONE));
5823 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5824 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5825
5826 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5827 .BlockMode(BlockMode::ECB)
5828 .Padding(PaddingMode::NONE)
5829 .Padding(PaddingMode::PKCS7));
5830 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5831 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5832}
5833
5834/*
Selene Huang31ab4042020-04-29 04:22:39 -07005835 * EncryptionOperationsTest.AesWrongPurpose
5836 *
5837 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5838 * specified.
5839 */
5840TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5841 auto err = GenerateKey(AuthorizationSetBuilder()
5842 .Authorization(TAG_NO_AUTH_REQUIRED)
5843 .AesKey(128)
5844 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5845 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5846 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5847 .Padding(PaddingMode::NONE));
5848 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5849 ASSERT_GT(key_blob_.size(), 0U);
5850
5851 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5852 .BlockMode(BlockMode::GCM)
5853 .Padding(PaddingMode::NONE)
5854 .Authorization(TAG_MAC_LENGTH, 128));
5855 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5856
5857 CheckedDeleteKey();
5858
5859 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5860 .Authorization(TAG_NO_AUTH_REQUIRED)
5861 .AesKey(128)
5862 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5863 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5864 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5865 .Padding(PaddingMode::NONE)));
5866
5867 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5868 .BlockMode(BlockMode::GCM)
5869 .Padding(PaddingMode::NONE)
5870 .Authorization(TAG_MAC_LENGTH, 128));
5871 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5872}
5873
5874/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005875 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005876 *
5877 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5878 * multiple of the block size and no padding is specified.
5879 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005880TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5881 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005882 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005883 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5884 .Authorization(TAG_NO_AUTH_REQUIRED)
5885 .AesEncryptionKey(128)
5886 .Authorization(TAG_BLOCK_MODE, blockMode)
5887 .Padding(PaddingMode::NONE)));
5888 // Message is slightly shorter than two blocks.
5889 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005890
David Drysdaled2cc8c22021-04-15 13:29:45 +01005891 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5892 AuthorizationSet out_params;
5893 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5894 string ciphertext;
5895 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5896 EXPECT_EQ(0U, ciphertext.size());
5897
5898 CheckedDeleteKey();
5899 }
Selene Huang31ab4042020-04-29 04:22:39 -07005900}
5901
5902/*
5903 * EncryptionOperationsTest.AesEcbPkcs7Padding
5904 *
5905 * Verifies that AES PKCS7 padding works for any message length.
5906 */
5907TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5908 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5909 .Authorization(TAG_NO_AUTH_REQUIRED)
5910 .AesEncryptionKey(128)
5911 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5912 .Padding(PaddingMode::PKCS7)));
5913
5914 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5915
5916 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005917 for (size_t i = 0; i <= 48; i++) {
5918 SCOPED_TRACE(testing::Message() << "i = " << i);
5919 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5920 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005921 string ciphertext = EncryptMessage(message, params);
5922 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5923 string plaintext = DecryptMessage(ciphertext, params);
5924 EXPECT_EQ(message, plaintext);
5925 }
5926}
5927
5928/*
5929 * EncryptionOperationsTest.AesEcbWrongPadding
5930 *
5931 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5932 * specified.
5933 */
5934TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5935 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5936 .Authorization(TAG_NO_AUTH_REQUIRED)
5937 .AesEncryptionKey(128)
5938 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5939 .Padding(PaddingMode::NONE)));
5940
5941 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5942
5943 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005944 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005945 string message(i, 'a');
5946 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5947 }
5948}
5949
5950/*
5951 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5952 *
5953 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5954 */
5955TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5956 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5957 .Authorization(TAG_NO_AUTH_REQUIRED)
5958 .AesEncryptionKey(128)
5959 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5960 .Padding(PaddingMode::PKCS7)));
5961
5962 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5963
5964 string message = "a";
5965 string ciphertext = EncryptMessage(message, params);
5966 EXPECT_EQ(16U, ciphertext.size());
5967 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005968
Seth Moore7a55ae32021-06-23 14:28:11 -07005969 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5970 ++ciphertext[ciphertext.size() / 2];
5971
5972 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5973 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005974 ErrorCode error = Finish(ciphertext, &plaintext);
5975 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005976 // This is the expected error, we can exit the test now.
5977 return;
5978 } else {
5979 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005980 ASSERT_EQ(error, ErrorCode::OK)
5981 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005982 }
5983 }
5984 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005985}
5986
David Drysdaleb8093292022-04-08 12:22:35 +01005987/*
5988 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5989 *
5990 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5991 */
5992TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5993 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5994 .Authorization(TAG_NO_AUTH_REQUIRED)
5995 .AesEncryptionKey(128)
5996 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5997 .Padding(PaddingMode::PKCS7)));
5998
5999 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6000
6001 string message = "a";
6002 string ciphertext = EncryptMessage(message, params);
6003 EXPECT_EQ(16U, ciphertext.size());
6004 EXPECT_NE(ciphertext, message);
6005
6006 // Shorten the ciphertext.
6007 ciphertext.resize(ciphertext.size() - 1);
6008 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6009 string plaintext;
6010 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
6011}
6012
Selene Huang31ab4042020-04-29 04:22:39 -07006013vector<uint8_t> CopyIv(const AuthorizationSet& set) {
6014 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006015 EXPECT_TRUE(iv);
6016 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07006017}
6018
6019/*
6020 * EncryptionOperationsTest.AesCtrRoundTripSuccess
6021 *
6022 * Verifies that AES CTR mode works.
6023 */
6024TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
6025 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6026 .Authorization(TAG_NO_AUTH_REQUIRED)
6027 .AesEncryptionKey(128)
6028 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6029 .Padding(PaddingMode::NONE)));
6030
6031 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6032
6033 string message = "123";
6034 AuthorizationSet out_params;
6035 string ciphertext1 = EncryptMessage(message, params, &out_params);
6036 vector<uint8_t> iv1 = CopyIv(out_params);
6037 EXPECT_EQ(16U, iv1.size());
6038
6039 EXPECT_EQ(message.size(), ciphertext1.size());
6040
6041 out_params.Clear();
6042 string ciphertext2 = EncryptMessage(message, params, &out_params);
6043 vector<uint8_t> iv2 = CopyIv(out_params);
6044 EXPECT_EQ(16U, iv2.size());
6045
6046 // IVs should be random, so ciphertexts should differ.
6047 EXPECT_NE(ciphertext1, ciphertext2);
6048
6049 auto params_iv1 =
6050 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
6051 auto params_iv2 =
6052 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
6053
6054 string plaintext = DecryptMessage(ciphertext1, params_iv1);
6055 EXPECT_EQ(message, plaintext);
6056 plaintext = DecryptMessage(ciphertext2, params_iv2);
6057 EXPECT_EQ(message, plaintext);
6058
6059 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
6060 plaintext = DecryptMessage(ciphertext1, params_iv2);
6061 EXPECT_NE(message, plaintext);
6062 plaintext = DecryptMessage(ciphertext2, params_iv1);
6063 EXPECT_NE(message, plaintext);
6064}
6065
6066/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306067 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07006068 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306069 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07006070 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306071TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
6072 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
6073}
Selene Huang31ab4042020-04-29 04:22:39 -07006074
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306075/*
6076 * EncryptionOperationsTest.AesCbcIncremental
6077 *
6078 * Verifies that AES works for CBC block mode, when provided data in various size increments.
6079 */
6080TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
6081 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
6082}
Selene Huang31ab4042020-04-29 04:22:39 -07006083
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306084/*
6085 * EncryptionOperationsTest.AesCtrIncremental
6086 *
6087 * Verifies that AES works for CTR block mode, when provided data in various size increments.
6088 */
6089TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
6090 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
6091}
Selene Huang31ab4042020-04-29 04:22:39 -07006092
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306093/*
6094 * EncryptionOperationsTest.AesGcmIncremental
6095 *
6096 * Verifies that AES works for GCM block mode, when provided data in various size increments.
6097 */
6098TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
6099 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07006100}
6101
Prashant Patildd5f7f02022-07-06 18:58:07 +00006102/*
6103 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
6104 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6105 */
6106TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
6107 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
6108 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
6109 string kat_plaintext =
6110 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
6111 "809FFF37081C22EF278F896AB213A2A631");
6112 string kat_ciphertext =
6113 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
6114 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
6115 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6116 kat_ciphertext);
6117}
6118
6119/*
6120 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
6121 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6122 */
6123TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
6124 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
6125 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
6126 string kat_plaintext =
6127 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
6128 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
6129 string kat_ciphertext =
6130 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
6131 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
6132 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6133 kat_plaintext, kat_ciphertext);
6134}
6135
6136/*
6137 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
6138 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6139 */
6140TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
6141 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
6142 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
6143 string kat_plaintext =
6144 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
6145 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
6146 string kat_ciphertext =
6147 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
6148 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
6149 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6150 kat_ciphertext);
6151}
6152
6153/*
6154 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
6155 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6156 */
6157TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
6158 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
6159 string kat_plaintext =
6160 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
6161 "7B6168A9A27BCE554BEA94EF26E6C742A0");
6162 string kat_ciphertext =
6163 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
6164 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
6165 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6166 kat_ciphertext);
6167}
6168
6169/*
6170 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
6171 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6172 */
6173TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
6174 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
6175 string kat_plaintext =
6176 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
6177 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
6178 string kat_ciphertext =
6179 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6180 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6181 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6182 kat_ciphertext);
6183}
6184
6185/*
6186 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6187 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6188 */
6189TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6190 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6191 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6192 string kat_plaintext =
6193 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6194 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6195 string kat_ciphertext =
6196 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6197 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6198 "bdfcc0cba0");
6199
6200 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6201 kat_ciphertext);
6202}
6203
6204/*
6205 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6206 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6207 */
6208TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6209 if (SecLevel() == SecurityLevel::STRONGBOX) {
6210 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6211 }
6212 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6213 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6214 string kat_plaintext =
6215 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6216 "167f2497c994bd496eb80bfb2ba2c9d5af");
6217 string kat_ciphertext =
6218 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6219 "72c134552f3a138e726fbe493b3a839598");
6220 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6221 kat_ciphertext);
6222}
6223
6224/*
6225 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6226 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6227 */
6228TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6229 if (SecLevel() == SecurityLevel::STRONGBOX) {
6230 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6231 }
6232 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6233 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6234 string kat_plaintext =
6235 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6236 "b170");
6237 string kat_ciphertext =
6238 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6239 "4e3884138ff403a41fd99818708ada301c");
6240 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6241 kat_plaintext, kat_ciphertext);
6242}
6243
6244/*
6245 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6246 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6247 */
6248TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6249 if (SecLevel() == SecurityLevel::STRONGBOX) {
6250 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6251 }
6252 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6253 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6254 string kat_plaintext =
6255 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6256 "28091e09cdbbd3b42b");
6257 string kat_ciphertext =
6258 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6259 "2ae0f90f0c19f42b4a");
6260 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6261 kat_ciphertext);
6262}
6263
6264/*
6265 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6266 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6267 */
6268TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6269 if (SecLevel() == SecurityLevel::STRONGBOX) {
6270 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6271 }
6272 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6273 string kat_plaintext =
6274 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6275 "44ab");
6276 string kat_ciphertext =
6277 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6278 "2453");
6279 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6280 kat_ciphertext);
6281}
6282
6283/*
6284 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6285 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6286 */
6287TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6288 if (SecLevel() == SecurityLevel::STRONGBOX) {
6289 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6290 }
6291 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6292 string kat_plaintext =
6293 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6294 "e2c7");
6295 string kat_ciphertext =
6296 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6297 "bb7e3a889dd4a9589098b44acf1056e7aa");
6298 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6299 kat_ciphertext);
6300}
6301
6302/*
6303 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6304 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6305 */
6306TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6307 if (SecLevel() == SecurityLevel::STRONGBOX) {
6308 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6309 }
6310 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6311 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6312 string kat_plaintext =
6313 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6314 "ff52");
6315 string kat_ciphertext =
6316 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6317 "1413ad70fb0e1970669095ad77ebb5974ae8");
6318
6319 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6320 kat_ciphertext);
6321}
6322
6323/*
6324 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6325 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6326 */
6327TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6328 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6329 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6330 string kat_plaintext =
6331 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6332 "494cb53caca353e4b637ba05687be20f8d");
6333 string kat_ciphertext =
6334 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6335 "6047da1e4fd7c4e1cf2656097f75ae8685");
6336 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6337 kat_ciphertext);
6338}
6339
6340/*
6341 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6342 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6343 */
6344TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6345 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6346 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6347 string kat_plaintext =
6348 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6349 "2545a82b73c48078b9dae62261c65909");
6350 string kat_ciphertext =
6351 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6352 "9403a71987b95124073d69f2a3cb95b0ab");
6353 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6354 kat_plaintext, kat_ciphertext);
6355}
6356
6357/*
6358 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6359 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6360 */
6361TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6362 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6363 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6364 string kat_plaintext =
6365 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6366 "1f6db3c884");
6367 string kat_ciphertext =
6368 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6369 "a7be30d4c3");
6370 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6371 kat_ciphertext);
6372}
6373
6374/*
6375 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6376 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6377 */
6378TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6379 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6380 string kat_plaintext =
6381 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6382 "31a476d6806b8116089c6ec50bb543200f");
6383 string kat_ciphertext =
6384 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6385 "c83e377faf246288931136bef2a07c0be4");
6386 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6387 kat_ciphertext);
6388}
6389
6390/*
6391 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6392 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6393 */
6394TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6395 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6396 string kat_plaintext =
6397 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6398 "6f");
6399 string kat_ciphertext =
6400 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6401 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6402 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6403 kat_ciphertext);
6404}
6405
6406/*
6407 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6408 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6409 */
6410TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6411 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6412 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6413 string kat_plaintext =
6414 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6415 "f0");
6416 string kat_ciphertext =
6417 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6418 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6419
6420 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6421 kat_ciphertext);
6422}
6423
Selene Huang31ab4042020-04-29 04:22:39 -07006424struct AesCtrSp80038aTestVector {
6425 const char* key;
6426 const char* nonce;
6427 const char* plaintext;
6428 const char* ciphertext;
6429};
6430
6431// These test vectors are taken from
6432// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6433static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6434 // AES-128
6435 {
6436 "2b7e151628aed2a6abf7158809cf4f3c",
6437 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6438 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6439 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6440 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6441 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6442 },
6443 // AES-192
6444 {
6445 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6446 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6447 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6448 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6449 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6450 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6451 },
6452 // AES-256
6453 {
6454 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6455 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6456 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6457 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6458 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6459 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6460 },
6461};
6462
6463/*
6464 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6465 *
6466 * Verifies AES CTR implementation against SP800-38A test vectors.
6467 */
6468TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6469 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6470 for (size_t i = 0; i < 3; i++) {
6471 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6472 const string key = hex2str(test.key);
6473 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6474 InvalidSizes.end())
6475 continue;
6476 const string nonce = hex2str(test.nonce);
6477 const string plaintext = hex2str(test.plaintext);
6478 const string ciphertext = hex2str(test.ciphertext);
6479 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6480 }
6481}
6482
6483/*
6484 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6485 *
6486 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6487 */
6488TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6489 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6490 .Authorization(TAG_NO_AUTH_REQUIRED)
6491 .AesEncryptionKey(128)
6492 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6493 .Padding(PaddingMode::PKCS7)));
6494 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6495 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6496}
6497
6498/*
6499 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6500 *
6501 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6502 */
6503TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6504 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6505 .Authorization(TAG_NO_AUTH_REQUIRED)
6506 .AesEncryptionKey(128)
6507 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6508 .Authorization(TAG_CALLER_NONCE)
6509 .Padding(PaddingMode::NONE)));
6510
6511 auto params = AuthorizationSetBuilder()
6512 .BlockMode(BlockMode::CTR)
6513 .Padding(PaddingMode::NONE)
6514 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6515 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6516
6517 params = AuthorizationSetBuilder()
6518 .BlockMode(BlockMode::CTR)
6519 .Padding(PaddingMode::NONE)
6520 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6521 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6522
6523 params = AuthorizationSetBuilder()
6524 .BlockMode(BlockMode::CTR)
6525 .Padding(PaddingMode::NONE)
6526 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6527 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6528}
6529
6530/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006531 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006532 *
6533 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6534 */
6535TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6536 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6537 .Authorization(TAG_NO_AUTH_REQUIRED)
6538 .AesEncryptionKey(128)
6539 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6540 .Padding(PaddingMode::NONE)));
6541 // Two-block message.
6542 string message = "12345678901234567890123456789012";
6543 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6544 AuthorizationSet out_params;
6545 string ciphertext1 = EncryptMessage(message, params, &out_params);
6546 vector<uint8_t> iv1 = CopyIv(out_params);
6547 EXPECT_EQ(message.size(), ciphertext1.size());
6548
6549 out_params.Clear();
6550
6551 string ciphertext2 = EncryptMessage(message, params, &out_params);
6552 vector<uint8_t> iv2 = CopyIv(out_params);
6553 EXPECT_EQ(message.size(), ciphertext2.size());
6554
6555 // IVs should be random, so ciphertexts should differ.
6556 EXPECT_NE(ciphertext1, ciphertext2);
6557
6558 params.push_back(TAG_NONCE, iv1);
6559 string plaintext = DecryptMessage(ciphertext1, params);
6560 EXPECT_EQ(message, plaintext);
6561}
6562
6563/*
Tommy Chiuee705692021-09-23 20:09:13 +08006564 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6565 *
6566 * Verifies that keymaster generates correct output on zero-input with
6567 * NonePadding mode
6568 */
6569TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6570 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6571 .Authorization(TAG_NO_AUTH_REQUIRED)
6572 .AesEncryptionKey(128)
6573 .BlockMode(BlockMode::CBC)
6574 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6575
6576 // Zero input message
6577 string message = "";
6578 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006579 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006580 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6581 AuthorizationSet out_params;
6582 string ciphertext1 = EncryptMessage(message, params, &out_params);
6583 vector<uint8_t> iv1 = CopyIv(out_params);
6584 if (padding == PaddingMode::NONE)
6585 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6586 else
6587 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6588
6589 out_params.Clear();
6590
6591 string ciphertext2 = EncryptMessage(message, params, &out_params);
6592 vector<uint8_t> iv2 = CopyIv(out_params);
6593 if (padding == PaddingMode::NONE)
6594 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6595 else
6596 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6597
6598 // IVs should be random
6599 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6600
6601 params.push_back(TAG_NONCE, iv1);
6602 string plaintext = DecryptMessage(ciphertext1, params);
6603 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6604 }
6605}
6606
6607/*
Selene Huang31ab4042020-04-29 04:22:39 -07006608 * EncryptionOperationsTest.AesCallerNonce
6609 *
6610 * Verifies that AES caller-provided nonces work correctly.
6611 */
6612TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6613 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6614 .Authorization(TAG_NO_AUTH_REQUIRED)
6615 .AesEncryptionKey(128)
6616 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6617 .Authorization(TAG_CALLER_NONCE)
6618 .Padding(PaddingMode::NONE)));
6619
6620 string message = "12345678901234567890123456789012";
6621
6622 // Don't specify nonce, should get a random one.
6623 AuthorizationSetBuilder params =
6624 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6625 AuthorizationSet out_params;
6626 string ciphertext = EncryptMessage(message, params, &out_params);
6627 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006628 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006629
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006630 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006631 string plaintext = DecryptMessage(ciphertext, params);
6632 EXPECT_EQ(message, plaintext);
6633
6634 // Now specify a nonce, should also work.
6635 params = AuthorizationSetBuilder()
6636 .BlockMode(BlockMode::CBC)
6637 .Padding(PaddingMode::NONE)
6638 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6639 out_params.Clear();
6640 ciphertext = EncryptMessage(message, params, &out_params);
6641
6642 // Decrypt with correct nonce.
6643 plaintext = DecryptMessage(ciphertext, params);
6644 EXPECT_EQ(message, plaintext);
6645
6646 // Try with wrong nonce.
6647 params = AuthorizationSetBuilder()
6648 .BlockMode(BlockMode::CBC)
6649 .Padding(PaddingMode::NONE)
6650 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6651 plaintext = DecryptMessage(ciphertext, params);
6652 EXPECT_NE(message, plaintext);
6653}
6654
6655/*
6656 * EncryptionOperationsTest.AesCallerNonceProhibited
6657 *
6658 * Verifies that caller-provided nonces are not permitted when not specified in the key
6659 * authorizations.
6660 */
6661TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6662 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6663 .Authorization(TAG_NO_AUTH_REQUIRED)
6664 .AesEncryptionKey(128)
6665 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6666 .Padding(PaddingMode::NONE)));
6667
6668 string message = "12345678901234567890123456789012";
6669
6670 // Don't specify nonce, should get a random one.
6671 AuthorizationSetBuilder params =
6672 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6673 AuthorizationSet out_params;
6674 string ciphertext = EncryptMessage(message, params, &out_params);
6675 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006676 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006677
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006678 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006679 string plaintext = DecryptMessage(ciphertext, params);
6680 EXPECT_EQ(message, plaintext);
6681
6682 // Now specify a nonce, should fail
6683 params = AuthorizationSetBuilder()
6684 .BlockMode(BlockMode::CBC)
6685 .Padding(PaddingMode::NONE)
6686 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6687 out_params.Clear();
6688 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6689}
6690
6691/*
6692 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6693 *
6694 * Verifies that AES GCM mode works.
6695 */
6696TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6697 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6698 .Authorization(TAG_NO_AUTH_REQUIRED)
6699 .AesEncryptionKey(128)
6700 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6701 .Padding(PaddingMode::NONE)
6702 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6703
6704 string aad = "foobar";
6705 string message = "123456789012345678901234567890123456";
6706
6707 auto begin_params = AuthorizationSetBuilder()
6708 .BlockMode(BlockMode::GCM)
6709 .Padding(PaddingMode::NONE)
6710 .Authorization(TAG_MAC_LENGTH, 128);
6711
Selene Huang31ab4042020-04-29 04:22:39 -07006712 // Encrypt
6713 AuthorizationSet begin_out_params;
6714 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6715 << "Begin encrypt";
6716 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006717 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6718 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006719 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6720
6721 // Grab nonce
6722 begin_params.push_back(begin_out_params);
6723
6724 // Decrypt.
6725 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006726 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006727 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006728 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006729 EXPECT_EQ(message.length(), plaintext.length());
6730 EXPECT_EQ(message, plaintext);
6731}
6732
6733/*
6734 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6735 *
6736 * Verifies that AES GCM mode works, even when there's a long delay
6737 * between operations.
6738 */
6739TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6740 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6741 .Authorization(TAG_NO_AUTH_REQUIRED)
6742 .AesEncryptionKey(128)
6743 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6744 .Padding(PaddingMode::NONE)
6745 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6746
6747 string aad = "foobar";
6748 string message = "123456789012345678901234567890123456";
6749
6750 auto begin_params = AuthorizationSetBuilder()
6751 .BlockMode(BlockMode::GCM)
6752 .Padding(PaddingMode::NONE)
6753 .Authorization(TAG_MAC_LENGTH, 128);
6754
Selene Huang31ab4042020-04-29 04:22:39 -07006755 // Encrypt
6756 AuthorizationSet begin_out_params;
6757 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6758 << "Begin encrypt";
6759 string ciphertext;
6760 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006761 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006762 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006763 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006764
6765 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6766
6767 // Grab nonce
6768 begin_params.push_back(begin_out_params);
6769
6770 // Decrypt.
6771 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6772 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006773 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006774 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006775 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006776 sleep(5);
6777 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6778 EXPECT_EQ(message.length(), plaintext.length());
6779 EXPECT_EQ(message, plaintext);
6780}
6781
6782/*
6783 * EncryptionOperationsTest.AesGcmDifferentNonces
6784 *
6785 * Verifies that encrypting the same data with different nonces produces different outputs.
6786 */
6787TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6788 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6789 .Authorization(TAG_NO_AUTH_REQUIRED)
6790 .AesEncryptionKey(128)
6791 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6792 .Padding(PaddingMode::NONE)
6793 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6794 .Authorization(TAG_CALLER_NONCE)));
6795
6796 string aad = "foobar";
6797 string message = "123456789012345678901234567890123456";
6798 string nonce1 = "000000000000";
6799 string nonce2 = "111111111111";
6800 string nonce3 = "222222222222";
6801
6802 string ciphertext1 =
6803 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6804 string ciphertext2 =
6805 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6806 string ciphertext3 =
6807 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6808
6809 ASSERT_NE(ciphertext1, ciphertext2);
6810 ASSERT_NE(ciphertext1, ciphertext3);
6811 ASSERT_NE(ciphertext2, ciphertext3);
6812}
6813
6814/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006815 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6816 *
6817 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6818 */
6819TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6820 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6821 .Authorization(TAG_NO_AUTH_REQUIRED)
6822 .AesEncryptionKey(128)
6823 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6824 .Padding(PaddingMode::NONE)
6825 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6826
6827 string aad = "foobar";
6828 string message = "123456789012345678901234567890123456";
6829
6830 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6831 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6832 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6833
6834 ASSERT_NE(ciphertext1, ciphertext2);
6835 ASSERT_NE(ciphertext1, ciphertext3);
6836 ASSERT_NE(ciphertext2, ciphertext3);
6837}
6838
6839/*
Selene Huang31ab4042020-04-29 04:22:39 -07006840 * EncryptionOperationsTest.AesGcmTooShortTag
6841 *
6842 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6843 */
6844TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6845 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6846 .Authorization(TAG_NO_AUTH_REQUIRED)
6847 .AesEncryptionKey(128)
6848 .BlockMode(BlockMode::GCM)
6849 .Padding(PaddingMode::NONE)
6850 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6851 string message = "123456789012345678901234567890123456";
6852 auto params = AuthorizationSetBuilder()
6853 .BlockMode(BlockMode::GCM)
6854 .Padding(PaddingMode::NONE)
6855 .Authorization(TAG_MAC_LENGTH, 96);
6856
6857 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6858}
6859
6860/*
6861 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6862 *
6863 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6864 */
6865TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6866 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6867 .Authorization(TAG_NO_AUTH_REQUIRED)
6868 .AesEncryptionKey(128)
6869 .BlockMode(BlockMode::GCM)
6870 .Padding(PaddingMode::NONE)
6871 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6872 string aad = "foobar";
6873 string message = "123456789012345678901234567890123456";
6874 auto params = AuthorizationSetBuilder()
6875 .BlockMode(BlockMode::GCM)
6876 .Padding(PaddingMode::NONE)
6877 .Authorization(TAG_MAC_LENGTH, 128);
6878
Selene Huang31ab4042020-04-29 04:22:39 -07006879 // Encrypt
6880 AuthorizationSet begin_out_params;
6881 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6882 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006883 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006884
6885 AuthorizationSet finish_out_params;
6886 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006887 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6888 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006889
6890 params = AuthorizationSetBuilder()
6891 .Authorizations(begin_out_params)
6892 .BlockMode(BlockMode::GCM)
6893 .Padding(PaddingMode::NONE)
6894 .Authorization(TAG_MAC_LENGTH, 96);
6895
6896 // Decrypt.
6897 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6898}
6899
6900/*
6901 * EncryptionOperationsTest.AesGcmCorruptKey
6902 *
6903 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6904 */
6905TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6906 const uint8_t nonce_bytes[] = {
6907 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6908 };
6909 string nonce = make_string(nonce_bytes);
6910 const uint8_t ciphertext_bytes[] = {
6911 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6912 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6913 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6914 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6915 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6916 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6917 };
6918 string ciphertext = make_string(ciphertext_bytes);
6919
6920 auto params = AuthorizationSetBuilder()
6921 .BlockMode(BlockMode::GCM)
6922 .Padding(PaddingMode::NONE)
6923 .Authorization(TAG_MAC_LENGTH, 128)
6924 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6925
6926 auto import_params = AuthorizationSetBuilder()
6927 .Authorization(TAG_NO_AUTH_REQUIRED)
6928 .AesEncryptionKey(128)
6929 .BlockMode(BlockMode::GCM)
6930 .Padding(PaddingMode::NONE)
6931 .Authorization(TAG_CALLER_NONCE)
6932 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6933
6934 // Import correct key and decrypt
6935 const uint8_t key_bytes[] = {
6936 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6937 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6938 };
6939 string key = make_string(key_bytes);
6940 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6941 string plaintext = DecryptMessage(ciphertext, params);
6942 CheckedDeleteKey();
6943
6944 // Corrupt key and attempt to decrypt
6945 key[0] = 0;
6946 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6947 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6948 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6949 CheckedDeleteKey();
6950}
6951
6952/*
6953 * EncryptionOperationsTest.AesGcmAadNoData
6954 *
6955 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6956 * encrypt.
6957 */
6958TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6959 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6960 .Authorization(TAG_NO_AUTH_REQUIRED)
6961 .AesEncryptionKey(128)
6962 .BlockMode(BlockMode::GCM)
6963 .Padding(PaddingMode::NONE)
6964 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6965
6966 string aad = "1234567890123456";
6967 auto params = AuthorizationSetBuilder()
6968 .BlockMode(BlockMode::GCM)
6969 .Padding(PaddingMode::NONE)
6970 .Authorization(TAG_MAC_LENGTH, 128);
6971
Selene Huang31ab4042020-04-29 04:22:39 -07006972 // Encrypt
6973 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006974 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006975 string ciphertext;
6976 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006977 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6978 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006979 EXPECT_TRUE(finish_out_params.empty());
6980
6981 // Grab nonce
6982 params.push_back(begin_out_params);
6983
6984 // Decrypt.
6985 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006986 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006987 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006988 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006989
6990 EXPECT_TRUE(finish_out_params.empty());
6991
6992 EXPECT_EQ("", plaintext);
6993}
6994
6995/*
6996 * EncryptionOperationsTest.AesGcmMultiPartAad
6997 *
6998 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6999 * chunks.
7000 */
7001TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
7002 const size_t tag_bits = 128;
7003 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7004 .Authorization(TAG_NO_AUTH_REQUIRED)
7005 .AesEncryptionKey(128)
7006 .BlockMode(BlockMode::GCM)
7007 .Padding(PaddingMode::NONE)
7008 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7009
7010 string message = "123456789012345678901234567890123456";
7011 auto begin_params = AuthorizationSetBuilder()
7012 .BlockMode(BlockMode::GCM)
7013 .Padding(PaddingMode::NONE)
7014 .Authorization(TAG_MAC_LENGTH, tag_bits);
7015 AuthorizationSet begin_out_params;
7016
David Drysdale7fc26b92022-05-13 09:54:24 +01007017 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007018
7019 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07007020 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
7021 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007022 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007023 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7024 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007025
Selene Huang31ab4042020-04-29 04:22:39 -07007026 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07007027 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07007028
7029 // Grab nonce.
7030 begin_params.push_back(begin_out_params);
7031
7032 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01007033 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007034 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007035 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007036 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007037 EXPECT_EQ(message, plaintext);
7038}
7039
7040/*
7041 * EncryptionOperationsTest.AesGcmAadOutOfOrder
7042 *
7043 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
7044 */
7045TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
7046 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7047 .Authorization(TAG_NO_AUTH_REQUIRED)
7048 .AesEncryptionKey(128)
7049 .BlockMode(BlockMode::GCM)
7050 .Padding(PaddingMode::NONE)
7051 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7052
7053 string message = "123456789012345678901234567890123456";
7054 auto begin_params = AuthorizationSetBuilder()
7055 .BlockMode(BlockMode::GCM)
7056 .Padding(PaddingMode::NONE)
7057 .Authorization(TAG_MAC_LENGTH, 128);
7058 AuthorizationSet begin_out_params;
7059
David Drysdale7fc26b92022-05-13 09:54:24 +01007060 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007061
Shawn Willden92d79c02021-02-19 07:31:55 -07007062 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007063 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007064 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7065 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007066
David Drysdaled2cc8c22021-04-15 13:29:45 +01007067 // The failure should have already cancelled the operation.
7068 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
7069
Shawn Willden92d79c02021-02-19 07:31:55 -07007070 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07007071}
7072
7073/*
7074 * EncryptionOperationsTest.AesGcmBadAad
7075 *
7076 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
7077 */
7078TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
7079 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7080 .Authorization(TAG_NO_AUTH_REQUIRED)
7081 .AesEncryptionKey(128)
7082 .BlockMode(BlockMode::GCM)
7083 .Padding(PaddingMode::NONE)
7084 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7085
7086 string message = "12345678901234567890123456789012";
7087 auto begin_params = AuthorizationSetBuilder()
7088 .BlockMode(BlockMode::GCM)
7089 .Padding(PaddingMode::NONE)
7090 .Authorization(TAG_MAC_LENGTH, 128);
7091
Selene Huang31ab4042020-04-29 04:22:39 -07007092 // Encrypt
7093 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007094 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007095 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007096 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007097 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007098
7099 // Grab nonce
7100 begin_params.push_back(begin_out_params);
7101
Selene Huang31ab4042020-04-29 04:22:39 -07007102 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007103 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007104 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007105 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007106 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007107}
7108
7109/*
7110 * EncryptionOperationsTest.AesGcmWrongNonce
7111 *
7112 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
7113 */
7114TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
7115 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7116 .Authorization(TAG_NO_AUTH_REQUIRED)
7117 .AesEncryptionKey(128)
7118 .BlockMode(BlockMode::GCM)
7119 .Padding(PaddingMode::NONE)
7120 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7121
7122 string message = "12345678901234567890123456789012";
7123 auto begin_params = AuthorizationSetBuilder()
7124 .BlockMode(BlockMode::GCM)
7125 .Padding(PaddingMode::NONE)
7126 .Authorization(TAG_MAC_LENGTH, 128);
7127
Selene Huang31ab4042020-04-29 04:22:39 -07007128 // Encrypt
7129 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007130 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007131 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007132 string ciphertext;
7133 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07007134 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007135
7136 // Wrong nonce
7137 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
7138
7139 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007140 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007141 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007142 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007143 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007144
7145 // With wrong nonce, should have gotten garbage plaintext (or none).
7146 EXPECT_NE(message, plaintext);
7147}
7148
7149/*
7150 * EncryptionOperationsTest.AesGcmCorruptTag
7151 *
7152 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
7153 */
7154TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
7155 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7156 .Authorization(TAG_NO_AUTH_REQUIRED)
7157 .AesEncryptionKey(128)
7158 .BlockMode(BlockMode::GCM)
7159 .Padding(PaddingMode::NONE)
7160 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7161
7162 string aad = "1234567890123456";
7163 string message = "123456789012345678901234567890123456";
7164
7165 auto params = AuthorizationSetBuilder()
7166 .BlockMode(BlockMode::GCM)
7167 .Padding(PaddingMode::NONE)
7168 .Authorization(TAG_MAC_LENGTH, 128);
7169
Selene Huang31ab4042020-04-29 04:22:39 -07007170 // Encrypt
7171 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007172 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007173 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007174 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007175 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007176
7177 // Corrupt tag
7178 ++(*ciphertext.rbegin());
7179
7180 // Grab nonce
7181 params.push_back(begin_out_params);
7182
7183 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007184 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007185 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007186 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007187 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007188}
7189
7190/*
7191 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7192 *
7193 * Verifies that 3DES is basically functional.
7194 */
7195TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7196 auto auths = AuthorizationSetBuilder()
7197 .TripleDesEncryptionKey(168)
7198 .BlockMode(BlockMode::ECB)
7199 .Authorization(TAG_NO_AUTH_REQUIRED)
7200 .Padding(PaddingMode::NONE);
7201
7202 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7203 // Two-block message.
7204 string message = "1234567890123456";
7205 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7206 string ciphertext1 = EncryptMessage(message, inParams);
7207 EXPECT_EQ(message.size(), ciphertext1.size());
7208
7209 string ciphertext2 = EncryptMessage(string(message), inParams);
7210 EXPECT_EQ(message.size(), ciphertext2.size());
7211
7212 // ECB is deterministic.
7213 EXPECT_EQ(ciphertext1, ciphertext2);
7214
7215 string plaintext = DecryptMessage(ciphertext1, inParams);
7216 EXPECT_EQ(message, plaintext);
7217}
7218
7219/*
7220 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7221 *
7222 * Verifies that CBC keys reject ECB usage.
7223 */
7224TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7225 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7226 .TripleDesEncryptionKey(168)
7227 .BlockMode(BlockMode::CBC)
7228 .Authorization(TAG_NO_AUTH_REQUIRED)
7229 .Padding(PaddingMode::NONE)));
7230
7231 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7232 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7233}
7234
7235/*
7236 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7237 *
7238 * Tests ECB mode with PKCS#7 padding, various message sizes.
7239 */
7240TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7241 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7242 .TripleDesEncryptionKey(168)
7243 .BlockMode(BlockMode::ECB)
7244 .Authorization(TAG_NO_AUTH_REQUIRED)
7245 .Padding(PaddingMode::PKCS7)));
7246
7247 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007248 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007249 string message(i, 'a');
7250 auto inParams =
7251 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7252 string ciphertext = EncryptMessage(message, inParams);
7253 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7254 string plaintext = DecryptMessage(ciphertext, inParams);
7255 EXPECT_EQ(message, plaintext);
7256 }
7257}
7258
7259/*
7260 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7261 *
7262 * Verifies that keys configured for no padding reject PKCS7 padding
7263 */
7264TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7265 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7266 .TripleDesEncryptionKey(168)
7267 .BlockMode(BlockMode::ECB)
7268 .Authorization(TAG_NO_AUTH_REQUIRED)
7269 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007270 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7271 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007272}
7273
7274/*
7275 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7276 *
7277 * Verifies that corrupted padding is detected.
7278 */
7279TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7280 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7281 .TripleDesEncryptionKey(168)
7282 .BlockMode(BlockMode::ECB)
7283 .Authorization(TAG_NO_AUTH_REQUIRED)
7284 .Padding(PaddingMode::PKCS7)));
7285
7286 string message = "a";
7287 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7288 EXPECT_EQ(8U, ciphertext.size());
7289 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007290
7291 AuthorizationSetBuilder begin_params;
7292 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7293 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007294
7295 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7296 ++ciphertext[ciphertext.size() / 2];
7297
David Drysdale7fc26b92022-05-13 09:54:24 +01007298 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007299 string plaintext;
7300 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7301 ErrorCode error = Finish(&plaintext);
7302 if (error == ErrorCode::INVALID_ARGUMENT) {
7303 // This is the expected error, we can exit the test now.
7304 return;
7305 } else {
7306 // Very small chance we got valid decryption, so try again.
7307 ASSERT_EQ(error, ErrorCode::OK);
7308 }
7309 }
7310 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007311}
7312
7313struct TripleDesTestVector {
7314 const char* name;
7315 const KeyPurpose purpose;
7316 const BlockMode block_mode;
7317 const PaddingMode padding_mode;
7318 const char* key;
7319 const char* iv;
7320 const char* input;
7321 const char* output;
7322};
7323
7324// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7325// of the NIST vectors are multiples of the block size.
7326static const TripleDesTestVector kTripleDesTestVectors[] = {
7327 {
7328 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7329 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7330 "", // IV
7331 "329d86bdf1bc5af4", // input
7332 "d946c2756d78633f", // output
7333 },
7334 {
7335 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7336 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7337 "", // IV
7338 "6b1540781b01ce1997adae102dbf3c5b", // input
7339 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7340 },
7341 {
7342 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7343 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7344 "", // IV
7345 "6daad94ce08acfe7", // input
7346 "660e7d32dcc90e79", // output
7347 },
7348 {
7349 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7350 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7351 "", // IV
7352 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7353 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7354 },
7355 {
7356 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7357 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7358 "43f791134c5647ba", // IV
7359 "dcc153cef81d6f24", // input
7360 "92538bd8af18d3ba", // output
7361 },
7362 {
7363 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7364 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7365 "c2e999cb6249023c", // IV
7366 "c689aee38a301bb316da75db36f110b5", // input
7367 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7368 },
7369 {
7370 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7371 PaddingMode::PKCS7,
7372 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7373 "c2e999cb6249023c", // IV
7374 "c689aee38a301bb316da75db36f110b500", // input
7375 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7376 },
7377 {
7378 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7379 PaddingMode::PKCS7,
7380 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7381 "c2e999cb6249023c", // IV
7382 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7383 "c689aee38a301bb316da75db36f110b500", // output
7384 },
7385 {
7386 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7387 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7388 "41746c7e442d3681", // IV
7389 "c53a7b0ec40600fe", // input
7390 "d4f00eb455de1034", // output
7391 },
7392 {
7393 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7394 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7395 "3982bc02c3727d45", // IV
7396 "6006f10adef52991fcc777a1238bbb65", // input
7397 "edae09288e9e3bc05746d872b48e3b29", // output
7398 },
7399};
7400
7401/*
7402 * EncryptionOperationsTest.TripleDesTestVector
7403 *
7404 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7405 */
7406TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7407 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7408 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7409 SCOPED_TRACE(test->name);
7410 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7411 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7412 hex2str(test->output));
7413 }
7414}
7415
7416/*
7417 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7418 *
7419 * Validates CBC mode functionality.
7420 */
7421TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7422 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7423 .TripleDesEncryptionKey(168)
7424 .BlockMode(BlockMode::CBC)
7425 .Authorization(TAG_NO_AUTH_REQUIRED)
7426 .Padding(PaddingMode::NONE)));
7427
7428 ASSERT_GT(key_blob_.size(), 0U);
7429
Brian J Murray734c8412022-01-13 14:55:30 -08007430 // Four-block message.
7431 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007432 vector<uint8_t> iv1;
7433 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7434 EXPECT_EQ(message.size(), ciphertext1.size());
7435
7436 vector<uint8_t> iv2;
7437 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7438 EXPECT_EQ(message.size(), ciphertext2.size());
7439
7440 // IVs should be random, so ciphertexts should differ.
7441 EXPECT_NE(iv1, iv2);
7442 EXPECT_NE(ciphertext1, ciphertext2);
7443
7444 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7445 EXPECT_EQ(message, plaintext);
7446}
7447
7448/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007449 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7450 *
7451 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7452 */
7453TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7454 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7455 .TripleDesEncryptionKey(168)
7456 .BlockMode(BlockMode::CBC)
7457 .Authorization(TAG_NO_AUTH_REQUIRED)
7458 .Authorization(TAG_CALLER_NONCE)
7459 .Padding(PaddingMode::NONE)));
7460 auto params = AuthorizationSetBuilder()
7461 .BlockMode(BlockMode::CBC)
7462 .Padding(PaddingMode::NONE)
7463 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7464 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7465}
7466
7467/*
Selene Huang31ab4042020-04-29 04:22:39 -07007468 * EncryptionOperationsTest.TripleDesCallerIv
7469 *
7470 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7471 */
7472TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7473 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7474 .TripleDesEncryptionKey(168)
7475 .BlockMode(BlockMode::CBC)
7476 .Authorization(TAG_NO_AUTH_REQUIRED)
7477 .Authorization(TAG_CALLER_NONCE)
7478 .Padding(PaddingMode::NONE)));
7479 string message = "1234567890123456";
7480 vector<uint8_t> iv;
7481 // Don't specify IV, should get a random one.
7482 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7483 EXPECT_EQ(message.size(), ciphertext1.size());
7484 EXPECT_EQ(8U, iv.size());
7485
7486 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7487 EXPECT_EQ(message, plaintext);
7488
7489 // Now specify an IV, should also work.
7490 iv = AidlBuf("abcdefgh");
7491 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7492
7493 // Decrypt with correct IV.
7494 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7495 EXPECT_EQ(message, plaintext);
7496
7497 // Now try with wrong IV.
7498 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7499 EXPECT_NE(message, plaintext);
7500}
7501
7502/*
7503 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7504 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007505 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007506 */
7507TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7508 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7509 .TripleDesEncryptionKey(168)
7510 .BlockMode(BlockMode::CBC)
7511 .Authorization(TAG_NO_AUTH_REQUIRED)
7512 .Padding(PaddingMode::NONE)));
7513
7514 string message = "12345678901234567890123456789012";
7515 vector<uint8_t> iv;
7516 // Don't specify nonce, should get a random one.
7517 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7518 EXPECT_EQ(message.size(), ciphertext1.size());
7519 EXPECT_EQ(8U, iv.size());
7520
7521 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7522 EXPECT_EQ(message, plaintext);
7523
7524 // Now specify a nonce, should fail.
7525 auto input_params = AuthorizationSetBuilder()
7526 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7527 .BlockMode(BlockMode::CBC)
7528 .Padding(PaddingMode::NONE);
7529 AuthorizationSet output_params;
7530 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7531 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7532}
7533
7534/*
7535 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7536 *
7537 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7538 */
7539TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7540 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7541 .TripleDesEncryptionKey(168)
7542 .BlockMode(BlockMode::ECB)
7543 .Authorization(TAG_NO_AUTH_REQUIRED)
7544 .Padding(PaddingMode::NONE)));
7545 // Two-block message.
7546 string message = "1234567890123456";
7547 auto begin_params =
7548 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7549 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7550}
7551
7552/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007553 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007554 *
7555 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7556 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007557TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7558 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007559 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007560 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7561 .TripleDesEncryptionKey(168)
7562 .BlockMode(blockMode)
7563 .Authorization(TAG_NO_AUTH_REQUIRED)
7564 .Padding(PaddingMode::NONE)));
7565 // Message is slightly shorter than two blocks.
7566 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007567
David Drysdaled2cc8c22021-04-15 13:29:45 +01007568 auto begin_params =
7569 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7570 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007571 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007572 string ciphertext;
7573 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7574
7575 CheckedDeleteKey();
7576 }
Selene Huang31ab4042020-04-29 04:22:39 -07007577}
7578
7579/*
7580 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7581 *
7582 * Verifies that PKCS7 padding works correctly in CBC mode.
7583 */
7584TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7585 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7586 .TripleDesEncryptionKey(168)
7587 .BlockMode(BlockMode::CBC)
7588 .Authorization(TAG_NO_AUTH_REQUIRED)
7589 .Padding(PaddingMode::PKCS7)));
7590
7591 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007592 for (size_t i = 0; i <= 32; i++) {
7593 SCOPED_TRACE(testing::Message() << "i = " << i);
7594 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7595 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007596 vector<uint8_t> iv;
7597 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7598 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7599 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7600 EXPECT_EQ(message, plaintext);
7601 }
7602}
7603
7604/*
7605 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7606 *
7607 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7608 */
7609TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7610 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7611 .TripleDesEncryptionKey(168)
7612 .BlockMode(BlockMode::CBC)
7613 .Authorization(TAG_NO_AUTH_REQUIRED)
7614 .Padding(PaddingMode::NONE)));
7615
7616 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007617 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007618 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007619 auto begin_params =
7620 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7621 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7622 }
7623}
7624
7625/*
7626 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7627 *
7628 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7629 */
7630TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7631 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7632 .TripleDesEncryptionKey(168)
7633 .BlockMode(BlockMode::CBC)
7634 .Authorization(TAG_NO_AUTH_REQUIRED)
7635 .Padding(PaddingMode::PKCS7)));
7636
7637 string message = "a";
7638 vector<uint8_t> iv;
7639 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7640 EXPECT_EQ(8U, ciphertext.size());
7641 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007642
7643 auto begin_params = AuthorizationSetBuilder()
7644 .BlockMode(BlockMode::CBC)
7645 .Padding(PaddingMode::PKCS7)
7646 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007647
7648 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007649 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007650 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007651 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007652 string plaintext;
7653 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7654 ErrorCode error = Finish(&plaintext);
7655 if (error == ErrorCode::INVALID_ARGUMENT) {
7656 // This is the expected error, we can exit the test now.
7657 return;
7658 } else {
7659 // Very small chance we got valid decryption, so try again.
7660 ASSERT_EQ(error, ErrorCode::OK);
7661 }
7662 }
7663 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007664}
7665
7666/*
7667 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7668 *
7669 * Verifies that 3DES CBC works with many different input sizes.
7670 */
7671TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7672 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7673 .TripleDesEncryptionKey(168)
7674 .BlockMode(BlockMode::CBC)
7675 .Authorization(TAG_NO_AUTH_REQUIRED)
7676 .Padding(PaddingMode::NONE)));
7677
7678 int increment = 7;
7679 string message(240, 'a');
7680 AuthorizationSet input_params =
7681 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7682 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007683 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007684
7685 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007686 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007687 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007688 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7689 EXPECT_EQ(message.size(), ciphertext.size());
7690
7691 // Move TAG_NONCE into input_params
7692 input_params = output_params;
7693 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7694 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7695 output_params.Clear();
7696
David Drysdale7fc26b92022-05-13 09:54:24 +01007697 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007698 string plaintext;
7699 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007700 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007701 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7702 EXPECT_EQ(ciphertext.size(), plaintext.size());
7703 EXPECT_EQ(message, plaintext);
7704}
7705
7706INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7707
7708typedef KeyMintAidlTestBase MaxOperationsTest;
7709
7710/*
7711 * MaxOperationsTest.TestLimitAes
7712 *
7713 * Verifies that the max uses per boot tag works correctly with AES keys.
7714 */
7715TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007716 if (SecLevel() == SecurityLevel::STRONGBOX) {
7717 GTEST_SKIP() << "Test not applicable to StrongBox device";
7718 }
Selene Huang31ab4042020-04-29 04:22:39 -07007719
7720 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7721 .Authorization(TAG_NO_AUTH_REQUIRED)
7722 .AesEncryptionKey(128)
7723 .EcbMode()
7724 .Padding(PaddingMode::NONE)
7725 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7726
7727 string message = "1234567890123456";
7728
7729 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7730
7731 EncryptMessage(message, params);
7732 EncryptMessage(message, params);
7733 EncryptMessage(message, params);
7734
7735 // Fourth time should fail.
7736 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7737}
7738
7739/*
Qi Wud22ec842020-11-26 13:27:53 +08007740 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007741 *
7742 * Verifies that the max uses per boot tag works correctly with RSA keys.
7743 */
7744TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007745 if (SecLevel() == SecurityLevel::STRONGBOX) {
7746 GTEST_SKIP() << "Test not applicable to StrongBox device";
7747 }
Selene Huang31ab4042020-04-29 04:22:39 -07007748
7749 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7750 .Authorization(TAG_NO_AUTH_REQUIRED)
7751 .RsaSigningKey(1024, 65537)
7752 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007753 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7754 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007755
7756 string message = "1234567890123456";
7757
7758 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7759
7760 SignMessage(message, params);
7761 SignMessage(message, params);
7762 SignMessage(message, params);
7763
7764 // Fourth time should fail.
7765 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7766}
7767
7768INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7769
Qi Wud22ec842020-11-26 13:27:53 +08007770typedef KeyMintAidlTestBase UsageCountLimitTest;
7771
7772/*
Qi Wubeefae42021-01-28 23:16:37 +08007773 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007774 *
Qi Wubeefae42021-01-28 23:16:37 +08007775 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007776 */
Qi Wubeefae42021-01-28 23:16:37 +08007777TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007778 if (SecLevel() == SecurityLevel::STRONGBOX) {
7779 GTEST_SKIP() << "Test not applicable to StrongBox device";
7780 }
Qi Wud22ec842020-11-26 13:27:53 +08007781
7782 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7783 .Authorization(TAG_NO_AUTH_REQUIRED)
7784 .AesEncryptionKey(128)
7785 .EcbMode()
7786 .Padding(PaddingMode::NONE)
7787 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7788
7789 // Check the usage count limit tag appears in the authorizations.
7790 AuthorizationSet auths;
7791 for (auto& entry : key_characteristics_) {
7792 auths.push_back(AuthorizationSet(entry.authorizations));
7793 }
7794 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7795 << "key usage count limit " << 1U << " missing";
7796
7797 string message = "1234567890123456";
7798 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7799
Qi Wubeefae42021-01-28 23:16:37 +08007800 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7801 AuthorizationSet keystore_auths =
7802 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7803
Qi Wud22ec842020-11-26 13:27:53 +08007804 // First usage of AES key should work.
7805 EncryptMessage(message, params);
7806
Qi Wud22ec842020-11-26 13:27:53 +08007807 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7808 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7809 // must be invalidated from secure storage (such as RPMB partition).
7810 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7811 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007812 // Usage count limit tag is enforced by keystore, keymint does nothing.
7813 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007814 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007815 }
7816}
7817
7818/*
Qi Wubeefae42021-01-28 23:16:37 +08007819 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007820 *
Qi Wubeefae42021-01-28 23:16:37 +08007821 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007822 */
Qi Wubeefae42021-01-28 23:16:37 +08007823TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007824 if (SecLevel() == SecurityLevel::STRONGBOX) {
7825 GTEST_SKIP() << "Test not applicable to StrongBox device";
7826 }
Qi Wubeefae42021-01-28 23:16:37 +08007827
7828 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7829 .Authorization(TAG_NO_AUTH_REQUIRED)
7830 .AesEncryptionKey(128)
7831 .EcbMode()
7832 .Padding(PaddingMode::NONE)
7833 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7834
7835 // Check the usage count limit tag appears in the authorizations.
7836 AuthorizationSet auths;
7837 for (auto& entry : key_characteristics_) {
7838 auths.push_back(AuthorizationSet(entry.authorizations));
7839 }
7840 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7841 << "key usage count limit " << 3U << " missing";
7842
7843 string message = "1234567890123456";
7844 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7845
7846 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7847 AuthorizationSet keystore_auths =
7848 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7849
7850 EncryptMessage(message, params);
7851 EncryptMessage(message, params);
7852 EncryptMessage(message, params);
7853
7854 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7855 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7856 // must be invalidated from secure storage (such as RPMB partition).
7857 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7858 } else {
7859 // Usage count limit tag is enforced by keystore, keymint does nothing.
7860 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007861 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007862 }
7863}
7864
7865/*
7866 * UsageCountLimitTest.TestSingleUseRsa
7867 *
7868 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7869 */
7870TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007871 if (SecLevel() == SecurityLevel::STRONGBOX) {
7872 GTEST_SKIP() << "Test not applicable to StrongBox device";
7873 }
Qi Wud22ec842020-11-26 13:27:53 +08007874
7875 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7876 .Authorization(TAG_NO_AUTH_REQUIRED)
7877 .RsaSigningKey(1024, 65537)
7878 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007879 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7880 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007881
7882 // Check the usage count limit tag appears in the authorizations.
7883 AuthorizationSet auths;
7884 for (auto& entry : key_characteristics_) {
7885 auths.push_back(AuthorizationSet(entry.authorizations));
7886 }
7887 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7888 << "key usage count limit " << 1U << " missing";
7889
7890 string message = "1234567890123456";
7891 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7892
Qi Wubeefae42021-01-28 23:16:37 +08007893 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7894 AuthorizationSet keystore_auths =
7895 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7896
Qi Wud22ec842020-11-26 13:27:53 +08007897 // First usage of RSA key should work.
7898 SignMessage(message, params);
7899
Qi Wud22ec842020-11-26 13:27:53 +08007900 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7901 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7902 // must be invalidated from secure storage (such as RPMB partition).
7903 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7904 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007905 // Usage count limit tag is enforced by keystore, keymint does nothing.
7906 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007907 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007908 }
7909}
7910
7911/*
7912 * UsageCountLimitTest.TestLimitUseRsa
7913 *
7914 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7915 */
7916TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007917 if (SecLevel() == SecurityLevel::STRONGBOX) {
7918 GTEST_SKIP() << "Test not applicable to StrongBox device";
7919 }
Qi Wubeefae42021-01-28 23:16:37 +08007920
7921 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7922 .Authorization(TAG_NO_AUTH_REQUIRED)
7923 .RsaSigningKey(1024, 65537)
7924 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007925 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7926 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007927
7928 // Check the usage count limit tag appears in the authorizations.
7929 AuthorizationSet auths;
7930 for (auto& entry : key_characteristics_) {
7931 auths.push_back(AuthorizationSet(entry.authorizations));
7932 }
7933 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7934 << "key usage count limit " << 3U << " missing";
7935
7936 string message = "1234567890123456";
7937 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7938
7939 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7940 AuthorizationSet keystore_auths =
7941 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7942
7943 SignMessage(message, params);
7944 SignMessage(message, params);
7945 SignMessage(message, params);
7946
7947 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7948 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7949 // must be invalidated from secure storage (such as RPMB partition).
7950 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7951 } else {
7952 // Usage count limit tag is enforced by keystore, keymint does nothing.
7953 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007954 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007955 }
7956}
7957
Qi Wu8e727f72021-02-11 02:49:33 +08007958/*
7959 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7960 *
7961 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7962 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7963 * in hardware.
7964 */
7965TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
Qi Wu8e727f72021-02-11 02:49:33 +08007966 auto error = GenerateKey(AuthorizationSetBuilder()
7967 .RsaSigningKey(2048, 65537)
7968 .Digest(Digest::NONE)
7969 .Padding(PaddingMode::NONE)
7970 .Authorization(TAG_NO_AUTH_REQUIRED)
7971 .Authorization(TAG_ROLLBACK_RESISTANCE)
7972 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007973 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7974 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007975 }
David Drysdale513bf122021-10-06 11:53:13 +01007976
7977 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7978 ASSERT_EQ(ErrorCode::OK, error);
7979 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7980 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7981 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7982
7983 // The KeyMint should also enforce single use key in hardware when it supports rollback
7984 // resistance.
7985 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7986 .Authorization(TAG_NO_AUTH_REQUIRED)
7987 .RsaSigningKey(1024, 65537)
7988 .NoDigestOrPadding()
7989 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7990 .SetDefaultValidity()));
7991
7992 // Check the usage count limit tag appears in the hardware authorizations.
7993 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7994 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7995 << "key usage count limit " << 1U << " missing";
7996
7997 string message = "1234567890123456";
7998 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7999
8000 // First usage of RSA key should work.
8001 SignMessage(message, params);
8002
8003 // Usage count limit tag is enforced by hardware. After using the key, the key blob
8004 // must be invalidated from secure storage (such as RPMB partition).
8005 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08008006}
8007
Qi Wud22ec842020-11-26 13:27:53 +08008008INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
8009
David Drysdale7de9feb2021-03-05 14:56:19 +00008010typedef KeyMintAidlTestBase GetHardwareInfoTest;
8011
8012TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
8013 // Retrieving hardware info should give the same result each time.
8014 KeyMintHardwareInfo info;
8015 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
8016 KeyMintHardwareInfo info2;
8017 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
8018 EXPECT_EQ(info, info2);
8019}
8020
8021INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
8022
Selene Huang31ab4042020-04-29 04:22:39 -07008023typedef KeyMintAidlTestBase AddEntropyTest;
8024
8025/*
8026 * AddEntropyTest.AddEntropy
8027 *
8028 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
8029 * is actually added.
8030 */
8031TEST_P(AddEntropyTest, AddEntropy) {
8032 string data = "foo";
8033 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
8034}
8035
8036/*
8037 * AddEntropyTest.AddEmptyEntropy
8038 *
8039 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
8040 */
8041TEST_P(AddEntropyTest, AddEmptyEntropy) {
8042 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
8043}
8044
8045/*
8046 * AddEntropyTest.AddLargeEntropy
8047 *
8048 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
8049 */
8050TEST_P(AddEntropyTest, AddLargeEntropy) {
8051 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
8052}
8053
David Drysdalebb3d85e2021-04-13 11:15:51 +01008054/*
8055 * AddEntropyTest.AddTooLargeEntropy
8056 *
8057 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
8058 */
8059TEST_P(AddEntropyTest, AddTooLargeEntropy) {
8060 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
8061 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
8062}
8063
Selene Huang31ab4042020-04-29 04:22:39 -07008064INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
8065
Selene Huang31ab4042020-04-29 04:22:39 -07008066typedef KeyMintAidlTestBase KeyDeletionTest;
8067
8068/**
8069 * KeyDeletionTest.DeleteKey
8070 *
8071 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
8072 * valid key blob.
8073 */
8074TEST_P(KeyDeletionTest, DeleteKey) {
8075 auto error = GenerateKey(AuthorizationSetBuilder()
8076 .RsaSigningKey(2048, 65537)
8077 .Digest(Digest::NONE)
8078 .Padding(PaddingMode::NONE)
8079 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008080 .Authorization(TAG_ROLLBACK_RESISTANCE)
8081 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008082 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8083 GTEST_SKIP() << "Rollback resistance not supported";
8084 }
Selene Huang31ab4042020-04-29 04:22:39 -07008085
8086 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008087 ASSERT_EQ(ErrorCode::OK, error);
8088 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8089 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008090
David Drysdale513bf122021-10-06 11:53:13 +01008091 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07008092
David Drysdale513bf122021-10-06 11:53:13 +01008093 string message = "12345678901234567890123456789012";
8094 AuthorizationSet begin_out_params;
8095 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8096 Begin(KeyPurpose::SIGN, key_blob_,
8097 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8098 &begin_out_params));
8099 AbortIfNeeded();
8100 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008101}
8102
8103/**
8104 * KeyDeletionTest.DeleteInvalidKey
8105 *
8106 * This test checks that the HAL excepts invalid key blobs..
8107 */
8108TEST_P(KeyDeletionTest, DeleteInvalidKey) {
8109 // Generate key just to check if rollback protection is implemented
8110 auto error = GenerateKey(AuthorizationSetBuilder()
8111 .RsaSigningKey(2048, 65537)
8112 .Digest(Digest::NONE)
8113 .Padding(PaddingMode::NONE)
8114 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008115 .Authorization(TAG_ROLLBACK_RESISTANCE)
8116 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008117 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8118 GTEST_SKIP() << "Rollback resistance not supported";
8119 }
Selene Huang31ab4042020-04-29 04:22:39 -07008120
8121 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008122 ASSERT_EQ(ErrorCode::OK, error);
8123 AuthorizationSet enforced(SecLevelAuthorizations());
8124 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008125
David Drysdale513bf122021-10-06 11:53:13 +01008126 // Delete the key we don't care about the result at this point.
8127 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07008128
David Drysdale513bf122021-10-06 11:53:13 +01008129 // Now create an invalid key blob and delete it.
8130 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07008131
David Drysdale513bf122021-10-06 11:53:13 +01008132 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07008133}
8134
8135/**
8136 * KeyDeletionTest.DeleteAllKeys
8137 *
8138 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
8139 *
8140 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
8141 * FBE/FDE encryption keys, which means that the device will not even boot until after the
8142 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
8143 * been provisioned. Use this test only on dedicated testing devices that have no valuable
8144 * credentials stored in Keystore/Keymint.
8145 */
8146TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01008147 if (!arm_deleteAllKeys) {
8148 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
8149 return;
8150 }
Selene Huang31ab4042020-04-29 04:22:39 -07008151 auto error = GenerateKey(AuthorizationSetBuilder()
8152 .RsaSigningKey(2048, 65537)
8153 .Digest(Digest::NONE)
8154 .Padding(PaddingMode::NONE)
8155 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06008156 .Authorization(TAG_ROLLBACK_RESISTANCE)
8157 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008158 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8159 GTEST_SKIP() << "Rollback resistance not supported";
8160 }
Selene Huang31ab4042020-04-29 04:22:39 -07008161
8162 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008163 ASSERT_EQ(ErrorCode::OK, error);
8164 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8165 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008166
David Drysdale513bf122021-10-06 11:53:13 +01008167 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07008168
David Drysdale513bf122021-10-06 11:53:13 +01008169 string message = "12345678901234567890123456789012";
8170 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07008171
David Drysdale513bf122021-10-06 11:53:13 +01008172 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8173 Begin(KeyPurpose::SIGN, key_blob_,
8174 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8175 &begin_out_params));
8176 AbortIfNeeded();
8177 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008178}
8179
8180INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8181
David Drysdaled2cc8c22021-04-15 13:29:45 +01008182typedef KeyMintAidlTestBase KeyUpgradeTest;
8183
8184/**
8185 * KeyUpgradeTest.UpgradeInvalidKey
8186 *
8187 * This test checks that the HAL excepts invalid key blobs..
8188 */
8189TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8190 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8191
8192 std::vector<uint8_t> new_blob;
8193 Status result = keymint_->upgradeKey(key_blob,
8194 AuthorizationSetBuilder()
8195 .Authorization(TAG_APPLICATION_ID, "clientid")
8196 .Authorization(TAG_APPLICATION_DATA, "appdata")
8197 .vector_data(),
8198 &new_blob);
8199 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8200}
8201
8202INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8203
Selene Huang31ab4042020-04-29 04:22:39 -07008204using UpgradeKeyTest = KeyMintAidlTestBase;
8205
8206/*
8207 * UpgradeKeyTest.UpgradeKey
8208 *
8209 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8210 */
8211TEST_P(UpgradeKeyTest, UpgradeKey) {
8212 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8213 .AesEncryptionKey(128)
8214 .Padding(PaddingMode::NONE)
8215 .Authorization(TAG_NO_AUTH_REQUIRED)));
8216
8217 auto result = UpgradeKey(key_blob_);
8218
8219 // Key doesn't need upgrading. Should get okay, but no new key blob.
8220 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8221}
8222
8223INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8224
8225using ClearOperationsTest = KeyMintAidlTestBase;
8226
8227/*
8228 * ClearSlotsTest.TooManyOperations
8229 *
8230 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8231 * operations are started without being finished or aborted. Also verifies
8232 * that aborting the operations clears the operations.
8233 *
8234 */
8235TEST_P(ClearOperationsTest, TooManyOperations) {
8236 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8237 .Authorization(TAG_NO_AUTH_REQUIRED)
8238 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008239 .Padding(PaddingMode::NONE)
8240 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008241
8242 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8243 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008244 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008245 AuthorizationSet out_params;
8246 ErrorCode result;
8247 size_t i;
8248
8249 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008250 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008251 if (ErrorCode::OK != result) {
8252 break;
8253 }
8254 }
8255 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8256 // Try again just in case there's a weird overflow bug
8257 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008258 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008259 for (size_t j = 0; j < i; j++) {
8260 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8261 << "Aboort failed for i = " << j << std::endl;
8262 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008263 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008264 AbortIfNeeded();
8265}
8266
8267INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8268
8269typedef KeyMintAidlTestBase TransportLimitTest;
8270
8271/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008272 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008273 *
8274 * Verifies that passing input data to finish succeeds as expected.
8275 */
8276TEST_P(TransportLimitTest, LargeFinishInput) {
8277 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8278 .Authorization(TAG_NO_AUTH_REQUIRED)
8279 .AesEncryptionKey(128)
8280 .BlockMode(BlockMode::ECB)
8281 .Padding(PaddingMode::NONE)));
8282
8283 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008284 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008285 auto cipher_params =
8286 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8287
8288 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008289 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008290
8291 string plain_message = std::string(1 << msg_size, 'x');
8292 string encrypted_message;
8293 auto rc = Finish(plain_message, &encrypted_message);
8294
8295 EXPECT_EQ(ErrorCode::OK, rc);
8296 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8297 << "Encrypt finish returned OK, but did not consume all of the given input";
8298 cipher_params.push_back(out_params);
8299
David Drysdale7fc26b92022-05-13 09:54:24 +01008300 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008301
8302 string decrypted_message;
8303 rc = Finish(encrypted_message, &decrypted_message);
8304 EXPECT_EQ(ErrorCode::OK, rc);
8305 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8306 << "Decrypt finish returned OK, did not consume all of the given input";
8307 }
8308}
8309
8310INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8311
Seth Moored79a0ec2021-12-13 20:03:33 +00008312static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008313 switch (curve) {
8314 case EcCurve::P_224:
8315 return NID_secp224r1;
8316 case EcCurve::P_256:
8317 return NID_X9_62_prime256v1;
8318 case EcCurve::P_384:
8319 return NID_secp384r1;
8320 case EcCurve::P_521:
8321 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008322 case EcCurve::CURVE_25519:
8323 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008324 }
8325}
8326
David Drysdale42fe1892021-10-14 14:43:46 +01008327class KeyAgreementTest : public KeyMintAidlTestBase {
8328 protected:
8329 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8330 std::vector<uint8_t>* localPublicKey) {
8331 // Generate EC key locally (with access to private key material)
8332 if (localCurve == EcCurve::CURVE_25519) {
8333 uint8_t privKeyData[32];
8334 uint8_t pubKeyData[32];
8335 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008336 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8337 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8338 } else {
8339 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8340 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8341 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8342 ASSERT_NE(group, nullptr);
8343 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8344 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8345 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8346 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008347 }
David Drysdalea410b772022-05-09 16:44:13 +01008348
8349 // Get encoded form of the public part of the locally generated key...
8350 unsigned char* p = nullptr;
8351 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8352 ASSERT_GT(localPublicKeySize, 0);
8353 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8354 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8355 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008356 }
8357
8358 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8359 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008360 auto builder = AuthorizationSetBuilder()
8361 .Authorization(TAG_NO_AUTH_REQUIRED)
8362 .Authorization(TAG_EC_CURVE, curve)
8363 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8364 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8365 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8366 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8367 .SetDefaultValidity();
8368 ErrorCode result = GenerateKey(builder);
8369
8370 if (SecLevel() == SecurityLevel::STRONGBOX) {
8371 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8372 result = GenerateKeyWithSelfSignedAttestKey(
8373 AuthorizationSetBuilder()
8374 .EcdsaKey(EcCurve::P_256)
8375 .AttestKey()
8376 .SetDefaultValidity(), /* attest key params */
8377 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8378 }
8379 }
David Drysdale42fe1892021-10-14 14:43:46 +01008380 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8381 ASSERT_GT(cert_chain_.size(), 0);
8382 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8383 ASSERT_NE(kmKeyCert, nullptr);
8384 // Check that keyAgreement (bit 4) is set in KeyUsage
8385 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8386 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8387 ASSERT_NE(*kmPubKey, nullptr);
8388 if (dump_Attestations) {
8389 for (size_t n = 0; n < cert_chain_.size(); n++) {
8390 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8391 }
8392 }
8393 }
8394
8395 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8396 const std::vector<uint8_t>& localPublicKey) {
8397 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8398 string ZabFromKeyMintStr;
8399 ASSERT_EQ(ErrorCode::OK,
8400 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8401 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8402 vector<uint8_t> ZabFromTest;
8403
8404 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8405 size_t kmPubKeySize = 32;
8406 uint8_t kmPubKeyData[32];
8407 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8408 ASSERT_EQ(kmPubKeySize, 32);
8409
8410 uint8_t localPrivKeyData[32];
8411 size_t localPrivKeySize = 32;
8412 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8413 &localPrivKeySize));
8414 ASSERT_EQ(localPrivKeySize, 32);
8415
8416 uint8_t sharedKey[32];
8417 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8418 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8419 } else {
8420 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8421 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8422 ASSERT_NE(ctx, nullptr);
8423 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8424 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8425 size_t ZabFromTestLen = 0;
8426 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8427 ZabFromTest.resize(ZabFromTestLen);
8428 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8429 }
8430 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8431 }
8432};
8433
David Zeuthene0c40892021-01-08 12:54:11 -05008434/*
8435 * KeyAgreementTest.Ecdh
8436 *
David Drysdale42fe1892021-10-14 14:43:46 +01008437 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008438 */
8439TEST_P(KeyAgreementTest, Ecdh) {
8440 // Because it's possible to use this API with keys on different curves, we
8441 // check all N^2 combinations where N is the number of supported
8442 // curves.
8443 //
8444 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8445 // lot more curves we can be smart about things and just pick |otherCurve| so
8446 // it's not |curve| and that way we end up with only 2*N runs
8447 //
8448 for (auto curve : ValidCurves()) {
8449 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008450 SCOPED_TRACE(testing::Message()
8451 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8452
David Zeuthene0c40892021-01-08 12:54:11 -05008453 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008454 EVP_PKEY_Ptr localPrivKey;
8455 vector<uint8_t> localPublicKey;
8456 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008457
8458 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008459 EVP_PKEY_Ptr kmPubKey;
8460 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008461
8462 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8463 if (curve != localCurve) {
8464 // If the keys are using different curves KeyMint should fail with
8465 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008466 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008467 string ZabFromKeyMintStr;
8468 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008469 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008470 &ZabFromKeyMintStr));
8471
8472 } else {
8473 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008474 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008475 }
8476
8477 CheckedDeleteKey();
8478 }
8479 }
8480}
8481
David Drysdale42fe1892021-10-14 14:43:46 +01008482/*
8483 * KeyAgreementTest.EcdhCurve25519
8484 *
8485 * Verifies that ECDH works for curve25519. This is also covered by the general
8486 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8487 * KeyMint 1.0.
8488 */
8489TEST_P(KeyAgreementTest, EcdhCurve25519) {
8490 if (!Curve25519Supported()) {
8491 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8492 }
8493
8494 // Generate EC key in KeyMint (only access to public key material)
8495 EcCurve curve = EcCurve::CURVE_25519;
8496 EVP_PKEY_Ptr kmPubKey = nullptr;
8497 GenerateKeyMintEcKey(curve, &kmPubKey);
8498
8499 // Generate EC key on same curve locally (with access to private key material).
8500 EVP_PKEY_Ptr privKey;
8501 vector<uint8_t> encodedPublicKey;
8502 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8503
8504 // Agree on a key between local and KeyMint and check it.
8505 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8506
8507 CheckedDeleteKey();
8508}
8509
8510/*
8511 * KeyAgreementTest.EcdhCurve25519Imported
8512 *
8513 * Verifies that ECDH works for an imported curve25519 key.
8514 */
8515TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8516 if (!Curve25519Supported()) {
8517 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8518 }
8519
8520 // Import x25519 key into KeyMint.
8521 EcCurve curve = EcCurve::CURVE_25519;
8522 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8523 .Authorization(TAG_NO_AUTH_REQUIRED)
8524 .EcdsaKey(EcCurve::CURVE_25519)
8525 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8526 .SetDefaultValidity(),
8527 KeyFormat::PKCS8, x25519_pkcs8_key));
8528 ASSERT_GT(cert_chain_.size(), 0);
8529 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8530 ASSERT_NE(kmKeyCert, nullptr);
8531 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8532 ASSERT_NE(kmPubKey.get(), nullptr);
8533
8534 // Expect the import to emit corresponding public key data.
8535 size_t kmPubKeySize = 32;
8536 uint8_t kmPubKeyData[32];
8537 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8538 ASSERT_EQ(kmPubKeySize, 32);
8539 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8540 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8541
8542 // Generate EC key on same curve locally (with access to private key material).
8543 EVP_PKEY_Ptr privKey;
8544 vector<uint8_t> encodedPublicKey;
8545 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8546
8547 // Agree on a key between local and KeyMint and check it.
8548 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8549
8550 CheckedDeleteKey();
8551}
8552
8553/*
8554 * KeyAgreementTest.EcdhCurve25519InvalidSize
8555 *
8556 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8557 */
8558TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8559 if (!Curve25519Supported()) {
8560 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8561 }
8562
8563 // Generate EC key in KeyMint (only access to public key material)
8564 EcCurve curve = EcCurve::CURVE_25519;
8565 EVP_PKEY_Ptr kmPubKey = nullptr;
8566 GenerateKeyMintEcKey(curve, &kmPubKey);
8567
8568 // Generate EC key on same curve locally (with access to private key material).
8569 EVP_PKEY_Ptr privKey;
8570 vector<uint8_t> encodedPublicKey;
8571 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8572
8573 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8574 string ZabFromKeyMintStr;
8575 // Send in an incomplete public key.
8576 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8577 &ZabFromKeyMintStr));
8578
8579 CheckedDeleteKey();
8580}
8581
8582/*
8583 * KeyAgreementTest.EcdhCurve25519Mismatch
8584 *
8585 * Verifies that ECDH fails between curve25519 and other curves.
8586 */
8587TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8588 if (!Curve25519Supported()) {
8589 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8590 }
8591
8592 // Generate EC key in KeyMint (only access to public key material)
8593 EcCurve curve = EcCurve::CURVE_25519;
8594 EVP_PKEY_Ptr kmPubKey = nullptr;
8595 GenerateKeyMintEcKey(curve, &kmPubKey);
8596
8597 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008598 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008599 if (localCurve == curve) {
8600 continue;
8601 }
8602 // Generate EC key on a different curve locally (with access to private key material).
8603 EVP_PKEY_Ptr privKey;
8604 vector<uint8_t> encodedPublicKey;
8605 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8606
David Drysdale7fc26b92022-05-13 09:54:24 +01008607 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008608 string ZabFromKeyMintStr;
8609 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8610 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8611 &ZabFromKeyMintStr));
8612 }
8613
8614 CheckedDeleteKey();
8615}
8616
David Zeuthene0c40892021-01-08 12:54:11 -05008617INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8618
David Drysdaled2cc8c22021-04-15 13:29:45 +01008619using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8620
8621// This is a problematic test, as it can render the device under test permanently unusable.
8622// Re-enable and run at your own risk.
8623TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8624 auto result = DestroyAttestationIds();
8625 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8626}
8627
8628INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8629
Shawn Willdend659c7c2021-02-19 14:51:51 -07008630using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008631
David Drysdaledb0dcf52021-05-18 11:43:31 +01008632/*
8633 * EarlyBootKeyTest.CreateEarlyBootKeys
8634 *
8635 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8636 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008637TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008638 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008639 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8640 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008641 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8642 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8643 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8644 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008645
David Drysdaleadfe6112021-05-27 12:00:53 +01008646 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8647 ASSERT_GT(keyData.blob.size(), 0U);
8648 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8649 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8650 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008651}
8652
David Drysdaledb0dcf52021-05-18 11:43:31 +01008653/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008654 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8655 *
8656 * Verifies that creating an early boot key with attestation succeeds.
8657 */
8658TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8659 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8660 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8661 builder->AttestationChallenge("challenge");
8662 builder->AttestationApplicationId("app_id");
8663 });
David Drysdale1b9febc2023-06-07 13:43:24 +01008664 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8665 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8666 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8667 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
David Drysdaleadfe6112021-05-27 12:00:53 +01008668
8669 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008670 // Strongbox may not support factory attestation. Key creation might fail with
8671 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8672 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8673 continue;
8674 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008675 ASSERT_GT(keyData.blob.size(), 0U);
8676 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8677 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8678 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008679}
8680
8681/*
8682 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008683 *
8684 * Verifies that using early boot keys at a later stage fails.
8685 */
8686TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8687 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8688 .Authorization(TAG_NO_AUTH_REQUIRED)
8689 .Authorization(TAG_EARLY_BOOT_ONLY)
8690 .HmacKey(128)
8691 .Digest(Digest::SHA_2_256)
8692 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8693 AuthorizationSet output_params;
8694 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8695 AuthorizationSetBuilder()
8696 .Digest(Digest::SHA_2_256)
8697 .Authorization(TAG_MAC_LENGTH, 256),
8698 &output_params));
8699}
8700
8701/*
8702 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8703 *
8704 * Verifies that importing early boot keys fails.
8705 */
8706TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8707 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8708 .Authorization(TAG_NO_AUTH_REQUIRED)
8709 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008710 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008711 .Digest(Digest::SHA_2_256)
8712 .SetDefaultValidity(),
8713 KeyFormat::PKCS8, ec_256_key));
8714}
8715
David Drysdaled2cc8c22021-04-15 13:29:45 +01008716// 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 +00008717// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8718// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8719// early boot, so you'll have to reboot between runs.
8720TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8721 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8722 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008723 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8724 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8725 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8726 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
8727
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008728 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8729 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8730 EXPECT_TRUE(
8731 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8732 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8733 EXPECT_TRUE(
8734 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8735
8736 // Should be able to use keys, since early boot has not ended
8737 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8738 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8739 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8740 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8741
8742 // End early boot
8743 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8744 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8745
8746 // Should not be able to use already-created keys.
8747 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8748 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8749 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8750 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8751
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008752 // Should not be able to create new keys
David Drysdale1b9febc2023-06-07 13:43:24 +01008753 auto [aesKeyData2, hmacKeyData2, rsaKeyData2, ecdsaKeyData2] =
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008754 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
David Drysdale1b9febc2023-06-07 13:43:24 +01008755 KeyBlobDeleter aes_deleter2(keymint_, aesKeyData2.blob);
8756 KeyBlobDeleter hmac_deleter2(keymint_, hmacKeyData2.blob);
8757 KeyBlobDeleter rsa_deleter2(keymint_, rsaKeyData2.blob);
8758 KeyBlobDeleter ecdsa_deleter2(keymint_, ecdsaKeyData2.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008759}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008760
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008761INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8762
Shawn Willden22fb9c12022-06-02 14:04:33 -06008763using VsrRequirementTest = KeyMintAidlTestBase;
8764
Eran Messeri5fe06ea2023-08-02 22:34:24 +01008765// @VsrTest = VSR-3.10-008
Shawn Willden22fb9c12022-06-02 14:04:33 -06008766TEST_P(VsrRequirementTest, Vsr13Test) {
8767 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008768 if (vsr_api_level < __ANDROID_API_T__) {
Shawn Willden22fb9c12022-06-02 14:04:33 -06008769 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8770 }
8771 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8772}
8773
Eran Messeri5fe06ea2023-08-02 22:34:24 +01008774// @VsrTest = VSR-3.10-013.001
Eran Messerib9346f52022-12-15 14:58:34 +00008775TEST_P(VsrRequirementTest, Vsr14Test) {
8776 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008777 if (vsr_api_level < __ANDROID_API_U__) {
Eran Messerib9346f52022-12-15 14:58:34 +00008778 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8779 }
8780 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8781}
8782
Shawn Willden22fb9c12022-06-02 14:04:33 -06008783INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8784
David Drysdale6c9bdb82024-01-23 09:32:04 +00008785class InstanceTest : public testing::Test {
8786 protected:
8787 static void SetUpTestSuite() {
8788 auto params = ::android::getAidlHalInstanceNames(IKeyMintDevice::descriptor);
8789 for (auto& param : params) {
8790 ASSERT_TRUE(AServiceManager_isDeclared(param.c_str()))
8791 << "IKeyMintDevice instance " << param << " found but not declared.";
8792 ::ndk::SpAIBinder binder(AServiceManager_waitForService(param.c_str()));
8793 auto keymint = IKeyMintDevice::fromBinder(binder);
8794 ASSERT_NE(keymint, nullptr) << "Failed to get IKeyMintDevice instance " << param;
8795
8796 KeyMintHardwareInfo info;
8797 ASSERT_TRUE(keymint->getHardwareInfo(&info).isOk());
8798 ASSERT_EQ(keymints_.count(info.securityLevel), 0)
8799 << "There must be exactly one IKeyMintDevice with security level "
8800 << info.securityLevel;
8801
8802 keymints_[info.securityLevel] = std::move(keymint);
8803 }
8804 }
8805
8806 int32_t AidlVersion(shared_ptr<IKeyMintDevice> keymint) {
8807 int32_t version = 0;
8808 auto status = keymint->getInterfaceVersion(&version);
8809 if (!status.isOk()) {
8810 ADD_FAILURE() << "Failed to determine interface version";
8811 }
8812 return version;
8813 }
8814
8815 static std::map<SecurityLevel, shared_ptr<IKeyMintDevice>> keymints_;
8816};
8817
8818std::map<SecurityLevel, shared_ptr<IKeyMintDevice>> InstanceTest::keymints_;
8819
8820// @VsrTest = VSR-3.10-017
8821// Check that the AIDL version advertised by the HAL service matches
8822// the value in the package manager feature version.
8823TEST_F(InstanceTest, AidlVersionInFeature) {
8824 if (is_gsi_image()) {
8825 GTEST_SKIP() << "Versions not required to match under GSI";
8826 }
8827 if (keymints_.count(SecurityLevel::TRUSTED_ENVIRONMENT) == 1) {
8828 auto tee = keymints_.find(SecurityLevel::TRUSTED_ENVIRONMENT)->second;
8829 int32_t tee_aidl_version = AidlVersion(tee) * 100;
8830 std::optional<int32_t> tee_feature_version = keymint_feature_value(/* strongbox */ false);
8831 ASSERT_TRUE(tee_feature_version.has_value());
8832 EXPECT_EQ(tee_aidl_version, tee_feature_version.value());
8833 }
8834 if (keymints_.count(SecurityLevel::STRONGBOX) == 1) {
8835 auto sb = keymints_.find(SecurityLevel::STRONGBOX)->second;
8836 int32_t sb_aidl_version = AidlVersion(sb) * 100;
8837 std::optional<int32_t> sb_feature_version = keymint_feature_value(/* strongbox */ true);
8838 ASSERT_TRUE(sb_feature_version.has_value());
8839 EXPECT_EQ(sb_aidl_version, sb_feature_version.value());
8840 }
8841}
8842
8843// @VsrTest = VSR-3.10-017
8844// Check that if package manager advertises support for KeyMint of a particular version, that
8845// version is present as a HAL service.
8846TEST_F(InstanceTest, FeatureVersionInAidl) {
8847 if (is_gsi_image()) {
8848 GTEST_SKIP() << "Versions not required to match under GSI";
8849 }
8850 std::optional<int32_t> tee_feature_version = keymint_feature_value(/* strongbox */ false);
8851 if (tee_feature_version.has_value() && tee_feature_version.value() >= 100) {
8852 // Feature flag advertises the existence of KeyMint; check it is present.
8853 ASSERT_EQ(keymints_.count(SecurityLevel::TRUSTED_ENVIRONMENT), 1);
8854 auto tee = keymints_.find(SecurityLevel::TRUSTED_ENVIRONMENT)->second;
8855 int32_t tee_aidl_version = AidlVersion(tee) * 100;
8856 EXPECT_EQ(tee_aidl_version, tee_feature_version.value());
8857 }
8858
8859 std::optional<int32_t> sb_feature_version = keymint_feature_value(/* strongbox */ true);
8860 if (sb_feature_version.has_value() && sb_feature_version.value() >= 100) {
8861 // Feature flag advertises the existence of KeyMint; check it is present.
8862 ASSERT_EQ(keymints_.count(SecurityLevel::STRONGBOX), 1);
8863 auto sb = keymints_.find(SecurityLevel::STRONGBOX)->second;
8864 int32_t sb_aidl_version = AidlVersion(sb) * 100;
8865 EXPECT_EQ(sb_aidl_version, sb_feature_version.value());
8866 }
8867}
8868
Janis Danisevskis24c04702020-12-16 18:28:39 -08008869} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008870
David Drysdale77a86d82024-01-03 11:22:56 +00008871using aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase;
8872
Selene Huang31ab4042020-04-29 04:22:39 -07008873int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008874 std::cout << "Testing ";
David Drysdale77a86d82024-01-03 11:22:56 +00008875 auto halInstances = KeyMintAidlTestBase::build_params();
Shawn Willden7c130392020-12-21 09:58:22 -07008876 std::cout << "HAL instances:\n";
8877 for (auto& entry : halInstances) {
8878 std::cout << " " << entry << '\n';
8879 }
8880
Selene Huang31ab4042020-04-29 04:22:39 -07008881 ::testing::InitGoogleTest(&argc, argv);
8882 for (int i = 1; i < argc; ++i) {
8883 if (argv[i][0] == '-') {
8884 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
David Drysdale77a86d82024-01-03 11:22:56 +00008885 KeyMintAidlTestBase::arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008886 }
8887 if (std::string(argv[i]) == "--dump_attestations") {
David Drysdale77a86d82024-01-03 11:22:56 +00008888 KeyMintAidlTestBase::dump_Attestations = true;
Shawn Willden7c130392020-12-21 09:58:22 -07008889 } else {
8890 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008891 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008892 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8893 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8894 // be run in emulated environments that don't have the normal bootloader
8895 // interactions.
8896 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8897 }
David Drysdale9f5c0c52022-11-03 15:10:16 +00008898 if (std::string(argv[i]) == "--keyblob_dir") {
8899 if (i + 1 >= argc) {
8900 std::cerr << "Missing argument for --keyblob_dir\n";
8901 return 1;
8902 }
David Drysdale77a86d82024-01-03 11:22:56 +00008903 KeyMintAidlTestBase::keyblob_dir = std::string(argv[i + 1]);
David Drysdale9f5c0c52022-11-03 15:10:16 +00008904 ++i;
8905 }
Tommy Chiu025f3c52023-05-15 06:23:44 +00008906 if (std::string(argv[i]) == "--expect_upgrade") {
8907 if (i + 1 >= argc) {
8908 std::cerr << "Missing argument for --expect_upgrade\n";
8909 return 1;
8910 }
8911 std::string arg = argv[i + 1];
David Drysdale77a86d82024-01-03 11:22:56 +00008912 KeyMintAidlTestBase::expect_upgrade =
8913 arg == "yes" ? true
8914 : (arg == "no" ? false : std::optional<bool>(std::nullopt));
8915 if (KeyMintAidlTestBase::expect_upgrade.has_value()) {
8916 std::cout << "expect_upgrade = "
8917 << (KeyMintAidlTestBase::expect_upgrade.value() ? "true" : "false")
8918 << std::endl;
8919 } else {
8920 std::cerr << "Error! Option --expect_upgrade " << arg << " unrecognized"
8921 << std::endl;
8922 }
Tommy Chiu025f3c52023-05-15 06:23:44 +00008923 ++i;
8924 }
Selene Huang31ab4042020-04-29 04:22:39 -07008925 }
8926 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008927 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008928}