blob: b65218fba97dcbc3e29876ca69983ed2767a7ff8 [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
Seth Moorec5c52ce2024-04-07 15:26:33 -070040#include <keymint_support/authorization_set.h>
Shawn Willden08a7e432020-12-11 13:05:27 +000041#include <keymint_support/key_param_output.h>
42#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070043
44#include "KeyMintAidlTestBase.h"
45
Janis Danisevskis24c04702020-12-16 18:28:39 -080046using aidl::android::hardware::security::keymint::AuthorizationSet;
47using aidl::android::hardware::security::keymint::KeyCharacteristics;
48using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070049
Selene Huang31ab4042020-04-29 04:22:39 -070050namespace std {
51
Janis Danisevskis24c04702020-12-16 18:28:39 -080052using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070053
54template <>
55struct std::equal_to<KeyCharacteristics> {
56 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070057 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070058
Shawn Willden7f424372021-01-10 18:06:50 -070059 // this isn't very efficient. Oh, well.
60 AuthorizationSet a_auths(a.authorizations);
61 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070062
Shawn Willden7f424372021-01-10 18:06:50 -070063 a_auths.Sort();
64 b_auths.Sort();
65
66 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070067 }
68};
69
70} // namespace std
71
Janis Danisevskis24c04702020-12-16 18:28:39 -080072namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000073
Selene Huang31ab4042020-04-29 04:22:39 -070074namespace {
75
David Drysdalefeab5d92022-01-06 15:46:23 +000076// Maximum supported Ed25519 message size.
77const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
78
David Drysdaledbbbe2e2021-12-02 07:44:23 +000079// Whether to check that BOOT_PATCHLEVEL is populated.
80bool check_boot_pl = true;
81
Seth Moore7a55ae32021-06-23 14:28:11 -070082// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000083// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070084// is a small (roughly 1/256) chance that corrupting ciphertext still results
85// in valid PKCS7 padding.
86constexpr size_t kMaxPaddingCorruptionRetries = 8;
87
Selene Huang31ab4042020-04-29 04:22:39 -070088template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000089bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
90 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070091 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080092 if (auto p = authorizationValue(ttag, param)) {
93 return *p == expected_value;
94 }
95 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070096 });
97 return (it != set.end());
98}
99
100template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +0000101bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -0700102 auto it = std::find_if(set.begin(), set.end(),
103 [&](const KeyParameter& param) { return param.tag == tag; });
104 return (it != set.end());
105}
106
107constexpr char hex_value[256] = {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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
111 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
113 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
123
124string hex2str(string a) {
125 string b;
126 size_t num = a.size() / 2;
127 b.resize(num);
128 for (size_t i = 0; i < num; i++) {
129 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
130 }
131 return b;
132}
133
David Drysdaled2cc8c22021-04-15 13:29:45 +0100134string rsa_key = hex2str(
135 // RFC 5208 s5
136 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
137 "020100" // INTEGER length 1 value 0x00 (version)
138 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
139 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
140 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
141 "0500" // NULL (parameters)
142 // } end SEQUENCE (AlgorithmIdentifier)
143 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
144 // RFC 8017 A.1.2
145 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
146 "020100" // INTEGER length 1 value 0x00 (version)
147 "028181" // INTEGER length 0x81 value (modulus) ...
148 "00c6095409047d8634812d5a218176e4"
149 "5c41d60a75b13901f234226cffe77652"
150 "1c5a77b9e389417b71c0b6a44d13afe4"
151 "e4a2805d46c9da2935adb1ff0c1f24ea"
152 "06e62b20d776430a4d435157233c6f91"
153 "6783c30e310fcbd89b85c2d567711697"
154 "85ac12bca244abda72bfb19fc44d27c8"
155 "1e1d92de284f4061edfd99280745ea6d"
156 "25"
157 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
158 "028180" // INTEGER length 0x80 (privateExponent) value...
159 "1be0f04d9cae3718691f035338308e91"
160 "564b55899ffb5084d2460e6630257e05"
161 "b3ceab02972dfabcd6ce5f6ee2589eb6"
162 "7911ed0fac16e43a444b8c861e544a05"
163 "93365772f8baf6b22fc9e3c5f1024b06"
164 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
165 "ace7240290bef16c0b3f7f3cdd64ce3a"
166 "b5912cf6e32f39ab188358afcccd8081"
167 "0241" // INTEGER length 0x41 (prime1)
168 "00e4b49ef50f765d3b24dde01aceaaf1"
169 "30f2c76670a91a61ae08af497b4a82be"
170 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
171 "8c92bfab137fba2285227b83c342ff7c"
172 "55"
173 "0241" // INTEGER length 0x41 (prime2)
174 "00ddabb5839c4c7f6bf3d4183231f005"
175 "b31aa58affdda5c79e4cce217f6bc930"
176 "dbe563d480706c24e9ebfcab28a6cdef"
177 "d324b77e1bf7251b709092c24ff501fd"
178 "91"
179 "0240" // INTEGER length 0x40 (exponent1)
180 "23d4340eda3445d8cd26c14411da6fdc"
181 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
182 "842c1d280405bc2f6c1bea214a1d742a"
183 "b996b35b63a82a5e470fa88dbf823cdd"
184 "0240" // INTEGER length 0x40 (exponent2)
185 "1b7b57449ad30d1518249a5f56bb9829"
186 "4d4b6ac12ffc86940497a5a5837a6cf9"
187 "46262b494526d328c11e1126380fde04"
188 "c24f916dec250892db09a6d77cdba351"
189 "0240" // INTEGER length 0x40 (coefficient)
190 "7762cd8f4d050da56bd591adb515d24d"
191 "7ccd32cca0d05f866d583514bd7324d5"
192 "f33645e8ed8b4a1cb3cc4a1d67987399"
193 "f2a09f5b3fb68c88d5e5d90ac33492d6"
194 // } end SEQUENCE (PrivateKey)
195 // } end SEQUENCE (PrivateKeyInfo)
196);
Selene Huang31ab4042020-04-29 04:22:39 -0700197
Selene Huange5727e62021-04-13 22:41:20 -0700198/*
199 * DER-encoded PKCS#8 format RSA key. Generated using:
200 *
201 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
202 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100203string rsa_2048_key = hex2str(
204 // RFC 5208 s5
205 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
206 "020100" // INTEGER length 1 value 0x00 (version)
207 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
208 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
209 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
210 "0500" // NULL (parameters)
211 // } end SEQUENCE (AlgorithmIdentifier)
212 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
213 // RFC 8017 A.1.2
214 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
215 "020100" // INTEGER length 1 value 0x00 (version)
216 "02820101" // INTEGER length 0x101 value (modulus) ...
217 "00BEBC342B56D443B1299F9A6A7056E8"
218 "0A897E318476A5A18029E63B2ED739A6"
219 "1791D339F58DC763D9D14911F2EDEC38"
220 "3DEE11F6319B44510E7A3ECD9B79B973"
221 "82E49500ACF8117DC89CAF0E621F7775"
222 "6554A2FD4664BFE7AB8B59AB48340DBF"
223 "A27B93B5A81F6ECDEB02D0759307128D"
224 "F3E3BAD4055C8B840216DFAA5700670E"
225 "6C5126F0962FCB70FF308F25049164CC"
226 "F76CC2DA66A7DD9A81A714C2809D6918"
227 "6133D29D84568E892B6FFBF3199BDB14"
228 "383EE224407F190358F111A949552ABA"
229 "6714227D1BD7F6B20DD0CB88F9467B71"
230 "9339F33BFF35B3870B3F62204E4286B0"
231 "948EA348B524544B5F9838F29EE643B0"
232 "79EEF8A713B220D7806924CDF7295070"
233 "C5"
234 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
235 "02820100" // INTEGER length 0x100 (privateExponent) value...
236 "69F377F35F2F584EF075353CCD1CA997"
237 "38DB3DBC7C7FF35F9366CE176DFD1B13"
238 "5AB10030344ABF5FBECF1D4659FDEF1C"
239 "0FC430834BE1BE3911951377BB3D563A"
240 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
241 "2686C7B4B3C09A7B8354133E6F93F790"
242 "D59EAEB92E84C9A4339302CCE28FDF04"
243 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
244 "6AB706645BF074A4E4090D06FB163124"
245 "365FD5EE7A20D350E9958CC30D91326E"
246 "1B292E9EF5DB408EC42DAF737D201497"
247 "04D0A678A0FB5B5446863B099228A352"
248 "D604BA8091A164D01D5AB05397C71EAD"
249 "20BE2A08FC528FE442817809C787FEE4"
250 "AB97F97B9130D022153EDC6EB6CBE7B0"
251 "F8E3473F2E901209B5DB10F93604DB01"
252 "028181" // INTEGER length 0x81 (prime1)
253 "00E83C0998214941EA4F9293F1B77E2E"
254 "99E6CF305FAF358238E126124FEAF2EB"
255 "9724B2EA7B78E6032343821A80E55D1D"
256 "88FB12D220C3F41A56142FEC85796D19"
257 "17F1E8C774F142B67D3D6E7B7E6B4383"
258 "E94DB5929089DBB346D5BDAB40CC2D96"
259 "EE0409475E175C63BF78CFD744136740"
260 "838127EA723FF3FE7FA368C1311B4A4E"
261 "05"
262 "028181" // INTEGER length 0x81 (prime2)
263 "00D240FCC0F5D7715CDE21CB2DC86EA1"
264 "46132EA3B06F61FF2AF54BF38473F59D"
265 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
266 "B1B58C39F95E4798CCBB43E83D0119AC"
267 "F532F359CA743C85199F0286610E2009"
268 "97D7312917179AC9B67558773212EC96"
269 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
270 "94D94E066A0900B7B70E82A44FB30053"
271 "C1"
272 "028181" // INTEGER length 0x81 (exponent1)
273 "00AD15DA1CBD6A492B66851BA8C316D3"
274 "8AB700E2CFDDD926A658003513C54BAA"
275 "152B30021D667D20078F500F8AD3E7F3"
276 "945D74A891ED1A28EAD0FEEAEC8C14A8"
277 "E834CF46A13D1378C99D18940823CFDD"
278 "27EC5810D59339E0C34198AC638E09C8"
279 "7CBB1B634A9864AE9F4D5EB2D53514F6"
280 "7B4CAEC048C8AB849A02E397618F3271"
281 "35"
282 "028180" // INTEGER length 0x80 (exponent2)
283 "1FA2C1A5331880A92D8F3E281C617108"
284 "BF38244F16E352E69ED417C7153F9EC3"
285 "18F211839C643DCF8B4DD67CE2AC312E"
286 "95178D5D952F06B1BF779F4916924B70"
287 "F582A23F11304E02A5E7565AE22A35E7"
288 "4FECC8B6FDC93F92A1A37703E4CF0E63"
289 "783BD02EB716A7ECBBFA606B10B74D01"
290 "579522E7EF84D91FC522292108D902C1"
291 "028180" // INTEGER length 0x80 (coefficient)
292 "796FE3825F9DCC85DF22D58690065D93"
293 "898ACD65C087BEA8DA3A63BF4549B795"
294 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
295 "0D74F40DED8E1102C52152A31B6165F8"
296 "3A6722AECFCC35A493D7634664B888A0"
297 "8D3EB034F12EA28BFEE346E205D33482"
298 "7F778B16ED40872BD29FCB36536B6E93"
299 "FFB06778696B4A9D81BB0A9423E63DE5"
300 // } end SEQUENCE (PrivateKey)
301 // } end SEQUENCE (PrivateKeyInfo)
302);
Selene Huange5727e62021-04-13 22:41:20 -0700303
David Drysdaled2cc8c22021-04-15 13:29:45 +0100304string ec_256_key = hex2str(
305 // RFC 5208 s5
306 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
307 "020100" // INTEGER length 1 value 0 (version)
308 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
309 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
310 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
311 "0608" // OBJECT IDENTIFIER length 8 (param)
312 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
313 // } end SEQUENCE (AlgorithmIdentifier)
314 "046d" // OCTET STRING length 0x6d (privateKey) holding...
315 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
316 "020101" // INTEGER length 1 value 1 (version)
317 "0420" // OCTET STRING length 0x20 (privateKey)
318 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
319 "941eed09366bc03299986481f3a4d859"
320 "a144" // TAG [1] len 0x44 (publicKey) {
321 "03420004bf85d7720d07c25461683bc6"
322 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
323 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
324 "bcc41c6eb00083cf3376d11fd44949e0"
325 "b2183bfe"
326 // } end SEQUENCE (ECPrivateKey)
327 // } end SEQUENCE (PrivateKeyInfo)
328);
Selene Huang31ab4042020-04-29 04:22:39 -0700329
David Drysdaled2cc8c22021-04-15 13:29:45 +0100330string ec_521_key = hex2str(
331 // RFC 5208 s5
332 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
333 "020100" // INTEGER length 1 value 0 (version)
334 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
335 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
336 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
337 "0605" // OBJECT IDENTIFIER length 5 (param)
338 "2B81040023" // 1.3.132.0.35 (secp521r1)
339 // } end SEQUENCE (AlgorithmIdentifier)
340 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
341 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
342 "020101" // INTEGER length 1 value 1 (version)
343 "0442" // OCTET STRING length 0x42 (privateKey)
344 "0011458C586DB5DAA92AFAB03F4FE46A"
345 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
346 "9D18D7D08B5BCFA0E53C75B064AD51C4"
347 "49BAE0258D54B94B1E885DED08ED4FB2"
348 "5CE9"
349 "A18189" // TAG [1] len 0x89 (publicKey) {
350 "03818600040149EC11C6DF0FA122C6A9"
351 "AFD9754A4FA9513A627CA329E349535A"
352 "5629875A8ADFBE27DCB932C051986377"
353 "108D054C28C6F39B6F2C9AF81802F9F3"
354 "26B842FF2E5F3C00AB7635CFB36157FC"
355 "0882D574A10D839C1A0C049DC5E0D775"
356 "E2EE50671A208431BB45E78E70BEFE93"
357 "0DB34818EE4D5C26259F5C6B8E28A652"
358 "950F9F88D7B4B2C9D9"
359 // } end SEQUENCE (ECPrivateKey)
360 // } end SEQUENCE (PrivateKeyInfo)
361);
Selene Huang31ab4042020-04-29 04:22:39 -0700362
David Drysdaled2cc8c22021-04-15 13:29:45 +0100363string ec_256_key_rfc5915 = hex2str(
364 // RFC 5208 s5
365 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
366 "020100" // INTEGER length 1 value 0 (version)
367 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
368 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
369 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
370 "0608" // OBJECT IDENTIFIER length 8 (param)
371 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
372 // } end SEQUENCE (AlgorithmIdentifier)
373 "0479" // OCTET STRING length 0x79 (privateKey) holding...
374 // RFC 5915 s3
375 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
376 "020101" // INTEGER length 1 value 1 (version)
377 "0420" // OCTET STRING length 0x42 (privateKey)
378 "782370a8c8ce5537baadd04dcff079c8"
379 "158cfa9c67b818b38e8d21c9fa750c1d"
380 "a00a" // TAG [0] length 0xa (parameters)
381 "0608" // OBJECT IDENTIFIER length 8
382 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
383 // } end TAG [0]
384 "a144" // TAG [1] length 0x44 (publicKey) {
385 "0342" // BIT STRING length 0x42
386 "00" // no pad bits
387 "04e2cc561ee701da0ad0ef0d176bb0c9"
388 "19d42e79c393fdc1bd6c4010d85cf2cf"
389 "8e68c905464666f98dad4f01573ba810"
390 "78b3428570a439ba3229fbc026c55068"
391 "2f"
392 // } end SEQUENCE (ECPrivateKey)
393 // } end SEQUENCE (PrivateKeyInfo)
394);
Selene Huang31ab4042020-04-29 04:22:39 -0700395
David Drysdaled2cc8c22021-04-15 13:29:45 +0100396string ec_256_key_sec1 = hex2str(
397 // RFC 5208 s5
398 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
399 "020100" // INTEGER length 1 value 0 (version)
400 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
401 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
402 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
403 "0608" // OBJECT IDENTIFIER length 8 (param)
404 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
405 // } end SEQUENCE (AlgorithmIdentifier)
406 "046d" // OCTET STRING length 0x6d (privateKey) holding...
407 // SEC1-v2 C.4
408 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
409 "020101" // INTEGER length 1 value 0x01 (version)
410 "0420" // OCTET STRING length 0x20 (privateKey)
411 "782370a8c8ce5537baadd04dcff079c8"
412 "158cfa9c67b818b38e8d21c9fa750c1d"
413 "a144" // TAG [1] length 0x44 (publicKey) {
414 "0342" // BIT STRING length 0x42
415 "00" // no pad bits
416 "04e2cc561ee701da0ad0ef0d176bb0c9"
417 "19d42e79c393fdc1bd6c4010d85cf2cf"
418 "8e68c905464666f98dad4f01573ba810"
419 "78b3428570a439ba3229fbc026c55068"
420 "2f"
421 // } end TAG [1] (publicKey)
422 // } end SEQUENCE (PrivateKeyInfo)
423);
Selene Huang31ab4042020-04-29 04:22:39 -0700424
David Drysdale42fe1892021-10-14 14:43:46 +0100425/**
426 * Ed25519 key pair generated as follows:
427 * ```
428 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
429 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
430 * Generating a ED25519 private key writing new private key to
431 * 'ed25519_priv.key'
432 * -----
433 * % cat ed25519_priv.key
434 * -----BEGIN PRIVATE KEY-----
435 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
436 * -----END PRIVATE KEY-----
437 * % der2ascii -pem -i ed25519_priv.key
438 * SEQUENCE {
439 * INTEGER { 0 }
440 * SEQUENCE {
441 * # ed25519
442 * OBJECT_IDENTIFIER { 1.3.101.112 }
443 * }
444 * OCTET_STRING {
445 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
446 * }
447 * }
448 * % cat ed25519.pem
449 * -----BEGIN CERTIFICATE-----
450 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
451 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
452 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
453 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
454 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
455 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
456 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
457 * -----END CERTIFICATE-----
458 * % openssl x509 -in ed25519.pem -text -noout
459 * Certificate:
460 * Data:
461 * Version: 3 (0x2)
462 * Serial Number:
463 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
464 * Signature Algorithm: ED25519
465 * Issuer: CN = fake.ed25519.com
466 * Validity
467 * Not Before: Oct 20 08:27:42 2021 GMT
468 * Not After : Sep 20 08:27:42 2023 GMT
469 * Subject: CN = fake.ed25519.com
470 * Subject Public Key Info:
471 * Public Key Algorithm: ED25519
472 * ED25519 Public-Key:
473 * pub:
474 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
475 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
476 * 56:91
477 * X509v3 extensions:
478 * X509v3 Subject Key Identifier:
479 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
480 * X509v3 Authority Key Identifier:
481 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
482 *
483 * X509v3 Basic Constraints: critical
484 * CA:TRUE
485 * Signature Algorithm: ED25519
486 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
487 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
488 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
489 * e7:07:32:60:32:8d:bb:eb:f6:0f
490 * ```
491 */
492string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
493string ed25519_pkcs8_key = hex2str(
494 // RFC 5208 s5
495 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
496 "0201" // INTEGER length 1 (Version)
497 "00" // version 0
498 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
499 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
500 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
501 // } end SEQUENCE (AlgorithmIdentifier)
502 "0422" // OCTET STRING length 0x22 (PrivateKey)
503 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
504 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
505 // } end SEQUENCE (PrivateKeyInfo)
506);
507string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
508
509/**
510 * X25519 key pair generated as follows:
511 * ```
512 * % openssl genpkey -algorithm X25519 > x25519_priv.key
513 * % cat x25519_priv.key
514 * -----BEGIN PRIVATE KEY-----
515 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
516 * -----END PRIVATE KEY-----
517 * % der2ascii -pem -i x25519_priv.key
518 * SEQUENCE {
519 * INTEGER { 0 }
520 * SEQUENCE {
521 * # x25519
522 * OBJECT_IDENTIFIER { 1.3.101.110 }
523 * }
524 * OCTET_STRING {
525 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
526 * }
527 * }
528 * ```
529 */
530
531string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
532string x25519_pkcs8_key = hex2str(
533 // RFC 5208 s5
534 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
535 "0201" // INTEGER length 1 (Version)
536 "00" // version 0
537 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
538 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
539 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
540 "0422" // OCTET STRING length 0x22 (PrivateKey)
541 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
542 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
543string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
544
Selene Huang31ab4042020-04-29 04:22:39 -0700545struct RSA_Delete {
546 void operator()(RSA* p) { RSA_free(p); }
547};
548
Selene Huang31ab4042020-04-29 04:22:39 -0700549std::string make_string(const uint8_t* data, size_t length) {
550 return std::string(reinterpret_cast<const char*>(data), length);
551}
552
553template <size_t N>
554std::string make_string(const uint8_t (&a)[N]) {
555 return make_string(a, N);
556}
557
558class AidlBuf : public vector<uint8_t> {
559 typedef vector<uint8_t> super;
560
561 public:
562 AidlBuf() {}
563 AidlBuf(const super& other) : super(other) {}
564 AidlBuf(super&& other) : super(std::move(other)) {}
565 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
566
567 AidlBuf& operator=(const super& other) {
568 super::operator=(other);
569 return *this;
570 }
571
572 AidlBuf& operator=(super&& other) {
573 super::operator=(std::move(other));
574 return *this;
575 }
576
577 AidlBuf& operator=(const string& other) {
578 resize(other.size());
579 for (size_t i = 0; i < other.size(); ++i) {
580 (*this)[i] = static_cast<uint8_t>(other[i]);
581 }
582 return *this;
583 }
584
585 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
586};
587
David Drysdale4dc01072021-04-01 12:17:35 +0100588string device_suffix(const string& name) {
589 size_t pos = name.find('/');
590 if (pos == string::npos) {
591 return name;
592 }
593 return name.substr(pos + 1);
594}
595
Seth Moore5a0320f2023-03-24 12:29:08 -0700596std::shared_ptr<IRemotelyProvisionedComponent> matching_rp_instance(const std::string& km_name) {
David Drysdale4dc01072021-04-01 12:17:35 +0100597 string km_suffix = device_suffix(km_name);
598
599 vector<string> rp_names =
600 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
601 for (const string& rp_name : rp_names) {
602 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
603 // KeyMint instance, assume they match.
604 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
605 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
Seth Moore5a0320f2023-03-24 12:29:08 -0700606 return IRemotelyProvisionedComponent::fromBinder(binder);
David Drysdale4dc01072021-04-01 12:17:35 +0100607 }
608 }
Seth Moore5a0320f2023-03-24 12:29:08 -0700609 return nullptr;
David Drysdale4dc01072021-04-01 12:17:35 +0100610}
611
Selene Huang31ab4042020-04-29 04:22:39 -0700612} // namespace
613
614class NewKeyGenerationTest : public KeyMintAidlTestBase {
615 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700616 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000617 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
Selene Huang31ab4042020-04-29 04:22:39 -0700618 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700619
Selene Huang31ab4042020-04-29 04:22:39 -0700620 // Check that some unexpected tags/values are NOT present.
621 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
622 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000623 }
624
625 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000626 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
David Drysdale7de9feb2021-03-05 14:56:19 +0000627 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
628 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
629
630 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000631 }
632
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000633 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics,
634 const KeyOrigin expectedKeyOrigin) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000635 // TODO(swillden): Distinguish which params should be in which auth list.
636 AuthorizationSet auths;
637 for (auto& entry : keyCharacteristics) {
638 auths.push_back(AuthorizationSet(entry.authorizations));
639 }
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000640 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, expectedKeyOrigin));
David Drysdale7de9feb2021-03-05 14:56:19 +0000641
642 // Verify that App data, ROT and auth timeout are NOT included.
643 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
644 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700645 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
646
David Drysdaled2cc8c22021-04-15 13:29:45 +0100647 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
648 // never adds it.
649 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
650
David Drysdale7de9feb2021-03-05 14:56:19 +0000651 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700652 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000653 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700654 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700655 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000656 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700657 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000658
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000659 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100660 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
661 EXPECT_TRUE(vendor_pl);
662 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000663
664 // Should include boot patchlevel (but there are some test scenarios where this is not
665 // possible).
666 if (check_boot_pl) {
667 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
668 EXPECT_TRUE(boot_pl);
669 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100670
David Drysdale7de9feb2021-03-05 14:56:19 +0000671 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700672 }
673};
674
675/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000676 * NewKeyGenerationTest.Aes
677 *
678 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
679 * have correct characteristics.
680 */
681TEST_P(NewKeyGenerationTest, Aes) {
682 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
683 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
684 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
685 SCOPED_TRACE(testing::Message()
686 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
687 vector<uint8_t> key_blob;
688 vector<KeyCharacteristics> key_characteristics;
689 auto builder = AuthorizationSetBuilder()
690 .AesEncryptionKey(key_size)
691 .BlockMode(block_mode)
692 .Padding(padding_mode)
693 .SetDefaultValidity();
694 if (block_mode == BlockMode::GCM) {
695 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
696 }
697 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100698 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000699
700 EXPECT_GT(key_blob.size(), 0U);
701 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100702 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000703
704 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
705
706 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
707 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
708 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000709 }
710 }
711 }
712}
713
714/*
715 * NewKeyGenerationTest.AesInvalidSize
716 *
717 * Verifies that specifying an invalid key size for AES key generation returns
718 * UNSUPPORTED_KEY_SIZE.
719 */
720TEST_P(NewKeyGenerationTest, AesInvalidSize) {
721 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
722 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
723 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
724 SCOPED_TRACE(testing::Message()
725 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
726 vector<uint8_t> key_blob;
727 vector<KeyCharacteristics> key_characteristics;
728 auto builder = AuthorizationSetBuilder()
729 .AesEncryptionKey(key_size)
730 .BlockMode(block_mode)
731 .Padding(padding_mode)
732 .SetDefaultValidity();
733 if (block_mode == BlockMode::GCM) {
734 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
735 }
736 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
737 GenerateKey(builder, &key_blob, &key_characteristics));
738 }
739 }
740 }
741
742 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
743 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100744 SCOPED_TRACE(testing::Message() << "AES-unknown-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000745 vector<uint8_t> key_blob;
746 vector<KeyCharacteristics> key_characteristics;
747 // No key size specified
748 auto builder = AuthorizationSetBuilder()
749 .Authorization(TAG_ALGORITHM, Algorithm::AES)
750 .BlockMode(block_mode)
751 .Padding(padding_mode)
752 .SetDefaultValidity();
753 if (block_mode == BlockMode::GCM) {
754 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
755 }
756 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
757 GenerateKey(builder, &key_blob, &key_characteristics));
758 }
759 }
760}
761
762/*
763 * NewKeyGenerationTest.AesInvalidPadding
764 *
765 * Verifies that specifying an invalid padding on AES keys gives a failure
766 * somewhere along the way.
767 */
768TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
769 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
770 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
771 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
772 SCOPED_TRACE(testing::Message()
773 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000774 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800775 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000776 .AesEncryptionKey(key_size)
777 .BlockMode(block_mode)
778 .Padding(padding_mode)
779 .SetDefaultValidity();
780 if (block_mode == BlockMode::GCM) {
781 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
782 }
783
Tommy Chiu3950b452021-05-03 22:01:46 +0800784 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000785 if (result == ErrorCode::OK) {
786 // Key creation was OK but has generated a key that cannot be used.
787 auto params =
788 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800789 if (block_mode == BlockMode::GCM) {
790 params.Authorization(TAG_MAC_LENGTH, 128);
791 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000792 auto result = Begin(KeyPurpose::ENCRYPT, params);
793 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100794 result == ErrorCode::INVALID_KEY_BLOB)
795 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000796 } else {
797 // The KeyMint implementation detected that the generated key
798 // is unusable.
799 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
800 }
801 }
802 }
803 }
804}
805
806/*
807 * NewKeyGenerationTest.AesGcmMissingMinMac
808 *
809 * Verifies that specifying an invalid key size for AES key generation returns
810 * UNSUPPORTED_KEY_SIZE.
811 */
812TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
813 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
814 BlockMode block_mode = BlockMode::GCM;
815 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
816 SCOPED_TRACE(testing::Message()
817 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
818 vector<uint8_t> key_blob;
819 vector<KeyCharacteristics> key_characteristics;
820 // No MIN_MAC_LENGTH provided.
821 auto builder = AuthorizationSetBuilder()
822 .AesEncryptionKey(key_size)
823 .BlockMode(block_mode)
824 .Padding(padding_mode)
825 .SetDefaultValidity();
826 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
827 GenerateKey(builder, &key_blob, &key_characteristics));
828 }
829 }
830}
831
832/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100833 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
834 *
835 * Verifies that specifying an invalid min MAC size for AES key generation returns
836 * UNSUPPORTED_MIN_MAC_LENGTH.
837 */
838TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
839 for (size_t min_mac_len : {88, 136}) {
840 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
841 BlockMode block_mode = BlockMode::GCM;
842 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
843 SCOPED_TRACE(testing::Message()
844 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
845 vector<uint8_t> key_blob;
846 vector<KeyCharacteristics> key_characteristics;
847 auto builder = AuthorizationSetBuilder()
848 .AesEncryptionKey(key_size)
849 .BlockMode(block_mode)
850 .Padding(padding_mode)
851 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
852 .SetDefaultValidity();
853 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
854 GenerateKey(builder, &key_blob, &key_characteristics));
855 }
856 }
857 }
858}
859
860/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000861 * NewKeyGenerationTest.TripleDes
862 *
863 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
864 * have correct characteristics.
865 */
866TEST_P(NewKeyGenerationTest, TripleDes) {
867 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
868 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
869 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
870 SCOPED_TRACE(testing::Message()
871 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
872 vector<uint8_t> key_blob;
873 vector<KeyCharacteristics> key_characteristics;
874 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
875 .TripleDesEncryptionKey(key_size)
876 .BlockMode(block_mode)
877 .Padding(padding_mode)
878 .Authorization(TAG_NO_AUTH_REQUIRED)
879 .SetDefaultValidity(),
880 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100881 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000882
883 EXPECT_GT(key_blob.size(), 0U);
884 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100885 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000886
887 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
888
889 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
890 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
891 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000892 }
893 }
894 }
895}
896
897/*
898 * NewKeyGenerationTest.TripleDesWithAttestation
899 *
900 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
901 * have correct characteristics.
902 *
903 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
904 * put in a certificate) but which isn't an error.
905 */
906TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
907 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
908 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
909 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
910 SCOPED_TRACE(testing::Message()
911 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
912
913 auto challenge = "hello";
914 auto app_id = "foo";
915
916 vector<uint8_t> key_blob;
917 vector<KeyCharacteristics> key_characteristics;
918 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
919 .TripleDesEncryptionKey(key_size)
920 .BlockMode(block_mode)
921 .Padding(padding_mode)
922 .Authorization(TAG_NO_AUTH_REQUIRED)
923 .AttestationChallenge(challenge)
924 .AttestationApplicationId(app_id)
925 .SetDefaultValidity(),
926 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +0100927 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale7de9feb2021-03-05 14:56:19 +0000928
929 EXPECT_GT(key_blob.size(), 0U);
930 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100931 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000932
933 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
934
935 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
936 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
937 << "Key size " << key_size << "missing";
David Drysdale7de9feb2021-03-05 14:56:19 +0000938 }
939 }
940 }
941}
942
943/*
944 * NewKeyGenerationTest.TripleDesInvalidSize
945 *
946 * Verifies that specifying an invalid key size for 3-DES key generation returns
947 * UNSUPPORTED_KEY_SIZE.
948 */
949TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
950 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
951 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
952 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
953 SCOPED_TRACE(testing::Message()
954 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
955 vector<uint8_t> key_blob;
956 vector<KeyCharacteristics> key_characteristics;
957 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
958 GenerateKey(AuthorizationSetBuilder()
959 .TripleDesEncryptionKey(key_size)
960 .BlockMode(block_mode)
961 .Padding(padding_mode)
962 .Authorization(TAG_NO_AUTH_REQUIRED)
963 .SetDefaultValidity(),
964 &key_blob, &key_characteristics));
965 }
966 }
967 }
968
969 // Omitting the key size fails.
970 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
971 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
972 SCOPED_TRACE(testing::Message()
973 << "3DES-default-" << block_mode << "-" << padding_mode);
974 vector<uint8_t> key_blob;
975 vector<KeyCharacteristics> key_characteristics;
976 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
977 GenerateKey(AuthorizationSetBuilder()
978 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
979 .BlockMode(block_mode)
980 .Padding(padding_mode)
981 .Authorization(TAG_NO_AUTH_REQUIRED)
982 .SetDefaultValidity(),
983 &key_blob, &key_characteristics));
984 }
985 }
986}
987
988/*
Selene Huang31ab4042020-04-29 04:22:39 -0700989 * NewKeyGenerationTest.Rsa
990 *
991 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
992 * have correct characteristics.
993 */
994TEST_P(NewKeyGenerationTest, Rsa) {
995 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100996 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -0700997 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700998 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700999 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1000 .RsaSigningKey(key_size, 65537)
1001 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001002 .Padding(PaddingMode::NONE)
1003 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001004 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001005 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07001006
1007 ASSERT_GT(key_blob.size(), 0U);
1008 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001009 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001010
Shawn Willden7f424372021-01-10 18:06:50 -07001011 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001012
1013 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1014 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1015 << "Key size " << key_size << "missing";
1016 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
Selene Huang31ab4042020-04-29 04:22:39 -07001017 }
1018}
1019
1020/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001021 * NewKeyGenerationTest.RsaWithMissingValidity
1022 *
1023 * Verifies that keymint returns an error while generating asymmetric key
1024 * without providing NOT_BEFORE and NOT_AFTER parameters.
1025 */
1026TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
Seth Moore7dc1fda2022-12-12 16:56:20 -08001027 if (AidlVersion() < 3) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001028 /*
1029 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1030 * specified for asymmetric key generation. However, this was not
1031 * checked at the time so we can only be strict about checking this for
Seth Mooreec10c482024-01-23 20:37:24 +00001032 * implementations of KeyMint version 3 and above.
Tommy Chiu7d22f602022-11-14 21:03:34 +08001033 */
Seth Mooreec10c482024-01-23 20:37:24 +00001034 GTEST_SKIP() << "Validity strict since KeyMint v3";
Tommy Chiu7d22f602022-11-14 21:03:34 +08001035 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001036 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1037 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1038 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1039
1040 vector<uint8_t> key_blob;
1041 vector<KeyCharacteristics> key_characteristics;
1042 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1043 GenerateKey(AuthorizationSetBuilder()
1044 .RsaSigningKey(2048, 65537)
1045 .Digest(Digest::NONE)
1046 .Padding(PaddingMode::NONE)
1047 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1048 kUndefinedExpirationDateTime),
1049 &key_blob, &key_characteristics));
1050
1051 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1052 GenerateKey(AuthorizationSetBuilder()
1053 .RsaSigningKey(2048, 65537)
1054 .Digest(Digest::NONE)
1055 .Padding(PaddingMode::NONE)
1056 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1057 &key_blob, &key_characteristics));
1058}
1059
1060/*
David Drysdalead785f52023-03-27 19:53:01 +01001061 * NewKeyGenerationTest.RsaWithSpecifiedValidity
1062 *
1063 * Verifies that KeyMint respects specified NOT_BEFORE and NOT_AFTER certificate dates.
1064 */
1065TEST_P(NewKeyGenerationTest, RsaWithSpecifiedValidity) {
1066 vector<uint8_t> key_blob;
1067 vector<KeyCharacteristics> key_characteristics;
Subrahmanyamane1560212023-05-09 04:40:33 +00001068 vector<uint64_t> test_vector_not_before_millis = {
1069 458046000000, /* 1984-07-07T11:00:00Z */
1070 1183806000000, /* 2007-07-07T11:00:00Z */
1071 1924991999000, /* 2030-12-31T23:59:59Z */
1072 3723753599000, /* 2087-12-31T23:59:59Z */
1073 26223868799000, /* 2800-12-31T23:59:59Z */
1074 45157996799000, /* 3400-12-31T23:59:59Z */
1075 60719587199000, /* 3894-02-15T23:59:59Z */
1076 95302051199000, /* 4989-12-31T23:59:59Z */
1077 86182012799000, /* 4700-12-31T23:59:59Z */
1078 111427574399000, /* 5500-12-31T23:59:59Z */
1079 136988668799000, /* 6310-12-31T23:59:59Z */
1080 139828895999000, /* 6400-12-31T23:59:59Z */
1081 169839503999000, /* 7351-12-31T23:59:59Z */
1082 171385804799000, /* 7400-12-31T23:59:59Z */
1083 190320019199000, /* 8000-12-31T23:59:59Z */
1084 193475692799000, /* 8100-12-31T23:59:59Z */
1085 242515209599000, /* 9654-12-31T23:59:59Z */
1086 250219065599000, /* 9899-02-15T23:59:59Z */
1087 };
1088 for (auto notBefore : test_vector_not_before_millis) {
1089 uint64_t notAfter = notBefore + 378691200000 /* 12 years milliseconds*/;
Subrahmanya Manikanta Venkateswarlu Bhamidipati Kameswara Srib66a37a2024-02-26 19:23:44 +00001090 SCOPED_TRACE(testing::Message() << "notBefore: " << notBefore << " notAfter: " << notAfter);
Subrahmanyamane1560212023-05-09 04:40:33 +00001091 ASSERT_EQ(ErrorCode::OK,
1092 GenerateKey(AuthorizationSetBuilder()
1093 .RsaSigningKey(2048, 65537)
1094 .Digest(Digest::NONE)
1095 .Padding(PaddingMode::NONE)
1096 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, notBefore)
1097 .Authorization(TAG_CERTIFICATE_NOT_AFTER, notAfter),
1098 &key_blob, &key_characteristics));
1099 ASSERT_GT(cert_chain_.size(), 0);
David Drysdalead785f52023-03-27 19:53:01 +01001100
Subrahmanyamane1560212023-05-09 04:40:33 +00001101 X509_Ptr cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1102 ASSERT_TRUE(!!cert.get());
David Drysdalead785f52023-03-27 19:53:01 +01001103
Subrahmanyamane1560212023-05-09 04:40:33 +00001104 const ASN1_TIME* not_before = X509_get0_notBefore(cert.get());
1105 ASSERT_NE(not_before, nullptr);
Subrahmanya Manikanta Venkateswarlu Bhamidipati Kameswara Srib66a37a2024-02-26 19:23:44 +00001106 int64_t not_before_time;
1107 ASSERT_EQ(ASN1_TIME_to_posix(not_before, &not_before_time), 1);
Subrahmanyamane1560212023-05-09 04:40:33 +00001108 EXPECT_EQ(not_before_time, (notBefore / 1000));
David Drysdalead785f52023-03-27 19:53:01 +01001109
Subrahmanyamane1560212023-05-09 04:40:33 +00001110 const ASN1_TIME* not_after = X509_get0_notAfter(cert.get());
1111 ASSERT_NE(not_after, nullptr);
Subrahmanya Manikanta Venkateswarlu Bhamidipati Kameswara Srib66a37a2024-02-26 19:23:44 +00001112 int64_t not_after_time;
1113 ASSERT_EQ(ASN1_TIME_to_posix(not_after, &not_after_time), 1);
Subrahmanyamane1560212023-05-09 04:40:33 +00001114 EXPECT_EQ(not_after_time, (notAfter / 1000));
1115 }
David Drysdalead785f52023-03-27 19:53:01 +01001116}
1117
1118/*
Qi Wud22ec842020-11-26 13:27:53 +08001119 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001120 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001121 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1122 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001123 */
1124TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001125 auto challenge = "hello";
1126 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001127
Selene Huang6e46f142021-04-20 19:20:11 -07001128 auto subject = "cert subj 2";
1129 vector<uint8_t> subject_der(make_name_from_str(subject));
1130
1131 uint64_t serial_int = 66;
1132 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1133
Selene Huang4f64c222021-04-13 19:54:36 -07001134 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001135 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001136 vector<uint8_t> key_blob;
1137 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001138 auto builder = AuthorizationSetBuilder()
1139 .RsaSigningKey(key_size, 65537)
1140 .Digest(Digest::NONE)
1141 .Padding(PaddingMode::NONE)
1142 .AttestationChallenge(challenge)
1143 .AttestationApplicationId(app_id)
1144 .Authorization(TAG_NO_AUTH_REQUIRED)
1145 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1146 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1147 .SetDefaultValidity();
1148
1149 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001150 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001151 KeyBlobDeleter deleter(keymint_, key_blob);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001152 ASSERT_GT(key_blob.size(), 0U);
1153 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001154 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001155
1156 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1157
1158 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1159 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1160 << "Key size " << key_size << "missing";
1161 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1162
David Drysdalea8a888e2022-06-08 12:43:56 +01001163 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001164 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001165 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001166
1167 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1168 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001169 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001170 sw_enforced, hw_enforced, SecLevel(),
1171 cert_chain_[0].encodedCertificate));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001172 }
1173}
1174
1175/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001176 * NewKeyGenerationTest.RsaWithRkpAttestation
David Drysdale4dc01072021-04-01 12:17:35 +01001177 *
Seth Moore7dc1fda2022-12-12 16:56:20 -08001178 * Verifies that keymint can generate all required RSA key sizes using an attestation key
David Drysdale4dc01072021-04-01 12:17:35 +01001179 * that has been generated using an associate IRemotelyProvisionedComponent.
1180 */
Seth Moore7dc1fda2022-12-12 16:56:20 -08001181TEST_P(NewKeyGenerationTest, RsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001182 if (!IsRkpSupportRequired()) {
1183 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001184 }
1185
Seth Moore5a0320f2023-03-24 12:29:08 -07001186 // Check for an IRemotelyProvisionedComponent instance associated with the
1187 // KeyMint instance.
1188 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1189 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1190 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1191 }
1192 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1193 << GetParam();
David Drysdale4dc01072021-04-01 12:17:35 +01001194
1195 // Generate a P-256 keypair to use as an attestation key.
1196 MacedPublicKey macedPubKey;
1197 std::vector<uint8_t> privateKeyBlob;
1198 auto status =
1199 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1200 ASSERT_TRUE(status.isOk());
1201 vector<uint8_t> coseKeyData;
1202 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1203
1204 AttestationKey attestation_key;
1205 attestation_key.keyBlob = std::move(privateKeyBlob);
1206 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1207
1208 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001209 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdale4dc01072021-04-01 12:17:35 +01001210 auto challenge = "hello";
1211 auto app_id = "foo";
1212
1213 vector<uint8_t> key_blob;
1214 vector<KeyCharacteristics> key_characteristics;
1215 ASSERT_EQ(ErrorCode::OK,
1216 GenerateKey(AuthorizationSetBuilder()
1217 .RsaSigningKey(key_size, 65537)
1218 .Digest(Digest::NONE)
1219 .Padding(PaddingMode::NONE)
1220 .AttestationChallenge(challenge)
1221 .AttestationApplicationId(app_id)
1222 .Authorization(TAG_NO_AUTH_REQUIRED)
1223 .SetDefaultValidity(),
1224 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
David Drysdale1b9febc2023-06-07 13:43:24 +01001225 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale4dc01072021-04-01 12:17:35 +01001226
1227 ASSERT_GT(key_blob.size(), 0U);
1228 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001229 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001230
1231 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1232
1233 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1234 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1235 << "Key size " << key_size << "missing";
1236 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1237
1238 // Attestation by itself is not valid (last entry is not self-signed).
1239 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1240
1241 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001242 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001243 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1244 ASSERT_TRUE(key_cert.get());
1245 EVP_PKEY_Ptr signing_pubkey;
1246 p256_pub_key(coseKeyData, &signing_pubkey);
1247 ASSERT_TRUE(signing_pubkey.get());
1248
1249 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1250 << "Verification of attested certificate failed "
1251 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
David Drysdale4dc01072021-04-01 12:17:35 +01001252 }
1253}
1254
1255/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001256 * NewKeyGenerationTest.EcdsaWithRkpAttestation
1257 *
1258 * Verifies that keymint can generate all required ECDSA key sizes using an attestation key
1259 * that has been generated using an associate IRemotelyProvisionedComponent.
1260 */
1261TEST_P(NewKeyGenerationTest, EcdsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001262 if (!IsRkpSupportRequired()) {
1263 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001264 }
1265
Seth Moore5a0320f2023-03-24 12:29:08 -07001266 // Check for an IRemotelyProvisionedComponent instance associated with the
1267 // KeyMint instance.
1268 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1269 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1270 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1271 }
1272 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1273 << GetParam();
Seth Moore7dc1fda2022-12-12 16:56:20 -08001274
1275 // Generate a P-256 keypair to use as an attestation key.
1276 MacedPublicKey macedPubKey;
1277 std::vector<uint8_t> privateKeyBlob;
1278 auto status =
1279 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1280 ASSERT_TRUE(status.isOk());
1281 vector<uint8_t> coseKeyData;
1282 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1283
1284 AttestationKey attestation_key;
1285 attestation_key.keyBlob = std::move(privateKeyBlob);
1286 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1287
1288 for (auto curve : ValidCurves()) {
1289 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
1290 auto challenge = "hello";
1291 auto app_id = "foo";
1292
1293 vector<uint8_t> key_blob;
1294 vector<KeyCharacteristics> key_characteristics;
1295 ASSERT_EQ(ErrorCode::OK,
1296 GenerateKey(AuthorizationSetBuilder()
1297 .EcdsaSigningKey(curve)
1298 .Digest(Digest::NONE)
1299 .AttestationChallenge(challenge)
1300 .AttestationApplicationId(app_id)
1301 .Authorization(TAG_NO_AUTH_REQUIRED)
1302 .SetDefaultValidity(),
1303 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
David Drysdale1b9febc2023-06-07 13:43:24 +01001304 KeyBlobDeleter deleter(keymint_, key_blob);
Seth Moore7dc1fda2022-12-12 16:56:20 -08001305
1306 ASSERT_GT(key_blob.size(), 0U);
1307 CheckBaseParams(key_characteristics);
1308 CheckCharacteristics(key_blob, key_characteristics);
1309
1310 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1311
1312 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1313 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1314
1315 // Attestation by itself is not valid (last entry is not self-signed).
1316 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1317
1318 // The signature over the attested key should correspond to the P256 public key.
1319 ASSERT_GT(cert_chain_.size(), 0);
1320 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1321 ASSERT_TRUE(key_cert.get());
1322 EVP_PKEY_Ptr signing_pubkey;
1323 p256_pub_key(coseKeyData, &signing_pubkey);
1324 ASSERT_TRUE(signing_pubkey.get());
1325
1326 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1327 << "Verification of attested certificate failed "
1328 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
Seth Moore7dc1fda2022-12-12 16:56:20 -08001329 }
1330}
1331
1332/*
Selene Huang4f64c222021-04-13 19:54:36 -07001333 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1334 *
1335 * Verifies that keymint attestation for RSA encryption keys with challenge and
1336 * app id is also successful.
1337 */
1338TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1339 auto key_size = 2048;
1340 auto challenge = "hello";
1341 auto app_id = "foo";
1342
Selene Huang6e46f142021-04-20 19:20:11 -07001343 auto subject = "subj 2";
1344 vector<uint8_t> subject_der(make_name_from_str(subject));
1345
1346 uint64_t serial_int = 111166;
1347 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1348
Selene Huang4f64c222021-04-13 19:54:36 -07001349 vector<uint8_t> key_blob;
1350 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001351 auto builder = AuthorizationSetBuilder()
1352 .RsaEncryptionKey(key_size, 65537)
1353 .Padding(PaddingMode::NONE)
1354 .AttestationChallenge(challenge)
1355 .AttestationApplicationId(app_id)
1356 .Authorization(TAG_NO_AUTH_REQUIRED)
1357 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1358 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1359 .SetDefaultValidity();
1360
1361 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001362 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001363 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001364
1365 ASSERT_GT(key_blob.size(), 0U);
1366 AuthorizationSet auths;
1367 for (auto& entry : key_characteristics) {
1368 auths.push_back(AuthorizationSet(entry.authorizations));
1369 }
1370
1371 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1372 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1373
1374 // Verify that App data and ROT are NOT included.
1375 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1376 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1377
1378 // Check that some unexpected tags/values are NOT present.
1379 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1380 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1381
1382 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1383
1384 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1385 ASSERT_TRUE(os_ver);
1386 EXPECT_EQ(*os_ver, os_version());
1387
1388 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1389
1390 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1391 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1392 << "Key size " << key_size << "missing";
1393 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1394
David Drysdalea8a888e2022-06-08 12:43:56 +01001395 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001396 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001397 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001398
1399 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1400 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001401 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001402 sw_enforced, hw_enforced, SecLevel(),
1403 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07001404}
1405
1406/*
1407 * NewKeyGenerationTest.RsaWithSelfSign
1408 *
1409 * Verifies that attesting to RSA key generation is successful, and returns
1410 * self signed certificate if no challenge is provided. And signing etc
1411 * works as expected.
1412 */
1413TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001414 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1415 vector<uint8_t> subject_der(make_name_from_str(subject));
1416
1417 uint64_t serial_int = 0;
1418 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1419
Selene Huang4f64c222021-04-13 19:54:36 -07001420 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001421 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang4f64c222021-04-13 19:54:36 -07001422 vector<uint8_t> key_blob;
1423 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001424 ASSERT_EQ(ErrorCode::OK,
1425 GenerateKey(AuthorizationSetBuilder()
1426 .RsaSigningKey(key_size, 65537)
1427 .Digest(Digest::NONE)
1428 .Padding(PaddingMode::NONE)
1429 .Authorization(TAG_NO_AUTH_REQUIRED)
1430 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1431 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1432 .SetDefaultValidity(),
1433 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001434 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001435
1436 ASSERT_GT(key_blob.size(), 0U);
1437 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001438 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001439
1440 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1441
1442 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1443 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1444 << "Key size " << key_size << "missing";
1445 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1446
David Drysdalea8a888e2022-06-08 12:43:56 +01001447 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001448 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001449 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001450 }
1451}
1452
1453/*
1454 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1455 *
1456 * Verifies that attesting to RSA checks for missing app ID.
1457 */
1458TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1459 auto challenge = "hello";
1460 vector<uint8_t> key_blob;
1461 vector<KeyCharacteristics> key_characteristics;
1462
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001463 auto builder = AuthorizationSetBuilder()
1464 .RsaSigningKey(2048, 65537)
1465 .Digest(Digest::NONE)
1466 .Padding(PaddingMode::NONE)
1467 .AttestationChallenge(challenge)
1468 .Authorization(TAG_NO_AUTH_REQUIRED)
1469 .SetDefaultValidity();
1470
1471 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001472 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001473}
1474
1475/*
1476 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1477 *
1478 * Verifies that attesting to RSA ignores app id if challenge is missing.
1479 */
1480TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1481 auto key_size = 2048;
1482 auto app_id = "foo";
1483
Selene Huang6e46f142021-04-20 19:20:11 -07001484 auto subject = "cert subj 2";
1485 vector<uint8_t> subject_der(make_name_from_str(subject));
1486
1487 uint64_t serial_int = 1;
1488 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1489
Selene Huang4f64c222021-04-13 19:54:36 -07001490 vector<uint8_t> key_blob;
1491 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001492 ASSERT_EQ(ErrorCode::OK,
1493 GenerateKey(AuthorizationSetBuilder()
1494 .RsaSigningKey(key_size, 65537)
1495 .Digest(Digest::NONE)
1496 .Padding(PaddingMode::NONE)
1497 .AttestationApplicationId(app_id)
1498 .Authorization(TAG_NO_AUTH_REQUIRED)
1499 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1500 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1501 .SetDefaultValidity(),
1502 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001503 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001504
1505 ASSERT_GT(key_blob.size(), 0U);
1506 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001507 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001508
1509 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1510
1511 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1512 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1513 << "Key size " << key_size << "missing";
1514 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1515
David Drysdalea8a888e2022-06-08 12:43:56 +01001516 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001517 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001518 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1519 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang4f64c222021-04-13 19:54:36 -07001520}
1521
1522/*
Qi Wud22ec842020-11-26 13:27:53 +08001523 * NewKeyGenerationTest.LimitedUsageRsa
1524 *
1525 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1526 * resulting keys have correct characteristics.
1527 */
1528TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1529 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001530 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wud22ec842020-11-26 13:27:53 +08001531 vector<uint8_t> key_blob;
1532 vector<KeyCharacteristics> key_characteristics;
1533 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1534 .RsaSigningKey(key_size, 65537)
1535 .Digest(Digest::NONE)
1536 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001537 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1538 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001539 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001540 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08001541
1542 ASSERT_GT(key_blob.size(), 0U);
1543 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001544 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001545
1546 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1547
1548 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1549 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1550 << "Key size " << key_size << "missing";
1551 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1552
1553 // Check the usage count limit tag appears in the authorizations.
1554 AuthorizationSet auths;
1555 for (auto& entry : key_characteristics) {
1556 auths.push_back(AuthorizationSet(entry.authorizations));
1557 }
1558 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1559 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08001560 }
1561}
1562
1563/*
Qi Wubeefae42021-01-28 23:16:37 +08001564 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1565 *
1566 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1567 * resulting keys have correct characteristics and attestation.
1568 */
1569TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001570 auto challenge = "hello";
1571 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001572
Selene Huang6e46f142021-04-20 19:20:11 -07001573 auto subject = "cert subj 2";
1574 vector<uint8_t> subject_der(make_name_from_str(subject));
1575
1576 uint64_t serial_int = 66;
1577 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1578
Selene Huang4f64c222021-04-13 19:54:36 -07001579 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001580 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wubeefae42021-01-28 23:16:37 +08001581 vector<uint8_t> key_blob;
1582 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001583 auto builder = AuthorizationSetBuilder()
1584 .RsaSigningKey(key_size, 65537)
1585 .Digest(Digest::NONE)
1586 .Padding(PaddingMode::NONE)
1587 .AttestationChallenge(challenge)
1588 .AttestationApplicationId(app_id)
1589 .Authorization(TAG_NO_AUTH_REQUIRED)
1590 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1591 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1592 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1593 .SetDefaultValidity();
1594
1595 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001596 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001597 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wubeefae42021-01-28 23:16:37 +08001598
1599 ASSERT_GT(key_blob.size(), 0U);
1600 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001601 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001602
1603 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1604
1605 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1606 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1607 << "Key size " << key_size << "missing";
1608 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1609
1610 // Check the usage count limit tag appears in the authorizations.
1611 AuthorizationSet auths;
1612 for (auto& entry : key_characteristics) {
1613 auths.push_back(AuthorizationSet(entry.authorizations));
1614 }
1615 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1616 << "key usage count limit " << 1U << " missing";
1617
1618 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001619 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001620 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001621 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001622
1623 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1624 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001625 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001626 sw_enforced, hw_enforced, SecLevel(),
1627 cert_chain_[0].encodedCertificate));
Qi Wubeefae42021-01-28 23:16:37 +08001628 }
1629}
1630
1631/*
Selene Huang31ab4042020-04-29 04:22:39 -07001632 * NewKeyGenerationTest.NoInvalidRsaSizes
1633 *
1634 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1635 */
1636TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1637 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001638 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07001639 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001640 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001641 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1642 GenerateKey(AuthorizationSetBuilder()
1643 .RsaSigningKey(key_size, 65537)
1644 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001645 .Padding(PaddingMode::NONE)
1646 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001647 &key_blob, &key_characteristics));
1648 }
1649}
1650
1651/*
1652 * NewKeyGenerationTest.RsaNoDefaultSize
1653 *
1654 * Verifies that failing to specify a key size for RSA key generation returns
1655 * UNSUPPORTED_KEY_SIZE.
1656 */
1657TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1658 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1659 GenerateKey(AuthorizationSetBuilder()
1660 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1661 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001662 .SigningKey()
1663 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001664}
1665
1666/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001667 * NewKeyGenerationTest.RsaMissingParams
1668 *
1669 * Verifies that omitting optional tags works.
1670 */
1671TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1672 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001673 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdaled2cc8c22021-04-15 13:29:45 +01001674 ASSERT_EQ(ErrorCode::OK,
1675 GenerateKey(
1676 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1677 CheckedDeleteKey();
1678 }
1679}
1680
1681/*
Selene Huang31ab4042020-04-29 04:22:39 -07001682 * NewKeyGenerationTest.Ecdsa
1683 *
David Drysdale42fe1892021-10-14 14:43:46 +01001684 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001685 * have correct characteristics.
1686 */
1687TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001688 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001689 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07001690 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001691 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001692 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001693 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001694 .Digest(Digest::NONE)
1695 .SetDefaultValidity(),
1696 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01001697 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07001698 ASSERT_GT(key_blob.size(), 0U);
1699 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001700 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001701
Shawn Willden7f424372021-01-10 18:06:50 -07001702 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001703
1704 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001705 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001706 }
1707}
1708
1709/*
David Drysdale42fe1892021-10-14 14:43:46 +01001710 * NewKeyGenerationTest.EcdsaCurve25519
1711 *
1712 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1713 * has correct characteristics.
1714 */
1715TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1716 if (!Curve25519Supported()) {
1717 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1718 }
1719
1720 EcCurve curve = EcCurve::CURVE_25519;
1721 vector<uint8_t> key_blob;
1722 vector<KeyCharacteristics> key_characteristics;
1723 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1724 .EcdsaSigningKey(curve)
1725 .Digest(Digest::NONE)
1726 .SetDefaultValidity(),
1727 &key_blob, &key_characteristics);
1728 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01001729 KeyBlobDeleter deleter(keymint_, key_blob);
1730
David Drysdale42fe1892021-10-14 14:43:46 +01001731 ASSERT_GT(key_blob.size(), 0U);
1732
1733 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1734 ASSERT_GT(cert_chain_.size(), 0);
1735
1736 CheckBaseParams(key_characteristics);
1737 CheckCharacteristics(key_blob, key_characteristics);
1738
1739 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1740
1741 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1742 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
David Drysdale42fe1892021-10-14 14:43:46 +01001743}
1744
1745/*
1746 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1747 *
1748 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1749 * SIGN and AGREE_KEY.
1750 */
1751TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1752 if (!Curve25519Supported()) {
1753 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1754 }
1755
1756 EcCurve curve = EcCurve::CURVE_25519;
1757 vector<uint8_t> key_blob;
1758 vector<KeyCharacteristics> key_characteristics;
1759 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1760 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1761 .EcdsaSigningKey(curve)
1762 .Digest(Digest::NONE)
1763 .SetDefaultValidity(),
1764 &key_blob, &key_characteristics);
1765 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1766}
1767
1768/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001769 * NewKeyGenerationTest.EcdsaWithMissingValidity
1770 *
1771 * Verifies that keymint returns an error while generating asymmetric key
1772 * without providing NOT_BEFORE and NOT_AFTER parameters.
1773 */
1774TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001775 if (AidlVersion() < 2) {
1776 /*
1777 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1778 * specified for asymmetric key generation. However, this was not
1779 * checked at the time so we can only be strict about checking this for
1780 * implementations of KeyMint version 2 and above.
1781 */
1782 GTEST_SKIP() << "Validity strict since KeyMint v2";
1783 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001784 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1785 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1786 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1787
1788 vector<uint8_t> key_blob;
1789 vector<KeyCharacteristics> key_characteristics;
1790 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1791 GenerateKey(AuthorizationSetBuilder()
1792 .EcdsaSigningKey(EcCurve::P_256)
1793 .Digest(Digest::NONE)
1794 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1795 kUndefinedExpirationDateTime),
1796 &key_blob, &key_characteristics));
1797
1798 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1799 GenerateKey(AuthorizationSetBuilder()
1800 .EcdsaSigningKey(EcCurve::P_256)
1801 .Digest(Digest::NONE)
1802 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1803 &key_blob, &key_characteristics));
1804}
1805
1806/*
Selene Huang4f64c222021-04-13 19:54:36 -07001807 * NewKeyGenerationTest.EcdsaAttestation
1808 *
1809 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1810 * an attestation will be generated.
1811 */
1812TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1813 auto challenge = "hello";
1814 auto app_id = "foo";
1815
Selene Huang6e46f142021-04-20 19:20:11 -07001816 auto subject = "cert subj 2";
1817 vector<uint8_t> subject_der(make_name_from_str(subject));
1818
1819 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1820 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1821
David Drysdaledf09e542021-06-08 15:46:11 +01001822 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001823 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07001824 vector<uint8_t> key_blob;
1825 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001826 auto builder = AuthorizationSetBuilder()
1827 .Authorization(TAG_NO_AUTH_REQUIRED)
1828 .EcdsaSigningKey(curve)
1829 .Digest(Digest::NONE)
1830 .AttestationChallenge(challenge)
1831 .AttestationApplicationId(app_id)
1832 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1833 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1834 .SetDefaultValidity();
1835
1836 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001837 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001838 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07001839 ASSERT_GT(key_blob.size(), 0U);
1840 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001841 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001842
1843 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1844
1845 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001846 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001847
1848 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1849 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001850 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001851
1852 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1853 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001854 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001855 sw_enforced, hw_enforced, SecLevel(),
1856 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07001857 }
1858}
1859
1860/*
David Drysdale42fe1892021-10-14 14:43:46 +01001861 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1862 *
1863 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1864 * an attestation will be generated.
1865 */
1866TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1867 if (!Curve25519Supported()) {
1868 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1869 }
1870
1871 EcCurve curve = EcCurve::CURVE_25519;
1872 auto challenge = "hello";
1873 auto app_id = "foo";
1874
1875 auto subject = "cert subj 2";
1876 vector<uint8_t> subject_der(make_name_from_str(subject));
1877
1878 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1879 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1880
1881 vector<uint8_t> key_blob;
1882 vector<KeyCharacteristics> key_characteristics;
1883 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1884 .Authorization(TAG_NO_AUTH_REQUIRED)
1885 .EcdsaSigningKey(curve)
1886 .Digest(Digest::NONE)
1887 .AttestationChallenge(challenge)
1888 .AttestationApplicationId(app_id)
1889 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1890 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1891 .SetDefaultValidity(),
1892 &key_blob, &key_characteristics);
1893 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01001894 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale42fe1892021-10-14 14:43:46 +01001895 ASSERT_GT(key_blob.size(), 0U);
1896 CheckBaseParams(key_characteristics);
1897 CheckCharacteristics(key_blob, key_characteristics);
1898
1899 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1900
1901 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1902 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1903
1904 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1905 ASSERT_GT(cert_chain_.size(), 0);
1906 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1907
1908 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1909 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1910 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1911 sw_enforced, hw_enforced, SecLevel(),
1912 cert_chain_[0].encodedCertificate));
David Drysdale42fe1892021-10-14 14:43:46 +01001913}
1914
1915/*
David Drysdale37af4b32021-05-14 16:46:59 +01001916 * NewKeyGenerationTest.EcdsaAttestationTags
1917 *
1918 * Verifies that creation of an attested ECDSA key includes various tags in the
1919 * attestation extension.
1920 */
1921TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1922 auto challenge = "hello";
1923 auto app_id = "foo";
1924 auto subject = "cert subj 2";
1925 vector<uint8_t> subject_der(make_name_from_str(subject));
1926 uint64_t serial_int = 0x1010;
1927 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1928 const AuthorizationSetBuilder base_builder =
1929 AuthorizationSetBuilder()
1930 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001931 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001932 .Digest(Digest::NONE)
1933 .AttestationChallenge(challenge)
1934 .AttestationApplicationId(app_id)
1935 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1936 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1937 .SetDefaultValidity();
1938
1939 // Various tags that map to fields in the attestation extension ASN.1 schema.
1940 auto extra_tags = AuthorizationSetBuilder()
1941 .Authorization(TAG_ROLLBACK_RESISTANCE)
1942 .Authorization(TAG_EARLY_BOOT_ONLY)
1943 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1944 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1945 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1946 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1947 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1948 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1949 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1950 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1951 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1952 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001953
David Drysdale37af4b32021-05-14 16:46:59 +01001954 for (const KeyParameter& tag : extra_tags) {
1955 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1956 vector<uint8_t> key_blob;
1957 vector<KeyCharacteristics> key_characteristics;
1958 AuthorizationSetBuilder builder = base_builder;
1959 builder.push_back(tag);
1960 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1961 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1962 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1963 continue;
1964 }
Seth Mooreb393b082021-07-12 14:18:28 -07001965 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1966 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001967 continue;
1968 }
1969 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01001970 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale37af4b32021-05-14 16:46:59 +01001971 ASSERT_GT(key_blob.size(), 0U);
1972
1973 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1974 ASSERT_GT(cert_chain_.size(), 0);
1975 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1976
1977 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1978 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001979 // Some tags are optional, so don't require them to be in the enforcements.
1980 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001981 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1982 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1983 }
1984
1985 // Verifying the attestation record will check for the specific tag because
1986 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001987 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1988 hw_enforced, SecLevel(),
1989 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001990 }
1991
David Drysdalec53b7d92021-10-11 12:35:58 +01001992 // Collection of invalid attestation ID tags.
1993 auto invalid_tags =
1994 AuthorizationSetBuilder()
1995 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1996 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1997 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1998 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1999 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
2000 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
2001 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
2002 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01002003 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01002004 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01002005 vector<uint8_t> key_blob;
2006 vector<KeyCharacteristics> key_characteristics;
2007 AuthorizationSetBuilder builder =
2008 AuthorizationSetBuilder()
2009 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002010 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01002011 .Digest(Digest::NONE)
2012 .AttestationChallenge(challenge)
2013 .AttestationApplicationId(app_id)
2014 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2015 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2016 .SetDefaultValidity();
2017 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002018
2019 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
David Drysdalec68dc932023-07-06 10:05:12 +01002020 device_id_attestation_check_acceptable_error(tag.tag, error);
David Drysdale37af4b32021-05-14 16:46:59 +01002021 }
2022}
2023
2024/*
David Drysdalec53b7d92021-10-11 12:35:58 +01002025 * NewKeyGenerationTest.EcdsaAttestationIdTags
2026 *
2027 * Verifies that creation of an attested ECDSA key includes various ID tags in the
2028 * attestation extension.
2029 */
2030TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
2031 auto challenge = "hello";
2032 auto app_id = "foo";
2033 auto subject = "cert subj 2";
2034 vector<uint8_t> subject_der(make_name_from_str(subject));
2035 uint64_t serial_int = 0x1010;
2036 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2037 const AuthorizationSetBuilder base_builder =
2038 AuthorizationSetBuilder()
2039 .Authorization(TAG_NO_AUTH_REQUIRED)
2040 .EcdsaSigningKey(EcCurve::P_256)
2041 .Digest(Digest::NONE)
2042 .AttestationChallenge(challenge)
2043 .AttestationApplicationId(app_id)
2044 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2045 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2046 .SetDefaultValidity();
2047
2048 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2049 auto extra_tags = AuthorizationSetBuilder();
Prashant Patil24f75792023-09-07 15:25:14 +00002050 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_BRAND, "brand");
2051 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "device");
2052 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "name");
2053 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer");
2054 add_attestation_id(&extra_tags, TAG_ATTESTATION_ID_MODEL, "model");
Tri Vo799e4352022-11-07 17:23:50 -08002055 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
David Drysdalec53b7d92021-10-11 12:35:58 +01002056
2057 for (const KeyParameter& tag : extra_tags) {
2058 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2059 vector<uint8_t> key_blob;
2060 vector<KeyCharacteristics> key_characteristics;
2061 AuthorizationSetBuilder builder = base_builder;
2062 builder.push_back(tag);
2063 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
Prashant Patil88ad1892022-03-15 16:31:02 +00002064 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2065 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002066 continue;
2067 }
2068 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002069 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdalec53b7d92021-10-11 12:35:58 +01002070 ASSERT_GT(key_blob.size(), 0U);
2071
2072 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2073 ASSERT_GT(cert_chain_.size(), 0);
2074 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2075
2076 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2077 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2078
2079 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2080 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2081 // attestation extension should contain them, so make sure the extra tag is added.
2082 hw_enforced.push_back(tag);
2083
2084 // Verifying the attestation record will check for the specific tag because
2085 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002086 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2087 hw_enforced, SecLevel(),
2088 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002089 }
2090}
2091
2092/*
David Drysdale565ccc72021-10-11 12:49:50 +01002093 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2094 *
2095 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2096 */
2097TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2098 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002099 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002100 auto challenge = "hello";
2101 auto subject = "cert subj 2";
2102 vector<uint8_t> subject_der(make_name_from_str(subject));
2103 uint64_t serial_int = 0x1010;
2104 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002105 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002106 AuthorizationSetBuilder()
2107 .Authorization(TAG_NO_AUTH_REQUIRED)
2108 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2109 .EcdsaSigningKey(EcCurve::P_256)
2110 .Digest(Digest::NONE)
2111 .AttestationChallenge(challenge)
2112 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2113 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2114 .AttestationApplicationId(app_id)
2115 .Authorization(TAG_CREATION_DATETIME, datetime)
2116 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002117 if (reset) {
2118 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2119 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002120 auto result = GenerateKey(builder);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002121 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002122 ASSERT_GT(key_blob_.size(), 0U);
2123
2124 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2125 ASSERT_GT(cert_chain_.size(), 0);
2126 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2127
2128 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2129 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2130
2131 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002132 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2133 hw_enforced, SecLevel(),
2134 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002135 EXPECT_GT(unique_id->size(), 0);
2136 CheckedDeleteKey();
2137 };
2138
2139 // Generate unique ID
2140 auto app_id = "foo";
2141 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2142 vector<uint8_t> unique_id;
2143 get_unique_id(app_id, cert_date, &unique_id);
2144
2145 // Generating a new key with the same parameters should give the same unique ID.
2146 vector<uint8_t> unique_id2;
2147 get_unique_id(app_id, cert_date, &unique_id2);
2148 EXPECT_EQ(unique_id, unique_id2);
2149
2150 // Generating a new key with a slightly different date should give the same unique ID.
2151 uint64_t rounded_date = cert_date / 2592000000LLU;
2152 uint64_t min_date = rounded_date * 2592000000LLU;
2153 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2154
2155 vector<uint8_t> unique_id3;
2156 get_unique_id(app_id, min_date, &unique_id3);
2157 EXPECT_EQ(unique_id, unique_id3);
2158
2159 vector<uint8_t> unique_id4;
2160 get_unique_id(app_id, max_date, &unique_id4);
2161 EXPECT_EQ(unique_id, unique_id4);
2162
2163 // A different attestation application ID should yield a different unique ID.
2164 auto app_id2 = "different_foo";
2165 vector<uint8_t> unique_id5;
2166 get_unique_id(app_id2, cert_date, &unique_id5);
2167 EXPECT_NE(unique_id, unique_id5);
2168
2169 // A radically different date should yield a different unique ID.
2170 vector<uint8_t> unique_id6;
2171 get_unique_id(app_id, 1611621648000, &unique_id6);
2172 EXPECT_NE(unique_id, unique_id6);
2173
2174 vector<uint8_t> unique_id7;
2175 get_unique_id(app_id, max_date + 1, &unique_id7);
2176 EXPECT_NE(unique_id, unique_id7);
2177
2178 vector<uint8_t> unique_id8;
2179 get_unique_id(app_id, min_date - 1, &unique_id8);
2180 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002181
2182 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2183 vector<uint8_t> unique_id9;
2184 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2185 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002186}
2187
2188/*
David Drysdale37af4b32021-05-14 16:46:59 +01002189 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2190 *
2191 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2192 */
2193TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2194 auto challenge = "hello";
2195 auto attest_app_id = "foo";
2196 auto subject = "cert subj 2";
2197 vector<uint8_t> subject_der(make_name_from_str(subject));
2198 uint64_t serial_int = 0x1010;
2199 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2200
2201 // Earlier versions of the attestation extension schema included a slot:
2202 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2203 // This should never have been included, and should never be filled in.
2204 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2205 // to confirm that this field never makes it into the attestation extension.
2206 vector<uint8_t> key_blob;
2207 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002208 auto builder = AuthorizationSetBuilder()
2209 .Authorization(TAG_NO_AUTH_REQUIRED)
2210 .EcdsaSigningKey(EcCurve::P_256)
2211 .Digest(Digest::NONE)
2212 .AttestationChallenge(challenge)
2213 .AttestationApplicationId(attest_app_id)
2214 .Authorization(TAG_APPLICATION_ID, "client_id")
2215 .Authorization(TAG_APPLICATION_DATA, "appdata")
2216 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2217 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2218 .SetDefaultValidity();
2219
2220 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
David Drysdale37af4b32021-05-14 16:46:59 +01002221 ASSERT_EQ(result, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01002222 KeyBlobDeleter deleter(keymint_, key_blob);
David Drysdale37af4b32021-05-14 16:46:59 +01002223 ASSERT_GT(key_blob.size(), 0U);
2224
2225 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2226 ASSERT_GT(cert_chain_.size(), 0);
2227 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2228
2229 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2230 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002231 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2232 hw_enforced, SecLevel(),
2233 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002234
2235 // Check that the app id is not in the cert.
2236 string app_id = "clientid";
2237 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2238 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2239 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2240 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2241 cert_chain_[0].encodedCertificate.end());
David Drysdale37af4b32021-05-14 16:46:59 +01002242}
2243
2244/*
Selene Huang4f64c222021-04-13 19:54:36 -07002245 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2246 *
2247 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2248 * the key will generate a self signed attestation.
2249 */
2250TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002251 auto subject = "cert subj 2";
2252 vector<uint8_t> subject_der(make_name_from_str(subject));
2253
2254 uint64_t serial_int = 0x123456FFF1234;
2255 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2256
David Drysdaledf09e542021-06-08 15:46:11 +01002257 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002258 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002259 vector<uint8_t> key_blob;
2260 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002261 ASSERT_EQ(ErrorCode::OK,
2262 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002263 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002264 .Digest(Digest::NONE)
2265 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2266 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2267 .SetDefaultValidity(),
2268 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002269 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002270 ASSERT_GT(key_blob.size(), 0U);
2271 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002272 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002273
2274 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2275
2276 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002277 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002278
2279 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2280 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002281 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002282
2283 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2284 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002285 }
2286}
2287
2288/*
2289 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2290 *
2291 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2292 * app id must also be provided or else it will fail.
2293 */
2294TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2295 auto challenge = "hello";
2296 vector<uint8_t> key_blob;
2297 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002298 auto builder = AuthorizationSetBuilder()
2299 .EcdsaSigningKey(EcCurve::P_256)
2300 .Digest(Digest::NONE)
2301 .AttestationChallenge(challenge)
2302 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002303
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002304 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002305 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002306}
2307
2308/*
2309 * NewKeyGenerationTest.EcdsaIgnoreAppId
2310 *
2311 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2312 * any appid will be ignored, and keymint will generate a self sign certificate.
2313 */
2314TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2315 auto app_id = "foo";
2316
David Drysdaledf09e542021-06-08 15:46:11 +01002317 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002318 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002319 vector<uint8_t> key_blob;
2320 vector<KeyCharacteristics> key_characteristics;
2321 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002322 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002323 .Digest(Digest::NONE)
2324 .AttestationApplicationId(app_id)
2325 .SetDefaultValidity(),
2326 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002327 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002328
2329 ASSERT_GT(key_blob.size(), 0U);
2330 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002331 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002332
2333 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2334
2335 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002336 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002337
2338 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2339 ASSERT_EQ(cert_chain_.size(), 1);
2340
2341 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2342 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002343 }
2344}
2345
2346/*
2347 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2348 *
2349 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2350 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2351 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2352 * to specify how many following bytes will be used to encode the length.
2353 */
2354TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2355 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002356 std::vector<uint32_t> app_id_lengths{143, 258};
2357
2358 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002359 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002360 const string app_id(length, 'a');
2361 vector<uint8_t> key_blob;
2362 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002363 auto builder = AuthorizationSetBuilder()
2364 .Authorization(TAG_NO_AUTH_REQUIRED)
2365 .EcdsaSigningKey(EcCurve::P_256)
2366 .Digest(Digest::NONE)
2367 .AttestationChallenge(challenge)
2368 .AttestationApplicationId(app_id)
2369 .SetDefaultValidity();
2370
2371 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002372 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale1b9febc2023-06-07 13:43:24 +01002373 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002374 ASSERT_GT(key_blob.size(), 0U);
2375 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002376 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002377
2378 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2379
2380 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002381 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002382
2383 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2384 ASSERT_GT(cert_chain_.size(), 0);
2385
2386 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2387 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002388 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002389 sw_enforced, hw_enforced, SecLevel(),
2390 cert_chain_[0].encodedCertificate));
Selene Huang4f64c222021-04-13 19:54:36 -07002391 }
2392}
2393
2394/*
Qi Wud22ec842020-11-26 13:27:53 +08002395 * NewKeyGenerationTest.LimitedUsageEcdsa
2396 *
2397 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2398 * resulting keys have correct characteristics.
2399 */
2400TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002401 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002402 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002403 vector<uint8_t> key_blob;
2404 vector<KeyCharacteristics> key_characteristics;
2405 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002406 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002407 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002408 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2409 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002410 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002411 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002412
2413 ASSERT_GT(key_blob.size(), 0U);
2414 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002415 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002416
2417 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2418
2419 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002420 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002421
2422 // Check the usage count limit tag appears in the authorizations.
2423 AuthorizationSet auths;
2424 for (auto& entry : key_characteristics) {
2425 auths.push_back(AuthorizationSet(entry.authorizations));
2426 }
2427 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2428 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002429 }
2430}
2431
2432/*
Selene Huang31ab4042020-04-29 04:22:39 -07002433 * NewKeyGenerationTest.EcdsaDefaultSize
2434 *
David Drysdaledf09e542021-06-08 15:46:11 +01002435 * Verifies that failing to specify a curve for EC key generation returns
David Drysdale84b685a2023-08-09 07:00:34 +01002436 * UNSUPPORTED_KEY_SIZE or UNSUPPORTED_EC_CURVE.
Selene Huang31ab4042020-04-29 04:22:39 -07002437 */
2438TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
David Drysdale84b685a2023-08-09 07:00:34 +01002439 auto result = GenerateKey(AuthorizationSetBuilder()
2440 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2441 .SigningKey()
2442 .Digest(Digest::NONE)
2443 .SetDefaultValidity());
2444 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2445 result == ErrorCode::UNSUPPORTED_EC_CURVE)
2446 << "unexpected result " << result;
Selene Huang31ab4042020-04-29 04:22:39 -07002447}
2448
2449/*
David Drysdale42fe1892021-10-14 14:43:46 +01002450 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002451 *
David Drysdale42fe1892021-10-14 14:43:46 +01002452 * Verifies that specifying an invalid curve for EC key generation returns
David Drysdale84b685a2023-08-09 07:00:34 +01002453 * UNSUPPORTED_KEY_SIZE or UNSUPPORTED_EC_CURVE.
Selene Huang31ab4042020-04-29 04:22:39 -07002454 */
David Drysdale42fe1892021-10-14 14:43:46 +01002455TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002456 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002457 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002458 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002459 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002460 auto result = GenerateKey(AuthorizationSetBuilder()
2461 .EcdsaSigningKey(curve)
2462 .Digest(Digest::NONE)
2463 .SetDefaultValidity(),
2464 &key_blob, &key_characteristics);
2465 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
David Drysdale84b685a2023-08-09 07:00:34 +01002466 result == ErrorCode::UNSUPPORTED_EC_CURVE)
2467 << "unexpected result " << result;
Selene Huang31ab4042020-04-29 04:22:39 -07002468 }
2469
David Drysdaledf09e542021-06-08 15:46:11 +01002470 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2471 GenerateKey(AuthorizationSetBuilder()
2472 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2473 .Authorization(TAG_KEY_SIZE, 190)
2474 .SigningKey()
2475 .Digest(Digest::NONE)
2476 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002477}
2478
2479/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002480 * NewKeyGenerationTest.EcdsaMissingCurve
2481 *
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002482 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V3.
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002483 */
2484TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002485 if (AidlVersion() < 3) {
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002486 /*
2487 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2488 * However, this was not checked at the time so we can only be strict about checking this
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002489 * for implementations of KeyMint version 3 and above.
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002490 */
David Drysdale9ed7d2c2023-09-14 15:16:27 +01002491 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v3";
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002492 }
2493 /* If EC_CURVE not provided, generateKey
2494 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2495 */
2496 auto result = GenerateKey(
2497 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2498 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2499 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2500}
2501
2502/*
Selene Huang31ab4042020-04-29 04:22:39 -07002503 * NewKeyGenerationTest.EcdsaMismatchKeySize
2504 *
2505 * Verifies that specifying mismatched key size and curve for EC key generation returns
2506 * INVALID_ARGUMENT.
2507 */
2508TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002509 if (SecLevel() == SecurityLevel::STRONGBOX) {
2510 GTEST_SKIP() << "Test not applicable to StrongBox device";
2511 }
Selene Huang31ab4042020-04-29 04:22:39 -07002512
David Drysdaledf09e542021-06-08 15:46:11 +01002513 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002514 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002515 .Authorization(TAG_KEY_SIZE, 224)
2516 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002517 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002518 .Digest(Digest::NONE)
2519 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002520 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002521}
2522
2523/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002524 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002525 *
2526 * Verifies that keymint does not support any curve designated as unsupported.
2527 */
2528TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2529 Digest digest;
2530 if (SecLevel() == SecurityLevel::STRONGBOX) {
2531 digest = Digest::SHA_2_256;
2532 } else {
2533 digest = Digest::SHA_2_512;
2534 }
2535 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002536 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002537 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2538 .EcdsaSigningKey(curve)
2539 .Digest(digest)
2540 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002541 << "Failed to generate key on curve: " << curve;
2542 CheckedDeleteKey();
2543 }
2544}
2545
2546/*
2547 * NewKeyGenerationTest.Hmac
2548 *
2549 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2550 * characteristics.
2551 */
2552TEST_P(NewKeyGenerationTest, Hmac) {
2553 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002554 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002555 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002556 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002557 constexpr size_t key_size = 128;
2558 ASSERT_EQ(ErrorCode::OK,
2559 GenerateKey(
2560 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2561 TAG_MIN_MAC_LENGTH, 128),
2562 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002563 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang31ab4042020-04-29 04:22:39 -07002564
2565 ASSERT_GT(key_blob.size(), 0U);
2566 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002567 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002568
Shawn Willden7f424372021-01-10 18:06:50 -07002569 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2570 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2571 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2572 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002573 }
2574}
2575
2576/*
Selene Huang4f64c222021-04-13 19:54:36 -07002577 * NewKeyGenerationTest.HmacNoAttestation
2578 *
2579 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2580 * and app id are provided.
2581 */
2582TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2583 auto challenge = "hello";
2584 auto app_id = "foo";
2585
2586 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002587 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002588 vector<uint8_t> key_blob;
2589 vector<KeyCharacteristics> key_characteristics;
2590 constexpr size_t key_size = 128;
2591 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2592 .HmacKey(key_size)
2593 .Digest(digest)
2594 .AttestationChallenge(challenge)
2595 .AttestationApplicationId(app_id)
2596 .Authorization(TAG_MIN_MAC_LENGTH, 128),
Seth Moorec5c52ce2024-04-07 15:26:33 -07002597 /*attest_key=*/std::nullopt, &key_blob,
2598 &key_characteristics, &cert_chain_));
David Drysdale1b9febc2023-06-07 13:43:24 +01002599 KeyBlobDeleter deleter(keymint_, key_blob);
Selene Huang4f64c222021-04-13 19:54:36 -07002600
2601 ASSERT_GT(key_blob.size(), 0U);
2602 ASSERT_EQ(cert_chain_.size(), 0);
2603 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002604 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002605
2606 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2607 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2608 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2609 << "Key size " << key_size << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002610 }
2611}
2612
2613/*
Qi Wud22ec842020-11-26 13:27:53 +08002614 * NewKeyGenerationTest.LimitedUsageHmac
2615 *
2616 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2617 * resulting keys have correct characteristics.
2618 */
2619TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2620 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002621 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002622 vector<uint8_t> key_blob;
2623 vector<KeyCharacteristics> key_characteristics;
2624 constexpr size_t key_size = 128;
2625 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2626 .HmacKey(key_size)
2627 .Digest(digest)
2628 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2629 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2630 &key_blob, &key_characteristics));
David Drysdale1b9febc2023-06-07 13:43:24 +01002631 KeyBlobDeleter deleter(keymint_, key_blob);
Qi Wud22ec842020-11-26 13:27:53 +08002632
2633 ASSERT_GT(key_blob.size(), 0U);
2634 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002635 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002636
2637 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2638 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2639 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2640 << "Key size " << key_size << "missing";
2641
2642 // Check the usage count limit tag appears in the authorizations.
2643 AuthorizationSet auths;
2644 for (auto& entry : key_characteristics) {
2645 auths.push_back(AuthorizationSet(entry.authorizations));
2646 }
2647 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2648 << "key usage count limit " << 1U << " missing";
Qi Wud22ec842020-11-26 13:27:53 +08002649 }
2650}
2651
2652/*
Selene Huang31ab4042020-04-29 04:22:39 -07002653 * NewKeyGenerationTest.HmacCheckKeySizes
2654 *
2655 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2656 */
2657TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2658 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002659 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002660 if (key_size < 64 || key_size % 8 != 0) {
2661 // To keep this test from being very slow, we only test a random fraction of
2662 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2663 // them, we expect to run ~40 of them in each run.
2664 if (key_size % 8 == 0 || random() % 10 == 0) {
2665 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2666 GenerateKey(AuthorizationSetBuilder()
2667 .HmacKey(key_size)
2668 .Digest(Digest::SHA_2_256)
2669 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2670 << "HMAC key size " << key_size << " invalid";
2671 }
2672 } else {
2673 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2674 .HmacKey(key_size)
2675 .Digest(Digest::SHA_2_256)
2676 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2677 << "Failed to generate HMAC key of size " << key_size;
2678 CheckedDeleteKey();
2679 }
2680 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002681 if (SecLevel() == SecurityLevel::STRONGBOX) {
2682 // STRONGBOX devices must not support keys larger than 512 bits.
2683 size_t key_size = 520;
2684 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2685 GenerateKey(AuthorizationSetBuilder()
2686 .HmacKey(key_size)
2687 .Digest(Digest::SHA_2_256)
2688 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2689 << "HMAC key size " << key_size << " unexpectedly valid";
2690 }
Selene Huang31ab4042020-04-29 04:22:39 -07002691}
2692
2693/*
2694 * NewKeyGenerationTest.HmacCheckMinMacLengths
2695 *
2696 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2697 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2698 * specific MAC length that failed, so reproducing a failed run will be easy.
2699 */
2700TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2701 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002702 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002703 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2704 // To keep this test from being very long, we only test a random fraction of
2705 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2706 // we expect to run ~17 of them in each run.
2707 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2708 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2709 GenerateKey(AuthorizationSetBuilder()
2710 .HmacKey(128)
2711 .Digest(Digest::SHA_2_256)
2712 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2713 << "HMAC min mac length " << min_mac_length << " invalid.";
2714 }
2715 } else {
2716 EXPECT_EQ(ErrorCode::OK,
2717 GenerateKey(AuthorizationSetBuilder()
2718 .HmacKey(128)
2719 .Digest(Digest::SHA_2_256)
2720 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2721 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2722 CheckedDeleteKey();
2723 }
2724 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002725
2726 // Minimum MAC length must be no more than 512 bits.
2727 size_t min_mac_length = 520;
2728 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2729 GenerateKey(AuthorizationSetBuilder()
2730 .HmacKey(128)
2731 .Digest(Digest::SHA_2_256)
2732 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2733 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002734}
2735
2736/*
2737 * NewKeyGenerationTest.HmacMultipleDigests
2738 *
2739 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2740 */
2741TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002742 if (SecLevel() == SecurityLevel::STRONGBOX) {
2743 GTEST_SKIP() << "Test not applicable to StrongBox device";
2744 }
Selene Huang31ab4042020-04-29 04:22:39 -07002745
2746 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2747 GenerateKey(AuthorizationSetBuilder()
2748 .HmacKey(128)
2749 .Digest(Digest::SHA1)
2750 .Digest(Digest::SHA_2_256)
2751 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2752}
2753
2754/*
2755 * NewKeyGenerationTest.HmacDigestNone
2756 *
2757 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2758 */
2759TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2760 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2761 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2762 128)));
2763
2764 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2765 GenerateKey(AuthorizationSetBuilder()
2766 .HmacKey(128)
2767 .Digest(Digest::NONE)
2768 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2769}
2770
Selene Huang4f64c222021-04-13 19:54:36 -07002771/*
2772 * NewKeyGenerationTest.AesNoAttestation
2773 *
2774 * Verifies that attestation parameters to AES keys are ignored and generateKey
2775 * will succeed.
2776 */
2777TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2778 auto challenge = "hello";
2779 auto app_id = "foo";
2780
2781 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2782 .Authorization(TAG_NO_AUTH_REQUIRED)
2783 .AesEncryptionKey(128)
2784 .EcbMode()
2785 .Padding(PaddingMode::PKCS7)
2786 .AttestationChallenge(challenge)
Seth Moorec5c52ce2024-04-07 15:26:33 -07002787 .AttestationApplicationId(app_id),
2788 /*attest_key=*/std::nullopt, &key_blob_,
2789 &key_characteristics_, &cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07002790
2791 ASSERT_EQ(cert_chain_.size(), 0);
2792}
2793
2794/*
2795 * NewKeyGenerationTest.TripleDesNoAttestation
2796 *
2797 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2798 * will be successful. No attestation should be generated.
2799 */
2800TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2801 auto challenge = "hello";
2802 auto app_id = "foo";
2803
2804 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2805 .TripleDesEncryptionKey(168)
2806 .BlockMode(BlockMode::ECB)
2807 .Authorization(TAG_NO_AUTH_REQUIRED)
2808 .Padding(PaddingMode::NONE)
2809 .AttestationChallenge(challenge)
Seth Moorec5c52ce2024-04-07 15:26:33 -07002810 .AttestationApplicationId(app_id),
2811 /*attest_key=*/std::nullopt, &key_blob_,
2812 &key_characteristics_, &cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07002813 ASSERT_EQ(cert_chain_.size(), 0);
2814}
2815
Selene Huang31ab4042020-04-29 04:22:39 -07002816INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2817
2818typedef KeyMintAidlTestBase SigningOperationsTest;
2819
2820/*
2821 * SigningOperationsTest.RsaSuccess
2822 *
2823 * Verifies that raw RSA signature operations succeed.
2824 */
2825TEST_P(SigningOperationsTest, RsaSuccess) {
2826 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2827 .RsaSigningKey(2048, 65537)
2828 .Digest(Digest::NONE)
2829 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002830 .Authorization(TAG_NO_AUTH_REQUIRED)
2831 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002832 string message = "12345678901234567890123456789012";
2833 string signature = SignMessage(
2834 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002835 LocalVerifyMessage(message, signature,
2836 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2837}
2838
2839/*
2840 * SigningOperationsTest.RsaAllPaddingsAndDigests
2841 *
2842 * Verifies RSA signature/verification for all padding modes and digests.
2843 */
2844TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2845 auto authorizations = AuthorizationSetBuilder()
2846 .Authorization(TAG_NO_AUTH_REQUIRED)
2847 .RsaSigningKey(2048, 65537)
2848 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2849 .Padding(PaddingMode::NONE)
2850 .Padding(PaddingMode::RSA_PSS)
2851 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2852 .SetDefaultValidity();
2853
2854 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2855
2856 string message(128, 'a');
2857 string corrupt_message(message);
2858 ++corrupt_message[corrupt_message.size() / 2];
2859
2860 for (auto padding :
2861 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2862 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002863 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002864 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2865 // Digesting only makes sense with padding.
2866 continue;
2867 }
2868
2869 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2870 // PSS requires digesting.
2871 continue;
2872 }
2873
2874 string signature =
2875 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2876 LocalVerifyMessage(message, signature,
2877 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2878 }
2879 }
Selene Huang31ab4042020-04-29 04:22:39 -07002880}
2881
2882/*
2883 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2884 *
Shawn Willden7f424372021-01-10 18:06:50 -07002885 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002886 */
2887TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2888 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2889 .Authorization(TAG_NO_AUTH_REQUIRED)
2890 .RsaSigningKey(2048, 65537)
2891 .Digest(Digest::NONE)
2892 .Padding(PaddingMode::NONE)
2893 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002894 .Authorization(TAG_APPLICATION_DATA, "appdata")
2895 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002896
2897 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2898
Selene Huang31ab4042020-04-29 04:22:39 -07002899 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2900 Begin(KeyPurpose::SIGN,
2901 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2902 AbortIfNeeded();
2903 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2904 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2905 .Digest(Digest::NONE)
2906 .Padding(PaddingMode::NONE)
2907 .Authorization(TAG_APPLICATION_ID, "clientid")));
2908 AbortIfNeeded();
2909 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2910 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2911 .Digest(Digest::NONE)
2912 .Padding(PaddingMode::NONE)
2913 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2914 AbortIfNeeded();
2915 EXPECT_EQ(ErrorCode::OK,
2916 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2917 .Digest(Digest::NONE)
2918 .Padding(PaddingMode::NONE)
2919 .Authorization(TAG_APPLICATION_DATA, "appdata")
2920 .Authorization(TAG_APPLICATION_ID, "clientid")));
2921 AbortIfNeeded();
2922}
2923
2924/*
2925 * SigningOperationsTest.RsaPssSha256Success
2926 *
2927 * Verifies that RSA-PSS signature operations succeed.
2928 */
2929TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2930 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2931 .RsaSigningKey(2048, 65537)
2932 .Digest(Digest::SHA_2_256)
2933 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002934 .Authorization(TAG_NO_AUTH_REQUIRED)
2935 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002936 // Use large message, which won't work without digesting.
2937 string message(1024, 'a');
2938 string signature = SignMessage(
2939 message,
2940 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2941}
2942
2943/*
2944 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2945 *
2946 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2947 * supports only unpadded operations.
2948 */
2949TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2950 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2951 .RsaSigningKey(2048, 65537)
2952 .Digest(Digest::NONE)
2953 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002954 .Padding(PaddingMode::NONE)
2955 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002956 string message = "12345678901234567890123456789012";
2957 string signature;
2958
2959 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2960 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2961 .Digest(Digest::NONE)
2962 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2963}
2964
2965/*
2966 * SigningOperationsTest.NoUserConfirmation
2967 *
2968 * Verifies that keymint rejects signing operations for keys with
2969 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2970 * presented.
2971 */
2972TEST_P(SigningOperationsTest, NoUserConfirmation) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002973 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Subrahmanyamance2bebd2023-04-28 23:37:02 +00002974 .RsaSigningKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002975 .Digest(Digest::NONE)
2976 .Padding(PaddingMode::NONE)
2977 .Authorization(TAG_NO_AUTH_REQUIRED)
2978 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2979 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002980
2981 const string message = "12345678901234567890123456789012";
2982 EXPECT_EQ(ErrorCode::OK,
2983 Begin(KeyPurpose::SIGN,
2984 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2985 string signature;
2986 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2987}
2988
2989/*
2990 * SigningOperationsTest.RsaPkcs1Sha256Success
2991 *
2992 * Verifies that digested RSA-PKCS1 signature operations succeed.
2993 */
2994TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2995 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2996 .RsaSigningKey(2048, 65537)
2997 .Digest(Digest::SHA_2_256)
2998 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002999 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3000 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003001 string message(1024, 'a');
3002 string signature = SignMessage(message, AuthorizationSetBuilder()
3003 .Digest(Digest::SHA_2_256)
3004 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3005}
3006
3007/*
3008 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3009 *
3010 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3011 */
3012TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3013 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3014 .RsaSigningKey(2048, 65537)
3015 .Digest(Digest::NONE)
3016 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003017 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3018 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003019 string message(53, 'a');
3020 string signature = SignMessage(message, AuthorizationSetBuilder()
3021 .Digest(Digest::NONE)
3022 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3023}
3024
3025/*
3026 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3027 *
3028 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3029 * given a too-long message.
3030 */
3031TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3032 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3033 .RsaSigningKey(2048, 65537)
3034 .Digest(Digest::NONE)
3035 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003036 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3037 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003038 string message(257, 'a');
3039
3040 EXPECT_EQ(ErrorCode::OK,
3041 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3042 .Digest(Digest::NONE)
3043 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3044 string signature;
3045 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3046}
3047
3048/*
3049 * SigningOperationsTest.RsaPssSha512TooSmallKey
3050 *
3051 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3052 * used with a key that is too small for the message.
3053 *
3054 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3055 * keymint specification requires that salt_size == digest_size, so the message will be
3056 * digest_size * 2 +
3057 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3058 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3059 * for a 1024-bit key.
3060 */
3061TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003062 if (SecLevel() == SecurityLevel::STRONGBOX) {
3063 GTEST_SKIP() << "Test not applicable to StrongBox device";
3064 }
Selene Huang31ab4042020-04-29 04:22:39 -07003065 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3066 .RsaSigningKey(1024, 65537)
3067 .Digest(Digest::SHA_2_512)
3068 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003069 .Padding(PaddingMode::RSA_PSS)
3070 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003071 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3072 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3073 .Digest(Digest::SHA_2_512)
3074 .Padding(PaddingMode::RSA_PSS)));
3075}
3076
3077/*
3078 * SigningOperationsTest.RsaNoPaddingTooLong
3079 *
3080 * Verifies that raw RSA signature operations fail with the correct error code when
3081 * given a too-long message.
3082 */
3083TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3084 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3085 .RsaSigningKey(2048, 65537)
3086 .Digest(Digest::NONE)
3087 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003088 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3089 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003090 // One byte too long
3091 string message(2048 / 8 + 1, 'a');
3092 ASSERT_EQ(ErrorCode::OK,
3093 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3094 .Digest(Digest::NONE)
3095 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3096 string result;
3097 ErrorCode finish_error_code = Finish(message, &result);
3098 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3099 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3100
3101 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3102 message = string(128 * 1024, 'a');
3103 ASSERT_EQ(ErrorCode::OK,
3104 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3105 .Digest(Digest::NONE)
3106 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3107 finish_error_code = Finish(message, &result);
3108 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3109 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3110}
3111
3112/*
3113 * SigningOperationsTest.RsaAbort
3114 *
3115 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3116 * test, but the behavior should be algorithm and purpose-independent.
3117 */
3118TEST_P(SigningOperationsTest, RsaAbort) {
3119 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3120 .RsaSigningKey(2048, 65537)
3121 .Digest(Digest::NONE)
3122 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003123 .Padding(PaddingMode::NONE)
3124 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003125
3126 ASSERT_EQ(ErrorCode::OK,
3127 Begin(KeyPurpose::SIGN,
3128 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3129 EXPECT_EQ(ErrorCode::OK, Abort());
3130
3131 // Another abort should fail
3132 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3133
3134 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003135 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003136}
3137
3138/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003139 * SigningOperationsTest.RsaNonUniqueParams
3140 *
3141 * Verifies that an operation with multiple padding modes is rejected.
3142 */
3143TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3144 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3145 .RsaSigningKey(2048, 65537)
3146 .Digest(Digest::NONE)
3147 .Digest(Digest::SHA1)
3148 .Authorization(TAG_NO_AUTH_REQUIRED)
3149 .Padding(PaddingMode::NONE)
3150 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3151 .SetDefaultValidity()));
3152
3153 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3154 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3155 .Digest(Digest::NONE)
3156 .Padding(PaddingMode::NONE)
3157 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3158
Tommy Chiuc93c4392021-05-11 18:36:50 +08003159 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3160 .Digest(Digest::NONE)
3161 .Digest(Digest::SHA1)
3162 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3163 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003164
3165 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3166 Begin(KeyPurpose::SIGN,
3167 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3168}
3169
3170/*
Selene Huang31ab4042020-04-29 04:22:39 -07003171 * SigningOperationsTest.RsaUnsupportedPadding
3172 *
3173 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3174 * with a padding mode inappropriate for RSA.
3175 */
3176TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3177 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3178 .RsaSigningKey(2048, 65537)
3179 .Authorization(TAG_NO_AUTH_REQUIRED)
3180 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003181 .Padding(PaddingMode::PKCS7)
3182 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003183 ASSERT_EQ(
3184 ErrorCode::UNSUPPORTED_PADDING_MODE,
3185 Begin(KeyPurpose::SIGN,
3186 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003187 CheckedDeleteKey();
3188
3189 ASSERT_EQ(ErrorCode::OK,
3190 GenerateKey(
3191 AuthorizationSetBuilder()
3192 .RsaSigningKey(2048, 65537)
3193 .Authorization(TAG_NO_AUTH_REQUIRED)
3194 .Digest(Digest::SHA_2_256 /* supported digest */)
3195 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3196 .SetDefaultValidity()));
3197 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3198 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3199 .Digest(Digest::SHA_2_256)
3200 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003201}
3202
3203/*
3204 * SigningOperationsTest.RsaPssNoDigest
3205 *
3206 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3207 */
3208TEST_P(SigningOperationsTest, RsaNoDigest) {
3209 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3210 .RsaSigningKey(2048, 65537)
3211 .Authorization(TAG_NO_AUTH_REQUIRED)
3212 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003213 .Padding(PaddingMode::RSA_PSS)
3214 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003215 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3216 Begin(KeyPurpose::SIGN,
3217 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3218
3219 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3220 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3221}
3222
3223/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003224 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003225 *
3226 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3227 * supported in some cases (as validated in other tests), but a mode must be specified.
3228 */
3229TEST_P(SigningOperationsTest, RsaNoPadding) {
3230 // Padding must be specified
3231 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3232 .RsaKey(2048, 65537)
3233 .Authorization(TAG_NO_AUTH_REQUIRED)
3234 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003235 .Digest(Digest::NONE)
3236 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003237 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3238 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3239}
3240
3241/*
3242 * SigningOperationsTest.RsaShortMessage
3243 *
3244 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3245 */
3246TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3247 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3248 .Authorization(TAG_NO_AUTH_REQUIRED)
3249 .RsaSigningKey(2048, 65537)
3250 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003251 .Padding(PaddingMode::NONE)
3252 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003253
3254 // Barely shorter
3255 string message(2048 / 8 - 1, 'a');
3256 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3257
3258 // Much shorter
3259 message = "a";
3260 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3261}
3262
3263/*
3264 * SigningOperationsTest.RsaSignWithEncryptionKey
3265 *
3266 * Verifies that RSA encryption keys cannot be used to sign.
3267 */
3268TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3269 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3270 .Authorization(TAG_NO_AUTH_REQUIRED)
3271 .RsaEncryptionKey(2048, 65537)
3272 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003273 .Padding(PaddingMode::NONE)
3274 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003275 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3276 Begin(KeyPurpose::SIGN,
3277 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3278}
3279
3280/*
3281 * SigningOperationsTest.RsaSignTooLargeMessage
3282 *
3283 * Verifies that attempting a raw signature of a message which is the same length as the key,
3284 * but numerically larger than the public modulus, fails with the correct error.
3285 */
3286TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3287 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3288 .Authorization(TAG_NO_AUTH_REQUIRED)
3289 .RsaSigningKey(2048, 65537)
3290 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003291 .Padding(PaddingMode::NONE)
3292 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003293
3294 // Largest possible message will always be larger than the public modulus.
3295 string message(2048 / 8, static_cast<char>(0xff));
3296 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3297 .Authorization(TAG_NO_AUTH_REQUIRED)
3298 .Digest(Digest::NONE)
3299 .Padding(PaddingMode::NONE)));
3300 string signature;
3301 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3302}
3303
3304/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003305 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3306 *
David Drysdale42fe1892021-10-14 14:43:46 +01003307 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003308 */
3309TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003310 string message = "1234567890";
3311 string corrupt_message = "2234567890";
3312 for (auto curve : ValidCurves()) {
3313 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003314 // Ed25519 only allows Digest::NONE.
3315 auto digests = (curve == EcCurve::CURVE_25519)
3316 ? std::vector<Digest>(1, Digest::NONE)
3317 : ValidDigests(true /* withNone */, false /* withMD5 */);
3318
David Drysdaledf8f52e2021-05-06 08:10:58 +01003319 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3320 .Authorization(TAG_NO_AUTH_REQUIRED)
3321 .EcdsaSigningKey(curve)
3322 .Digest(digests)
3323 .SetDefaultValidity());
3324 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3325 if (error != ErrorCode::OK) {
3326 continue;
3327 }
3328
3329 for (auto digest : digests) {
3330 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3331 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3332 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3333 }
3334
3335 auto rc = DeleteKey();
3336 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3337 }
3338}
3339
3340/*
Selene Huang31ab4042020-04-29 04:22:39 -07003341 * SigningOperationsTest.EcdsaAllCurves
3342 *
David Drysdale42fe1892021-10-14 14:43:46 +01003343 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003344 */
3345TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3346 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003347 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3348 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003349 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3350 .Authorization(TAG_NO_AUTH_REQUIRED)
3351 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003352 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003353 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003354 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3355 if (error != ErrorCode::OK) continue;
3356
3357 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003358 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003359 CheckedDeleteKey();
3360 }
3361}
3362
3363/*
David Drysdale42fe1892021-10-14 14:43:46 +01003364 * SigningOperationsTest.EcdsaCurve25519
3365 *
3366 * Verifies that ECDSA operations succeed with curve25519.
3367 */
3368TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3369 if (!Curve25519Supported()) {
3370 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3371 }
3372
3373 EcCurve curve = EcCurve::CURVE_25519;
3374 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3375 .Authorization(TAG_NO_AUTH_REQUIRED)
3376 .EcdsaSigningKey(curve)
3377 .Digest(Digest::NONE)
3378 .SetDefaultValidity());
3379 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3380
3381 string message(1024, 'a');
3382 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3383 CheckedDeleteKey();
3384}
3385
3386/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003387 * SigningOperationsTest.EcdsaCurve25519MaxSize
3388 *
3389 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3390 */
3391TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3392 if (!Curve25519Supported()) {
3393 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3394 }
3395
3396 EcCurve curve = EcCurve::CURVE_25519;
3397 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3398 .Authorization(TAG_NO_AUTH_REQUIRED)
3399 .EcdsaSigningKey(curve)
3400 .Digest(Digest::NONE)
3401 .SetDefaultValidity());
3402 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3403
3404 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3405
3406 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3407 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3408 string message(msg_size, 'a');
3409
3410 // Attempt to sign via Begin+Finish.
3411 AuthorizationSet out_params;
3412 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3413 EXPECT_TRUE(out_params.empty());
3414 string signature;
3415 auto result = Finish(message, &signature);
3416 EXPECT_EQ(result, ErrorCode::OK);
3417 LocalVerifyMessage(message, signature, params);
3418
3419 // Attempt to sign via Begin+Update+Finish
3420 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3421 EXPECT_TRUE(out_params.empty());
3422 string output;
3423 result = Update(message, &output);
3424 EXPECT_EQ(result, ErrorCode::OK);
3425 EXPECT_EQ(output.size(), 0);
3426 string signature2;
3427 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3428 LocalVerifyMessage(message, signature2, params);
3429 }
3430
3431 CheckedDeleteKey();
3432}
3433
3434/*
3435 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3436 *
3437 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3438 */
3439TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3440 if (!Curve25519Supported()) {
3441 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3442 }
3443
3444 EcCurve curve = EcCurve::CURVE_25519;
3445 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3446 .Authorization(TAG_NO_AUTH_REQUIRED)
3447 .EcdsaSigningKey(curve)
3448 .Digest(Digest::NONE)
3449 .SetDefaultValidity());
3450 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3451
3452 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3453
3454 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3455 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3456 string message(msg_size, 'a');
3457
3458 // Attempt to sign via Begin+Finish.
3459 AuthorizationSet out_params;
3460 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3461 EXPECT_TRUE(out_params.empty());
3462 string signature;
3463 auto result = Finish(message, &signature);
3464 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3465
3466 // Attempt to sign via Begin+Update (but never get to Finish)
3467 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3468 EXPECT_TRUE(out_params.empty());
3469 string output;
3470 result = Update(message, &output);
3471 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3472 }
3473
3474 CheckedDeleteKey();
3475}
3476
3477/*
Selene Huang31ab4042020-04-29 04:22:39 -07003478 * SigningOperationsTest.EcdsaNoDigestHugeData
3479 *
3480 * Verifies that ECDSA operations support very large messages, even without digesting. This
3481 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3482 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3483 * the framework.
3484 */
3485TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3486 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3487 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003488 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003489 .Digest(Digest::NONE)
3490 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003491 string message(1 * 1024, 'a');
3492 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3493}
3494
3495/*
3496 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3497 *
3498 * Verifies that using an EC key requires the correct app ID/data.
3499 */
3500TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3501 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3502 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003503 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003504 .Digest(Digest::NONE)
3505 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003506 .Authorization(TAG_APPLICATION_DATA, "appdata")
3507 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003508
3509 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3510
Selene Huang31ab4042020-04-29 04:22:39 -07003511 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3512 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3513 AbortIfNeeded();
3514 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3515 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3516 .Digest(Digest::NONE)
3517 .Authorization(TAG_APPLICATION_ID, "clientid")));
3518 AbortIfNeeded();
3519 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3520 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3521 .Digest(Digest::NONE)
3522 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3523 AbortIfNeeded();
3524 EXPECT_EQ(ErrorCode::OK,
3525 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3526 .Digest(Digest::NONE)
3527 .Authorization(TAG_APPLICATION_DATA, "appdata")
3528 .Authorization(TAG_APPLICATION_ID, "clientid")));
3529 AbortIfNeeded();
3530}
3531
3532/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003533 * SigningOperationsTest.EcdsaIncompatibleDigest
3534 *
3535 * Verifies that using an EC key requires compatible digest.
3536 */
3537TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3538 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3539 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003540 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003541 .Digest(Digest::NONE)
3542 .Digest(Digest::SHA1)
3543 .SetDefaultValidity()));
3544 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3545 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3546 AbortIfNeeded();
3547}
3548
3549/*
Selene Huang31ab4042020-04-29 04:22:39 -07003550 * SigningOperationsTest.AesEcbSign
3551 *
3552 * Verifies that attempts to use AES keys to sign fail in the correct way.
3553 */
3554TEST_P(SigningOperationsTest, AesEcbSign) {
3555 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3556 .Authorization(TAG_NO_AUTH_REQUIRED)
3557 .SigningKey()
3558 .AesEncryptionKey(128)
3559 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3560
3561 AuthorizationSet out_params;
3562 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3563 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3564 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3565 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3566}
3567
3568/*
3569 * SigningOperationsTest.HmacAllDigests
3570 *
3571 * Verifies that HMAC works with all digests.
3572 */
3573TEST_P(SigningOperationsTest, HmacAllDigests) {
3574 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003575 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003576 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3577 .Authorization(TAG_NO_AUTH_REQUIRED)
3578 .HmacKey(128)
3579 .Digest(digest)
3580 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3581 << "Failed to create HMAC key with digest " << digest;
3582 string message = "12345678901234567890123456789012";
3583 string signature = MacMessage(message, digest, 160);
3584 EXPECT_EQ(160U / 8U, signature.size())
3585 << "Failed to sign with HMAC key with digest " << digest;
3586 CheckedDeleteKey();
3587 }
3588}
3589
3590/*
3591 * SigningOperationsTest.HmacSha256TooLargeMacLength
3592 *
3593 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3594 * digest size.
3595 */
3596TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3597 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3598 .Authorization(TAG_NO_AUTH_REQUIRED)
3599 .HmacKey(128)
3600 .Digest(Digest::SHA_2_256)
3601 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3602 AuthorizationSet output_params;
3603 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3604 AuthorizationSetBuilder()
3605 .Digest(Digest::SHA_2_256)
3606 .Authorization(TAG_MAC_LENGTH, 264),
3607 &output_params));
3608}
3609
3610/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003611 * SigningOperationsTest.HmacSha256InvalidMacLength
3612 *
3613 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3614 * not a multiple of 8.
3615 */
3616TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3617 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3618 .Authorization(TAG_NO_AUTH_REQUIRED)
3619 .HmacKey(128)
3620 .Digest(Digest::SHA_2_256)
3621 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3622 AuthorizationSet output_params;
3623 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3624 AuthorizationSetBuilder()
3625 .Digest(Digest::SHA_2_256)
3626 .Authorization(TAG_MAC_LENGTH, 161),
3627 &output_params));
3628}
3629
3630/*
Selene Huang31ab4042020-04-29 04:22:39 -07003631 * SigningOperationsTest.HmacSha256TooSmallMacLength
3632 *
3633 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3634 * specified minimum MAC length.
3635 */
3636TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3637 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3638 .Authorization(TAG_NO_AUTH_REQUIRED)
3639 .HmacKey(128)
3640 .Digest(Digest::SHA_2_256)
3641 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3642 AuthorizationSet output_params;
3643 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3644 AuthorizationSetBuilder()
3645 .Digest(Digest::SHA_2_256)
3646 .Authorization(TAG_MAC_LENGTH, 120),
3647 &output_params));
3648}
3649
3650/*
3651 * SigningOperationsTest.HmacRfc4231TestCase3
3652 *
3653 * Validates against the test vectors from RFC 4231 test case 3.
3654 */
3655TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3656 string key(20, 0xaa);
3657 string message(50, 0xdd);
3658 uint8_t sha_224_expected[] = {
3659 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3660 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3661 };
3662 uint8_t sha_256_expected[] = {
3663 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3664 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3665 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3666 };
3667 uint8_t sha_384_expected[] = {
3668 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3669 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3670 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3671 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3672 };
3673 uint8_t sha_512_expected[] = {
3674 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3675 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3676 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3677 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3678 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3679 };
3680
3681 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3682 if (SecLevel() != SecurityLevel::STRONGBOX) {
3683 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3684 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3685 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3686 }
3687}
3688
3689/*
3690 * SigningOperationsTest.HmacRfc4231TestCase5
3691 *
3692 * Validates against the test vectors from RFC 4231 test case 5.
3693 */
3694TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3695 string key(20, 0x0c);
3696 string message = "Test With Truncation";
3697
3698 uint8_t sha_224_expected[] = {
3699 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3700 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3701 };
3702 uint8_t sha_256_expected[] = {
3703 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3704 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3705 };
3706 uint8_t sha_384_expected[] = {
3707 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3708 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3709 };
3710 uint8_t sha_512_expected[] = {
3711 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3712 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3713 };
3714
3715 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3716 if (SecLevel() != SecurityLevel::STRONGBOX) {
3717 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3718 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3719 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3720 }
3721}
3722
3723INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3724
3725typedef KeyMintAidlTestBase VerificationOperationsTest;
3726
3727/*
Selene Huang31ab4042020-04-29 04:22:39 -07003728 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3729 *
3730 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3731 */
3732TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3733 string key_material = "HelloThisIsAKey";
3734
3735 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003736 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003737 EXPECT_EQ(ErrorCode::OK,
3738 ImportKey(AuthorizationSetBuilder()
3739 .Authorization(TAG_NO_AUTH_REQUIRED)
3740 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3741 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3742 .Digest(Digest::SHA_2_256)
3743 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3744 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003745 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003746 EXPECT_EQ(ErrorCode::OK,
3747 ImportKey(AuthorizationSetBuilder()
3748 .Authorization(TAG_NO_AUTH_REQUIRED)
3749 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3750 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3751 .Digest(Digest::SHA_2_256)
3752 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3753 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003754 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Selene Huang31ab4042020-04-29 04:22:39 -07003755
3756 string message = "This is a message.";
3757 string signature = SignMessage(
3758 signing_key, message,
3759 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3760
3761 // Signing key should not work.
3762 AuthorizationSet out_params;
3763 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3764 Begin(KeyPurpose::VERIFY, signing_key,
3765 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3766
3767 // Verification key should work.
3768 VerifyMessage(verification_key, message, signature,
3769 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
Selene Huang31ab4042020-04-29 04:22:39 -07003770}
3771
Prashant Patildec9fdc2021-12-08 15:25:47 +00003772/*
3773 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3774 *
3775 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3776 */
3777TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3778 string key_material = "HelloThisIsAKey";
3779
3780 vector<uint8_t> signing_key, verification_key;
3781 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3782 EXPECT_EQ(ErrorCode::OK,
3783 ImportKey(AuthorizationSetBuilder()
3784 .Authorization(TAG_NO_AUTH_REQUIRED)
3785 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3786 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3787 .Digest(Digest::SHA_2_256)
3788 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3789 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003790 KeyBlobDeleter sign_deleter(keymint_, signing_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003791 EXPECT_EQ(ErrorCode::OK,
3792 ImportKey(AuthorizationSetBuilder()
3793 .Authorization(TAG_NO_AUTH_REQUIRED)
3794 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3795 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3796 .Digest(Digest::SHA_2_256)
3797 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3798 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
David Drysdale1b9febc2023-06-07 13:43:24 +01003799 KeyBlobDeleter verify_deleter(keymint_, verification_key);
Prashant Patildec9fdc2021-12-08 15:25:47 +00003800
3801 string message = "This is a message.";
3802 string signature = SignMessage(
3803 signing_key, message,
3804 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3805
3806 AuthorizationSet begin_out_params;
3807 ASSERT_EQ(ErrorCode::OK,
3808 Begin(KeyPurpose::VERIFY, verification_key,
3809 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3810
3811 string corruptMessage = "This is b message."; // Corrupted message
3812 string output;
3813 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3814
3815 ASSERT_EQ(ErrorCode::OK,
3816 Begin(KeyPurpose::VERIFY, verification_key,
3817 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3818
3819 signature[0] += 1; // Corrupt a signature
3820 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
Prashant Patildec9fdc2021-12-08 15:25:47 +00003821}
3822
Selene Huang31ab4042020-04-29 04:22:39 -07003823INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3824
3825typedef KeyMintAidlTestBase ExportKeyTest;
3826
3827/*
3828 * ExportKeyTest.RsaUnsupportedKeyFormat
3829 *
3830 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3831 */
3832// TODO(seleneh) add ExportKey to GenerateKey
3833// check result
3834
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003835class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003836 public:
3837 template <TagType tag_type, Tag tag, typename ValueT>
3838 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3839 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003840 for (auto& entry : key_characteristics_) {
3841 if (entry.securityLevel == SecLevel()) {
3842 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3843 << "Tag " << tag << " with value " << expected
3844 << " not found at security level" << entry.securityLevel;
3845 } else {
3846 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3847 << "Tag " << tag << " found at security level " << entry.securityLevel;
3848 }
Selene Huang31ab4042020-04-29 04:22:39 -07003849 }
3850 }
3851
3852 void CheckOrigin() {
3853 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003854 // Origin isn't a crypto param, but it always lives with them.
3855 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003856 }
3857};
3858
3859/*
3860 * ImportKeyTest.RsaSuccess
3861 *
3862 * Verifies that importing and using an RSA key pair works correctly.
3863 */
3864TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003865 uint32_t key_size;
3866 string key;
3867
3868 if (SecLevel() == SecurityLevel::STRONGBOX) {
3869 key_size = 2048;
3870 key = rsa_2048_key;
3871 } else {
3872 key_size = 1024;
3873 key = rsa_key;
3874 }
3875
Selene Huang31ab4042020-04-29 04:22:39 -07003876 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3877 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003878 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003879 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003880 .Padding(PaddingMode::RSA_PSS)
3881 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003882 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003883
3884 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003885 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003886 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3887 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3888 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3889 CheckOrigin();
3890
3891 string message(1024 / 8, 'a');
3892 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3893 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003894 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003895}
3896
3897/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003898 * ImportKeyTest.RsaSuccessWithoutParams
3899 *
3900 * Verifies that importing and using an RSA key pair without specifying parameters
3901 * works correctly.
3902 */
3903TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3904 uint32_t key_size;
3905 string key;
3906
3907 if (SecLevel() == SecurityLevel::STRONGBOX) {
3908 key_size = 2048;
3909 key = rsa_2048_key;
3910 } else {
3911 key_size = 1024;
3912 key = rsa_key;
3913 }
3914
3915 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3916 .Authorization(TAG_NO_AUTH_REQUIRED)
3917 .SigningKey()
3918 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3919 .Digest(Digest::SHA_2_256)
3920 .Padding(PaddingMode::RSA_PSS)
3921 .SetDefaultValidity(),
3922 KeyFormat::PKCS8, key));
3923
3924 // Key size and public exponent are determined from the imported key material.
3925 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3926 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3927
3928 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3929 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3930 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3931 CheckOrigin();
3932
3933 string message(1024 / 8, 'a');
3934 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3935 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003936 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003937}
3938
3939/*
Selene Huang31ab4042020-04-29 04:22:39 -07003940 * ImportKeyTest.RsaKeySizeMismatch
3941 *
3942 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3943 * correct way.
3944 */
3945TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3946 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3947 ImportKey(AuthorizationSetBuilder()
3948 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3949 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003950 .Padding(PaddingMode::NONE)
3951 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003952 KeyFormat::PKCS8, rsa_key));
3953}
3954
3955/*
3956 * ImportKeyTest.RsaPublicExponentMismatch
3957 *
3958 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3959 * fails in the correct way.
3960 */
3961TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3962 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3963 ImportKey(AuthorizationSetBuilder()
3964 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3965 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003966 .Padding(PaddingMode::NONE)
3967 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003968 KeyFormat::PKCS8, rsa_key));
3969}
3970
3971/*
David Drysdalee60248c2021-10-04 12:54:13 +01003972 * ImportKeyTest.RsaAttestMultiPurposeFail
3973 *
3974 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3975 */
3976TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00003977 if (AidlVersion() < 2) {
3978 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
3979 // with other key purposes. However, this was not checked at the time
3980 // so we can only be strict about checking this for implementations of KeyMint
3981 // version 2 and above.
3982 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
3983 }
David Drysdalee60248c2021-10-04 12:54:13 +01003984 uint32_t key_size = 2048;
3985 string key = rsa_2048_key;
3986
3987 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3988 ImportKey(AuthorizationSetBuilder()
3989 .Authorization(TAG_NO_AUTH_REQUIRED)
3990 .RsaSigningKey(key_size, 65537)
3991 .AttestKey()
3992 .Digest(Digest::SHA_2_256)
3993 .Padding(PaddingMode::RSA_PSS)
3994 .SetDefaultValidity(),
3995 KeyFormat::PKCS8, key));
3996}
3997
3998/*
Selene Huang31ab4042020-04-29 04:22:39 -07003999 * ImportKeyTest.EcdsaSuccess
4000 *
4001 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4002 */
4003TEST_P(ImportKeyTest, EcdsaSuccess) {
4004 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4005 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004006 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004007 .Digest(Digest::SHA_2_256)
4008 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004009 KeyFormat::PKCS8, ec_256_key));
4010
4011 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004012 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4013 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4014
4015 CheckOrigin();
4016
4017 string message(32, 'a');
4018 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4019 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004020 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004021}
4022
4023/*
David Drysdale9b8d75e2023-09-05 15:16:47 +01004024 * ImportKeyTest.EcdsaSuccessCurveNotSpecified
4025 *
4026 * Verifies that importing and using an ECDSA P-256 key pair works correctly
4027 * when the EC_CURVE is not explicitly specified.
4028 */
4029TEST_P(ImportKeyTest, EcdsaSuccessCurveNotSpecified) {
David Drysdale1405dbc2023-11-02 09:26:44 +00004030 if (get_vsr_api_level() < __ANDROID_API_V__) {
David Drysdale9b8d75e2023-09-05 15:16:47 +01004031 /*
David Drysdale1405dbc2023-11-02 09:26:44 +00004032 * The KeyMint spec was previously not clear as to whether EC_CURVE was optional on import
4033 * of EC keys. However, this was not checked at the time so we can only be strict about
4034 * checking this for implementations at VSR-V or later.
David Drysdale9b8d75e2023-09-05 15:16:47 +01004035 */
David Drysdale1405dbc2023-11-02 09:26:44 +00004036 GTEST_SKIP() << "Skipping EC_CURVE on import only strict >= VSR-V";
David Drysdale9b8d75e2023-09-05 15:16:47 +01004037 }
4038
4039 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4040 .Authorization(TAG_NO_AUTH_REQUIRED)
4041 .Authorization(TAG_ALGORITHM, Algorithm::EC)
4042 .SigningKey()
4043 .Digest(Digest::SHA_2_256)
4044 .SetDefaultValidity(),
4045 KeyFormat::PKCS8, ec_256_key));
4046
4047 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4048 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4049 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4050
4051 CheckOrigin();
4052
4053 string message(32, 'a');
4054 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4055 string signature = SignMessage(message, params);
4056 LocalVerifyMessage(message, signature, params);
4057}
4058
4059/*
Selene Huang31ab4042020-04-29 04:22:39 -07004060 * ImportKeyTest.EcdsaP256RFC5915Success
4061 *
4062 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4063 * correctly.
4064 */
4065TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4066 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4067 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004068 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004069 .Digest(Digest::SHA_2_256)
4070 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004071 KeyFormat::PKCS8, ec_256_key_rfc5915));
4072
4073 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004074 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4075 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4076
4077 CheckOrigin();
4078
4079 string message(32, 'a');
4080 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4081 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004082 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004083}
4084
4085/*
4086 * ImportKeyTest.EcdsaP256SEC1Success
4087 *
4088 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4089 */
4090TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4091 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4092 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004093 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004094 .Digest(Digest::SHA_2_256)
4095 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004096 KeyFormat::PKCS8, ec_256_key_sec1));
4097
4098 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004099 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4100 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4101
4102 CheckOrigin();
4103
4104 string message(32, 'a');
4105 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4106 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004107 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004108}
4109
4110/*
4111 * ImportKeyTest.Ecdsa521Success
4112 *
4113 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4114 */
4115TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004116 if (SecLevel() == SecurityLevel::STRONGBOX) {
4117 GTEST_SKIP() << "Test not applicable to StrongBox device";
4118 }
Selene Huang31ab4042020-04-29 04:22:39 -07004119 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4120 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004121 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004122 .Digest(Digest::SHA_2_256)
4123 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004124 KeyFormat::PKCS8, ec_521_key));
4125
4126 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004127 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4128 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4129 CheckOrigin();
4130
4131 string message(32, 'a');
4132 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4133 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004134 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004135}
4136
4137/*
Selene Huang31ab4042020-04-29 04:22:39 -07004138 * ImportKeyTest.EcdsaCurveMismatch
4139 *
4140 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4141 * the correct way.
4142 */
4143TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4144 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4145 ImportKey(AuthorizationSetBuilder()
4146 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004147 .Digest(Digest::NONE)
4148 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004149 KeyFormat::PKCS8, ec_256_key));
4150}
4151
4152/*
David Drysdalee60248c2021-10-04 12:54:13 +01004153 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4154 *
4155 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4156 */
4157TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004158 if (AidlVersion() < 2) {
4159 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4160 // with other key purposes. However, this was not checked at the time
4161 // so we can only be strict about checking this for implementations of KeyMint
4162 // version 2 and above.
4163 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4164 }
David Drysdalee60248c2021-10-04 12:54:13 +01004165 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4166 ImportKey(AuthorizationSetBuilder()
4167 .Authorization(TAG_NO_AUTH_REQUIRED)
4168 .EcdsaSigningKey(EcCurve::P_256)
4169 .AttestKey()
4170 .Digest(Digest::SHA_2_256)
4171 .SetDefaultValidity(),
4172 KeyFormat::PKCS8, ec_256_key));
4173}
4174
4175/*
David Drysdale42fe1892021-10-14 14:43:46 +01004176 * ImportKeyTest.Ed25519RawSuccess
4177 *
4178 * Verifies that importing and using a raw Ed25519 private key works correctly.
4179 */
4180TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4181 if (!Curve25519Supported()) {
4182 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4183 }
4184
4185 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4186 .Authorization(TAG_NO_AUTH_REQUIRED)
4187 .EcdsaSigningKey(EcCurve::CURVE_25519)
4188 .Digest(Digest::NONE)
4189 .SetDefaultValidity(),
4190 KeyFormat::RAW, ed25519_key));
4191 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4192 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4193 CheckOrigin();
4194
4195 // The returned cert should hold the correct public key.
4196 ASSERT_GT(cert_chain_.size(), 0);
4197 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4198 ASSERT_NE(kmKeyCert, nullptr);
4199 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4200 ASSERT_NE(kmPubKey.get(), nullptr);
4201 size_t kmPubKeySize = 32;
4202 uint8_t kmPubKeyData[32];
4203 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4204 ASSERT_EQ(kmPubKeySize, 32);
4205 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4206
4207 string message(32, 'a');
4208 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4209 string signature = SignMessage(message, params);
4210 LocalVerifyMessage(message, signature, params);
4211}
4212
4213/*
4214 * ImportKeyTest.Ed25519Pkcs8Success
4215 *
4216 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4217 */
4218TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4219 if (!Curve25519Supported()) {
4220 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4221 }
4222
4223 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4224 .Authorization(TAG_NO_AUTH_REQUIRED)
4225 .EcdsaSigningKey(EcCurve::CURVE_25519)
4226 .Digest(Digest::NONE)
4227 .SetDefaultValidity(),
4228 KeyFormat::PKCS8, ed25519_pkcs8_key));
4229 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4230 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4231 CheckOrigin();
4232
4233 // The returned cert should hold the correct public key.
4234 ASSERT_GT(cert_chain_.size(), 0);
4235 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4236 ASSERT_NE(kmKeyCert, nullptr);
4237 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4238 ASSERT_NE(kmPubKey.get(), nullptr);
4239 size_t kmPubKeySize = 32;
4240 uint8_t kmPubKeyData[32];
4241 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4242 ASSERT_EQ(kmPubKeySize, 32);
4243 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4244
4245 string message(32, 'a');
4246 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4247 string signature = SignMessage(message, params);
4248 LocalVerifyMessage(message, signature, params);
4249}
4250
4251/*
4252 * ImportKeyTest.Ed25519CurveMismatch
4253 *
4254 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4255 * the correct way.
4256 */
4257TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4258 if (!Curve25519Supported()) {
4259 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4260 }
4261
4262 ASSERT_NE(ErrorCode::OK,
4263 ImportKey(AuthorizationSetBuilder()
4264 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4265 .Digest(Digest::NONE)
4266 .SetDefaultValidity(),
4267 KeyFormat::RAW, ed25519_key));
4268}
4269
4270/*
4271 * ImportKeyTest.Ed25519FormatMismatch
4272 *
4273 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4274 */
4275TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4276 if (!Curve25519Supported()) {
4277 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4278 }
4279
4280 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4281 .EcdsaSigningKey(EcCurve::CURVE_25519)
4282 .Digest(Digest::NONE)
4283 .SetDefaultValidity(),
4284 KeyFormat::PKCS8, ed25519_key));
4285 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4286 .EcdsaSigningKey(EcCurve::CURVE_25519)
4287 .Digest(Digest::NONE)
4288 .SetDefaultValidity(),
4289 KeyFormat::RAW, ed25519_pkcs8_key));
4290}
4291
4292/*
4293 * ImportKeyTest.Ed25519PurposeMismatch
4294 *
4295 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4296 */
4297TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4298 if (!Curve25519Supported()) {
4299 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4300 }
4301
4302 // Can't have both SIGN and ATTEST_KEY
4303 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4304 .EcdsaSigningKey(EcCurve::CURVE_25519)
4305 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4306 .Digest(Digest::NONE)
4307 .SetDefaultValidity(),
4308 KeyFormat::RAW, ed25519_key));
4309 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4310 // PKCS#8 format and so includes an OID).
4311 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4312 .EcdsaKey(EcCurve::CURVE_25519)
4313 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4314 .Digest(Digest::NONE)
4315 .SetDefaultValidity(),
4316 KeyFormat::PKCS8, ed25519_pkcs8_key));
4317}
4318
4319/*
4320 * ImportKeyTest.X25519RawSuccess
4321 *
4322 * Verifies that importing and using a raw X25519 private key works correctly.
4323 */
4324TEST_P(ImportKeyTest, X25519RawSuccess) {
4325 if (!Curve25519Supported()) {
4326 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4327 }
4328
4329 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4330 .Authorization(TAG_NO_AUTH_REQUIRED)
4331 .EcdsaKey(EcCurve::CURVE_25519)
4332 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4333 .SetDefaultValidity(),
4334 KeyFormat::RAW, x25519_key));
4335
4336 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4337 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4338 CheckOrigin();
4339}
4340
4341/*
4342 * ImportKeyTest.X25519Pkcs8Success
4343 *
4344 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4345 */
4346TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4347 if (!Curve25519Supported()) {
4348 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4349 }
4350
4351 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4352 .Authorization(TAG_NO_AUTH_REQUIRED)
4353 .EcdsaKey(EcCurve::CURVE_25519)
4354 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4355 .SetDefaultValidity(),
4356 KeyFormat::PKCS8, x25519_pkcs8_key));
4357
4358 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4359 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4360 CheckOrigin();
4361}
4362
4363/*
4364 * ImportKeyTest.X25519CurveMismatch
4365 *
4366 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4367 * the correct way.
4368 */
4369TEST_P(ImportKeyTest, X25519CurveMismatch) {
4370 if (!Curve25519Supported()) {
4371 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4372 }
4373
4374 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4375 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4376 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4377 .SetDefaultValidity(),
4378 KeyFormat::RAW, x25519_key));
4379}
4380
4381/*
4382 * ImportKeyTest.X25519FormatMismatch
4383 *
4384 * Verifies that importing an X25519 key with an invalid format fails.
4385 */
4386TEST_P(ImportKeyTest, X25519FormatMismatch) {
4387 if (!Curve25519Supported()) {
4388 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4389 }
4390
4391 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4392 .EcdsaKey(EcCurve::CURVE_25519)
4393 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4394 .SetDefaultValidity(),
4395 KeyFormat::PKCS8, x25519_key));
4396 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4397 .EcdsaKey(EcCurve::CURVE_25519)
4398 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4399 .SetDefaultValidity(),
4400 KeyFormat::RAW, x25519_pkcs8_key));
4401}
4402
4403/*
4404 * ImportKeyTest.X25519PurposeMismatch
4405 *
4406 * Verifies that importing an X25519 key pair with an invalid format fails.
4407 */
4408TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4409 if (!Curve25519Supported()) {
4410 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4411 }
4412
4413 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4414 .EcdsaKey(EcCurve::CURVE_25519)
4415 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4416 .SetDefaultValidity(),
4417 KeyFormat::PKCS8, x25519_pkcs8_key));
4418 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4419 .EcdsaSigningKey(EcCurve::CURVE_25519)
4420 .SetDefaultValidity(),
4421 KeyFormat::PKCS8, x25519_pkcs8_key));
4422}
4423
4424/*
Selene Huang31ab4042020-04-29 04:22:39 -07004425 * ImportKeyTest.AesSuccess
4426 *
4427 * Verifies that importing and using an AES key works.
4428 */
4429TEST_P(ImportKeyTest, AesSuccess) {
4430 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4431 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4432 .Authorization(TAG_NO_AUTH_REQUIRED)
4433 .AesEncryptionKey(key.size() * 8)
4434 .EcbMode()
4435 .Padding(PaddingMode::PKCS7),
4436 KeyFormat::RAW, key));
4437
4438 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4439 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4440 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4441 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4442 CheckOrigin();
4443
4444 string message = "Hello World!";
4445 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4446 string ciphertext = EncryptMessage(message, params);
4447 string plaintext = DecryptMessage(ciphertext, params);
4448 EXPECT_EQ(message, plaintext);
4449}
4450
4451/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004452 * ImportKeyTest.AesFailure
4453 *
4454 * Verifies that importing an invalid AES key fails.
4455 */
4456TEST_P(ImportKeyTest, AesFailure) {
4457 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4458 uint32_t bitlen = key.size() * 8;
4459 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004460 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004461 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004462 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004463 .Authorization(TAG_NO_AUTH_REQUIRED)
4464 .AesEncryptionKey(key_size)
4465 .EcbMode()
4466 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004467 KeyFormat::RAW, key);
4468 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004469 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4470 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004471 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004472
4473 // Explicit key size matches that of the provided key, but it's not a valid size.
4474 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4475 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4476 ImportKey(AuthorizationSetBuilder()
4477 .Authorization(TAG_NO_AUTH_REQUIRED)
4478 .AesEncryptionKey(long_key.size() * 8)
4479 .EcbMode()
4480 .Padding(PaddingMode::PKCS7),
4481 KeyFormat::RAW, long_key));
4482 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4483 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4484 ImportKey(AuthorizationSetBuilder()
4485 .Authorization(TAG_NO_AUTH_REQUIRED)
4486 .AesEncryptionKey(short_key.size() * 8)
4487 .EcbMode()
4488 .Padding(PaddingMode::PKCS7),
4489 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004490}
4491
4492/*
4493 * ImportKeyTest.TripleDesSuccess
4494 *
4495 * Verifies that importing and using a 3DES key works.
4496 */
4497TEST_P(ImportKeyTest, TripleDesSuccess) {
4498 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4499 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4500 .Authorization(TAG_NO_AUTH_REQUIRED)
4501 .TripleDesEncryptionKey(168)
4502 .EcbMode()
4503 .Padding(PaddingMode::PKCS7),
4504 KeyFormat::RAW, key));
4505
4506 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4507 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4508 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4509 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4510 CheckOrigin();
4511
4512 string message = "Hello World!";
4513 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4514 string ciphertext = EncryptMessage(message, params);
4515 string plaintext = DecryptMessage(ciphertext, params);
4516 EXPECT_EQ(message, plaintext);
4517}
4518
4519/*
4520 * ImportKeyTest.TripleDesFailure
4521 *
4522 * Verifies that importing an invalid 3DES key fails.
4523 */
4524TEST_P(ImportKeyTest, TripleDesFailure) {
4525 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004526 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004527 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004528 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004529 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004530 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004531 .Authorization(TAG_NO_AUTH_REQUIRED)
4532 .TripleDesEncryptionKey(key_size)
4533 .EcbMode()
4534 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004535 KeyFormat::RAW, key);
4536 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004537 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4538 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004539 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004540 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004541 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004542 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4543 ImportKey(AuthorizationSetBuilder()
4544 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004545 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004546 .EcbMode()
4547 .Padding(PaddingMode::PKCS7),
4548 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004549 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004550 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4551 ImportKey(AuthorizationSetBuilder()
4552 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004553 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004554 .EcbMode()
4555 .Padding(PaddingMode::PKCS7),
4556 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004557}
4558
4559/*
4560 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004561 *
4562 * Verifies that importing and using an HMAC key works.
4563 */
4564TEST_P(ImportKeyTest, HmacKeySuccess) {
4565 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4566 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4567 .Authorization(TAG_NO_AUTH_REQUIRED)
4568 .HmacKey(key.size() * 8)
4569 .Digest(Digest::SHA_2_256)
4570 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4571 KeyFormat::RAW, key));
4572
4573 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4574 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4575 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4576 CheckOrigin();
4577
4578 string message = "Hello World!";
4579 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4580 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4581}
4582
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004583/*
4584 * ImportKeyTest.GetKeyCharacteristics
4585 *
4586 * Verifies that imported keys have the correct characteristics.
4587 */
4588TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4589 vector<uint8_t> key_blob;
4590 vector<KeyCharacteristics> key_characteristics;
4591 auto base_builder = AuthorizationSetBuilder()
4592 .Padding(PaddingMode::NONE)
4593 .Authorization(TAG_NO_AUTH_REQUIRED)
4594 .SetDefaultValidity();
4595 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4596 Algorithm::TRIPLE_DES};
4597 ErrorCode result;
4598 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4599 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4600 for (auto alg : algorithms) {
4601 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4602 AuthorizationSetBuilder builder(base_builder);
4603 switch (alg) {
4604 case Algorithm::RSA:
4605 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4606
4607 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4608 &key_characteristics);
4609 break;
4610 case Algorithm::EC:
4611 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4612 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4613 &key_characteristics);
4614 break;
4615 case Algorithm::HMAC:
4616 builder.HmacKey(128)
4617 .Digest(Digest::SHA_2_256)
4618 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4619 result =
4620 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4621 break;
4622 case Algorithm::AES:
4623 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4624 result =
4625 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4626 break;
4627 case Algorithm::TRIPLE_DES:
4628 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4629 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4630 &key_characteristics);
4631 break;
4632 default:
4633 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4634 continue;
4635 }
4636 ASSERT_EQ(ErrorCode::OK, result);
4637 CheckCharacteristics(key_blob, key_characteristics);
4638 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4639 }
4640}
4641
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004642/*
4643 * ImportKeyTest.RsaOaepMGFDigestSuccess
4644 *
4645 * Include MGF-Digest explicitly in import key authorization list.
4646 * Test should import RSA key with OAEP padding and mgf-digests and verify that imported key
4647 * should have the correct characteristics.
4648 */
4649TEST_P(ImportKeyTest, RsaOaepMGFDigestSuccess) {
Prashant Patil2114dca2023-09-21 14:57:10 +00004650 // There was no test to assert that MGF1 digest was present in generated/imported key
4651 // characteristics before Keymint V3, so there are some Keymint implementations where
4652 // this test case fails(b/297306437), hence this test is skipped for Keymint < 3.
4653 if (AidlVersion() < 3) {
4654 GTEST_SKIP() << "Test not applicable to Keymint < V3";
4655 }
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004656 auto mgf_digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4657 size_t key_size = 2048;
4658
4659 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4660 .OaepMGFDigest(mgf_digests)
4661 .Authorization(TAG_NO_AUTH_REQUIRED)
4662 .RsaEncryptionKey(key_size, 65537)
4663 .Digest(Digest::SHA_2_256)
4664 .Padding(PaddingMode::RSA_OAEP)
4665 .SetDefaultValidity(),
4666 KeyFormat::PKCS8, rsa_2048_key));
4667
4668 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4669 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4670 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4671 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4672 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4673 CheckOrigin();
4674
4675 // Make sure explicitly specified mgf-digests exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00004676 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digests, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004677
4678 string message = "Hello";
4679
4680 for (auto digest : mgf_digests) {
4681 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4682 auto params = AuthorizationSetBuilder()
4683 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4684 .Digest(Digest::SHA_2_256)
4685 .Padding(PaddingMode::RSA_OAEP);
4686 string ciphertext1 = LocalRsaEncryptMessage(message, params);
4687 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4688 EXPECT_EQ(key_size / 8, ciphertext1.size());
4689
4690 string ciphertext2 = LocalRsaEncryptMessage(message, params);
4691 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4692 EXPECT_EQ(key_size / 8, ciphertext2.size());
4693
4694 // OAEP randomizes padding so every result should be different (with astronomically high
4695 // probability).
4696 EXPECT_NE(ciphertext1, ciphertext2);
4697
4698 string plaintext1 = DecryptMessage(ciphertext1, params);
4699 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4700 string plaintext2 = DecryptMessage(ciphertext2, params);
4701 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4702
4703 // Decrypting corrupted ciphertext should fail.
4704 size_t offset_to_corrupt = ciphertext1.size() - 1;
4705 char corrupt_byte = ~ciphertext1[offset_to_corrupt];
4706 ciphertext1[offset_to_corrupt] = corrupt_byte;
4707
4708 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4709 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04004710 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004711 EXPECT_EQ(0U, result.size());
4712 }
4713}
4714
4715/*
4716 * ImportKeyTest.RsaOaepMGFDigestDefaultSuccess
4717 *
4718 * Don't specify MGF-Digest explicitly in import key authorization list.
4719 * Test should import RSA key with OAEP padding and default mgf-digest (SHA1) and
4720 * verify that imported key should have the correct characteristics. Default
4721 * mgf-digest shouldn't be included in key charecteristics.
4722 */
4723TEST_P(ImportKeyTest, RsaOaepMGFDigestDefaultSuccess) {
4724 size_t key_size = 2048;
4725 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4726 .Authorization(TAG_NO_AUTH_REQUIRED)
4727 .RsaEncryptionKey(key_size, 65537)
4728 .Digest(Digest::SHA_2_256)
4729 .Padding(PaddingMode::RSA_OAEP)
4730 .SetDefaultValidity(),
4731 KeyFormat::PKCS8, rsa_2048_key));
4732
4733 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4734 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4735 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4736 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4737 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_OAEP);
4738 CheckOrigin();
4739
Prashant Patil2114dca2023-09-21 14:57:10 +00004740 vector defaultDigest = {Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004741 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00004742 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00004743}
4744
Selene Huang31ab4042020-04-29 04:22:39 -07004745INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4746
4747auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004748 // IKeyMintDevice.aidl
4749 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4750 "020100" // INTEGER length 1 value 0x00 (version)
4751 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4752 "934bf94e2aa28a3f83c9f79297250262"
4753 "fbe3276b5a1c91159bbfa3ef8957aac8"
4754 "4b59b30b455a79c2973480823d8b3863"
4755 "c3deef4a8e243590268d80e18751a0e1"
4756 "30f67ce6a1ace9f79b95e097474febc9"
4757 "81195b1d13a69086c0863f66a7b7fdb4"
4758 "8792227b1ac5e2489febdf087ab54864"
4759 "83033a6f001ca5d1ec1e27f5c30f4cec"
4760 "2642074a39ae68aee552e196627a8e3d"
4761 "867e67a8c01b11e75f13cca0a97ab668"
4762 "b50cda07a8ecb7cd8e3dd7009c963653"
4763 "4f6f239cffe1fc8daa466f78b676c711"
4764 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4765 "99b801597d5220e307eaa5bee507fb94"
4766 "d1fa69f9e519b2de315bac92c36f2ea1"
4767 "fa1df4478c0ddedeae8c70e0233cd098"
4768 "040c" // OCTET STRING length 0x0c (initializationVector)
4769 "d796b02c370f1fa4cc0124f1"
4770 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4771 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4772 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4773 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4774 "3106" // SET length 0x06
4775 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4776 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4777 // } end SET
4778 // } end [1]
4779 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4780 "020120" // INTEGER length 1 value 0x20 (AES)
4781 // } end [2]
4782 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4783 "02020100" // INTEGER length 2 value 0x100
4784 // } end [3]
4785 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4786 "3103" // SET length 0x03 {
4787 "020101" // INTEGER length 1 value 0x01 (ECB)
4788 // } end SET
4789 // } end [4]
4790 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4791 "3103" // SET length 0x03 {
4792 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4793 // } end SET
4794 // } end [5]
4795 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4796 // (noAuthRequired)
4797 "0500" // NULL
4798 // } end [503]
4799 // } end SEQUENCE (AuthorizationList)
4800 // } end SEQUENCE (KeyDescription)
4801 "0420" // OCTET STRING length 0x20 (encryptedKey)
4802 "ccd540855f833a5e1480bfd2d36faf3a"
4803 "eee15df5beabe2691bc82dde2a7aa910"
4804 "0410" // OCTET STRING length 0x10 (tag)
4805 "64c9f689c60ff6223ab6e6999e0eb6e5"
4806 // } SEQUENCE (SecureKeyWrapper)
4807);
Selene Huang31ab4042020-04-29 04:22:39 -07004808
4809auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004810 // IKeyMintDevice.aidl
4811 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4812 "020100" // INTEGER length 1 value 0x00 (version)
4813 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4814 "aad93ed5924f283b4bb5526fbe7a1412"
4815 "f9d9749ec30db9062b29e574a8546f33"
4816 "c88732452f5b8e6a391ee76c39ed1712"
4817 "c61d8df6213dec1cffbc17a8c6d04c7b"
4818 "30893d8daa9b2015213e219468215532"
4819 "07f8f9931c4caba23ed3bee28b36947e"
4820 "47f10e0a5c3dc51c988a628daad3e5e1"
4821 "f4005e79c2d5a96c284b4b8d7e4948f3"
4822 "31e5b85dd5a236f85579f3ea1d1b8484"
4823 "87470bdb0ab4f81a12bee42c99fe0df4"
4824 "bee3759453e69ad1d68a809ce06b949f"
4825 "7694a990429b2fe81e066ff43e56a216"
4826 "02db70757922a4bcc23ab89f1e35da77"
4827 "586775f423e519c2ea394caf48a28d0c"
4828 "8020f1dcf6b3a68ec246f615ae96dae9"
4829 "a079b1f6eb959033c1af5c125fd94168"
4830 "040c" // OCTET STRING length 0x0c (initializationVector)
4831 "6d9721d08589581ab49204a3"
4832 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4833 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4834 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4835 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4836 "3106" // SET length 0x06
4837 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4838 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4839 // } end SET
4840 // } end [1]
4841 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4842 "020120" // INTEGER length 1 value 0x20 (AES)
4843 // } end [2]
4844 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4845 "02020100" // INTEGER length 2 value 0x100
4846 // } end [3]
4847 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4848 "3103" // SET length 0x03 {
4849 "020101" // INTEGER length 1 value 0x01 (ECB)
4850 // } end SET
4851 // } end [4]
4852 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4853 "3103" // SET length 0x03 {
4854 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4855 // } end SET
4856 // } end [5]
4857 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4858 // (noAuthRequired)
4859 "0500" // NULL
4860 // } end [503]
4861 // } end SEQUENCE (AuthorizationList)
4862 // } end SEQUENCE (KeyDescription)
4863 "0420" // OCTET STRING length 0x20 (encryptedKey)
4864 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4865 "c20d1f99a9a024a76f35c8e2cab9b68d"
4866 "0410" // OCTET STRING length 0x10 (tag)
4867 "2560c70109ae67c030f00b98b512a670"
4868 // } SEQUENCE (SecureKeyWrapper)
4869);
Selene Huang31ab4042020-04-29 04:22:39 -07004870
4871auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004872 // RFC 5208 s5
4873 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4874 "020100" // INTEGER length 1 value 0x00 (version)
4875 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4876 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4877 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4878 "0500" // NULL (parameters)
4879 // } SEQUENCE (AlgorithmIdentifier)
4880 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4881 // RFC 8017 A.1.2
4882 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4883 "020100" // INTEGER length 1 value 0x00 (version)
4884 "02820101" // INTEGER length 0x0101 (modulus) value...
4885 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4886 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4887 "7b06e673a837313d56b1c725150a3fef" // 0x30
4888 "86acbddc41bb759c2854eae32d35841e" // 0x40
4889 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4890 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4891 "312d7bd5921ffaea1347c157406fef71" // 0x70
4892 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4893 "f4645c11f5c1374c3886427411c44979" // 0x90
4894 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4895 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4896 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4897 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4898 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4899 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4900 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4901 "55" // 0x101
4902 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4903 "02820100" // INTEGER length 0x100 (privateExponent) value...
4904 "431447b6251908112b1ee76f99f3711a" // 0x10
4905 "52b6630960046c2de70de188d833f8b8" // 0x20
4906 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4907 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4908 "e710b630a03adc683b5d2c43080e52be" // 0x50
4909 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4910 "822bccff087d63c940ba8a45f670feb2" // 0x70
4911 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4912 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4913 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4914 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4915 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4916 "52659d5a5ba05b663737a8696281865b" // 0xd0
4917 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4918 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4919 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4920 "028181" // INTEGER length 0x81 (prime1) value...
4921 "00de392e18d682c829266cc3454e1d61" // 0x10
4922 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4923 "ff841be5bac82a164c5970007047b8c5" // 0x30
4924 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4925 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4926 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4927 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4928 "9e91346130748a6e3c124f9149d71c74" // 0x80
4929 "35"
4930 "028181" // INTEGER length 0x81 (prime2) value...
4931 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4932 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4933 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4934 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4935 "9ed39a2d934c880440aed8832f984316" // 0x50
4936 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4937 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4938 "b880677c068e1be936e81288815252a8" // 0x80
4939 "a1"
4940 "028180" // INTEGER length 0x80 (exponent1) value...
4941 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4942 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4943 "5a063212a4f105a3764743e53281988a" // 0x30
4944 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4945 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4946 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4947 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4948 "4719d6e2b9439823719cd08bcd031781" // 0x80
4949 "028181" // INTEGER length 0x81 (exponent2) value...
4950 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4951 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4952 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4953 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4954 "1254186af30b22c10582a8a43e34fe94" // 0x50
4955 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4956 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4957 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4958 "61"
4959 "028181" // INTEGER length 0x81 (coefficient) value...
4960 "00c931617c77829dfb1270502be9195c" // 0x10
4961 "8f2830885f57dba869536811e6864236" // 0x20
4962 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4963 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4964 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4965 "959356210723287b0affcc9f727044d4" // 0x60
4966 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4967 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4968 "22"
4969 // } SEQUENCE
4970 // } SEQUENCE ()
4971);
Selene Huang31ab4042020-04-29 04:22:39 -07004972
4973string zero_masking_key =
4974 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4975string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4976
4977class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4978
4979TEST_P(ImportWrappedKeyTest, Success) {
4980 auto wrapping_key_desc = AuthorizationSetBuilder()
4981 .RsaEncryptionKey(2048, 65537)
4982 .Digest(Digest::SHA_2_256)
4983 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004984 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4985 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004986
4987 ASSERT_EQ(ErrorCode::OK,
4988 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4989 AuthorizationSetBuilder()
4990 .Digest(Digest::SHA_2_256)
4991 .Padding(PaddingMode::RSA_OAEP)));
4992
4993 string message = "Hello World!";
4994 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4995 string ciphertext = EncryptMessage(message, params);
4996 string plaintext = DecryptMessage(ciphertext, params);
4997 EXPECT_EQ(message, plaintext);
4998}
4999
David Drysdaled2cc8c22021-04-15 13:29:45 +01005000/*
5001 * ImportWrappedKeyTest.SuccessSidsIgnored
5002 *
5003 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
5004 * include Tag:USER_SECURE_ID.
5005 */
5006TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
5007 auto wrapping_key_desc = AuthorizationSetBuilder()
5008 .RsaEncryptionKey(2048, 65537)
5009 .Digest(Digest::SHA_2_256)
5010 .Padding(PaddingMode::RSA_OAEP)
5011 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5012 .SetDefaultValidity();
5013
5014 int64_t password_sid = 42;
5015 int64_t biometric_sid = 24;
5016 ASSERT_EQ(ErrorCode::OK,
5017 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5018 AuthorizationSetBuilder()
5019 .Digest(Digest::SHA_2_256)
5020 .Padding(PaddingMode::RSA_OAEP),
5021 password_sid, biometric_sid));
5022
5023 string message = "Hello World!";
5024 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5025 string ciphertext = EncryptMessage(message, params);
5026 string plaintext = DecryptMessage(ciphertext, params);
5027 EXPECT_EQ(message, plaintext);
5028}
5029
Selene Huang31ab4042020-04-29 04:22:39 -07005030TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5031 auto wrapping_key_desc = AuthorizationSetBuilder()
5032 .RsaEncryptionKey(2048, 65537)
5033 .Digest(Digest::SHA_2_256)
5034 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005035 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5036 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005037
5038 ASSERT_EQ(ErrorCode::OK,
5039 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5040 AuthorizationSetBuilder()
5041 .Digest(Digest::SHA_2_256)
5042 .Padding(PaddingMode::RSA_OAEP)));
5043}
5044
5045TEST_P(ImportWrappedKeyTest, WrongMask) {
5046 auto wrapping_key_desc = AuthorizationSetBuilder()
5047 .RsaEncryptionKey(2048, 65537)
5048 .Digest(Digest::SHA_2_256)
5049 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005050 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5051 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005052
5053 ASSERT_EQ(
5054 ErrorCode::VERIFICATION_FAILED,
5055 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5056 AuthorizationSetBuilder()
5057 .Digest(Digest::SHA_2_256)
5058 .Padding(PaddingMode::RSA_OAEP)));
5059}
5060
5061TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5062 auto wrapping_key_desc = AuthorizationSetBuilder()
5063 .RsaEncryptionKey(2048, 65537)
5064 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005065 .Padding(PaddingMode::RSA_OAEP)
5066 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005067
5068 ASSERT_EQ(
5069 ErrorCode::INCOMPATIBLE_PURPOSE,
5070 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5071 AuthorizationSetBuilder()
5072 .Digest(Digest::SHA_2_256)
5073 .Padding(PaddingMode::RSA_OAEP)));
5074}
5075
David Drysdaled2cc8c22021-04-15 13:29:45 +01005076TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5077 auto wrapping_key_desc = AuthorizationSetBuilder()
5078 .RsaEncryptionKey(2048, 65537)
5079 .Digest(Digest::SHA_2_256)
5080 .Padding(PaddingMode::RSA_PSS)
5081 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5082 .SetDefaultValidity();
5083
5084 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5085 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5086 AuthorizationSetBuilder()
5087 .Digest(Digest::SHA_2_256)
5088 .Padding(PaddingMode::RSA_OAEP)));
5089}
5090
5091TEST_P(ImportWrappedKeyTest, WrongDigest) {
5092 auto wrapping_key_desc = AuthorizationSetBuilder()
5093 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005094 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005095 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005096 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5097 .SetDefaultValidity();
5098
5099 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5100 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5101 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005102 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005103 .Padding(PaddingMode::RSA_OAEP)));
5104}
5105
Tri Vob02ff882023-09-29 14:49:20 -04005106auto wrapped_rsa_key = hex2str(
5107 "308206230201000482010060f81b63ae53aa4be2e91b0b7cbdabd108125836139e5b991f3e3c9a98eca6cb7188"
5108 "fba1c1232605747ed118975870c886e583a0ff766fc32b789a17029955caaff39a9c6c439be168e24b51046683"
5109 "ce16110e0df115ccabbadcbe7ea9118b9589e4cccf240b6f0a506dfee57e19738c3cabb7dbf63b43e1b9ab058b"
5110 "41b9480f2797210ef2bfbecb82526ac60ac006ebe0a053e825ad996d0ce8a98dc1ebf6ad889e491e03e9ddcc05"
5111 "63f31921b55a54c61aa7f846d814dfe548f2c7939940bc6cf20489733203732df924b2b2a5aa9b54d31e7e42b9"
5112 "e6cf107182edd33cb8e41db88167a79a264bbf883e69300ac82aac8de9dca0a13900150111efead81b74040c78"
5113 "01d20b1547cfef40de45da30350201013030a1083106020102020103a203020101a30402020800a40531030201"
5114 "01a5053103020104a6053103020103bf8377020500048204c126cd1642e83dea941151d872de12b8aaa835446e"
5115 "94d2c1ea99c030225c5cad125dabe2341d9aba63e4df7fefc51e8e6f623ffae2aab9927113562b674b3cc2d7fc"
5116 "fc34f199151a56ab114e792e6a21bd3b31fbf0d93050b9f90fb8e6cad3a067a4033848c4380184990f19a141d9"
5117 "527177fdc13d802c33d222206c36404518285fe7e631aaeb6072c22c351c8c9db06e0b24e11aecef305f6abefb"
5118 "4f31111534f7c55da8cf0d33882edbb43765304d1d45545c5207a858ea8d4369393bf1c54624df03da86c0ed47"
5119 "b9ce1297149622069d51d2512f656ad0d421e6ff746ce8f79920df6a204c31732414a2f7eb24f8c2950348187a"
5120 "4ba20b88a72355a4ec2b383be9f9b5b9ad564aa4c81de47dd95d77a8156ed0901d005a26f523b2a82c2d25d64d"
5121 "f7660a6d3a720a6ba1eafe71da9fed0265d37a475193525620e705a543a928827accad93aba90556da859808be"
5122 "dc2a8105af252e883892f41679d0600ddefb84415145bc28a2d9b0c60cea1ed3876486950ae0532cc1e953b0b5"
5123 "81314c74250550741b24e4221ebb2804428caa2f08356a7de853ccfc5b18c2179147a883fa5763dd54f0d45388"
5124 "c72f1bea19675d14014a725e125cdfac98d1701d9562be9d75362ea238b93244f46306cee4d77cbb8cbe7bf22d"
5125 "fe677bbb103c00a204e49a0731660a2b23ee73ec7297a17822d4c4468e271029f8f1e8995f1a37cdc38324ead3"
5126 "2474e6ee3ff671803d8a98a870324364d408c4d966d3cf0b9bbcbdbdff34a3e9666705362bc78beb96df4b8964"
5127 "d141022250f62d1433cba5d1f510859eff688e46ce65dea00f5ebcfe7a79081ef1f0f5584dba14b79bc5a5f309"
5128 "a1e48fe2bd9e94fcd9793d9b3632ccc51f18f7453e897e33b729abd2d34be324acbc22dfbf1d089aa93a178f79"
5129 "23344140a468ac120b2f0055c284576b968e1d5148c6879b207b6cdb4eb513bccca619ae12ef156a9df03d6d8c"
5130 "2c1c2ea7109dbcb61e5a74b36d0a7529f38b9ea742a956376da823251a6126693e2e1dab55b643c4e9783db835"
5131 "f64d91069a2de1cda55539da52cadeeba2d3278da9005d89b4de4c5571600823f53d9cab1b55f65a560479d9ee"
5132 "edeb361ab80ccedd0a067ddf5de639d115ffb3acf07fbba1cba6daa524b99db0b785273f7b6c15c4237ce1dce8"
5133 "1b81622f35f116b638c75f0e0b26ba6bd9c5caee60c8b4f9198052b25e8c101638598946cb02c14db0a21b46c6"
5134 "61ea123b2a2b5a51eb059715ce26940c977715a32e288b713013d66d0dae398d546abcd8c80966190b77732a7c"
5135 "e2b8fc83e0cd83f69adef2b24b69fba19c546362087c08c8dab941a8573a084be3407d45a318c9a299f69d79f6"
5136 "fae0859d6f08ee7708cf6041cccd815c3515f792aefc23a624e8e58bd9c6fe2f8f1ca6dcf04c6fdfa23eb3ff74"
5137 "c5e5c7388f9faa32c86b6cd7438774e6cf06cb23a32cddb04c30f7d11e221db306c7937796e70a4dcfb7415c04"
5138 "7823b965bedeaea196dc30fe648c52f3c1bcee62b19d4cccdb740ca35c3f3daad998c99dc117fffb7d150d500f"
5139 "812b60ebec8b2067b13938250d078768e77f898fcdfc5f3554b6eda9df3b42bef38bb4d67cb63b7ede01e93b4d"
5140 "c7768b52aa8ad8fb7fb288a529b84671f1ff9e44bb7c8f05d99806b65eb8e90b530fef3817f9fc4c921d0d46af"
5141 "11aee8252407adc6c54589e9f6e6c1e25fc7510cfe499ea20465610410bf575efdbeb5af763920c3b4cdc8401"
5142 "2");
5143
5144auto wrapped_ec_key = hex2str(
5145 "308201dd020100048201000bb910602f88b1419ada400c8ab7602cf2fdbb4ef5e36881255fd5f85d49c4110c52"
5146 "c75eab5e27a1732c1afa17bfe2cd393dea0a78a77ee08759e984411d1c7f0dbdcb6b77e05556694534be4434d8"
5147 "596a7152aec71481522c85f0cc4635df2875d58dc29a78317b2aedd3586055e6e2227616f6a8ac4b9db5a2ad0e"
5148 "10f5c4b43374bd6c9f57f79a103e64084414cfab3d3e0b7c2f26eb00a62105b7d1c7f41b7292fd6fce9395f39c"
5149 "e0b6da0b5bf0d29d8952b958bd29b47c5ebd20d53ade370f463e35a166c04af71e3d5ce550019d3d20a5544896"
5150 "65d169875d0e6a52348b7ec39b674f818e9b60dfa284d7ae4188471d05b9b2d9a5f750f5a00af999c568040c31"
5151 "4144bde8ada6279d32e61530270201013022a1083106020102020103a203020103a30402020100a50531030201"
5152 "04bf837702050004818a96e0f8be5a263616b506371d3c2ff3a3c2bcffc3ce067b242af66e30d5cd975b9546eb"
5153 "32216d4f083f08fde246ab05fd7e930a0f05701067b44840c01a6722e1b2408be5b6acd0b39a0329cb2f357515"
5154 "876433b193382c0b18aed9ed244dcbef5d61d98ca480f99a6cf2a00efda22eb8750db1725e30f64770ac6862ac"
5155 "44cfd08a2c55812b512a0b92f704105c80b6a23cf339b2b10c677613510b1b");
5156
5157auto wrapping_key_for_asym_keys = hex2str(
5158 "308204bd020100300d06092a864886f70d0101010500048204a7308204a30201000282010100a7f521fe024ebc"
5159 "659db8e7a32b41dba27c5d446cb3d064d594b811d4856c3a583d155b0ff9300df3745738c32c4c4cd15adb6090"
5160 "72ca870364bb7f3485784fde12e598b486c91950b9c45016bcb73c3842747c871be02dfc5f0e4b96d1ff5c8a09"
5161 "7ae77b27e46dc60f1f574d1bb5e97487c1c3f9b493509e07318e1a0f0e9fdae401f4a62a5dd54daa09bf88ef42"
5162 "9923f6f6f55d239908f227676d0f0b618238728dc4babd2a1f7d15fa9827346a1a160ab9427461533006fdf34d"
5163 "4efec9aeefcea80b3a7d4ee4a4550055f0030700c5d20abcc32ce74d90ffabf83e02a759ce9074809936564f3d"
5164 "3039af9c5e8a6afd9aa5459ab35c3eb851f10b3ae88ba91f0203010001028201001885515124451a7c3b6aa366"
5165 "cf09ee66ea81335c2b6461544d42125854a258624988b4a2c05ea3aac77174780a1f9997770c502cc6958ae093"
5166 "f44bbdff3e716a9a97aa93b099eb783da6cb8a8642ba27fc8bc522748f66275239640fc0d8e749bfd891b3093f"
5167 "f046da2e593088bb263a3d17ace4e7d81a0cf83fe3df2a139882bff509523a3f886922200168ddd8fb7b4c9f26"
5168 "62ff941c37937cebbbfeba24dd78d5ccd42025cb0276fa5661965f529274520bbb9faf36c501cafb48e5e47ae0"
5169 "6980334fa36b6c62e2da733a8c7f01067de17e38d32d4a0721a6d184405bceaebb39ed3838633e6fbe43ac8b23"
5170 "337bfe33cdf0b67ac3938ddccc37d775ad150102818100d538885135037730fad28e987d7562c1ef8ca58f95f7"
5171 "ed81cb165ca63e15e810552eb9d487c9b9cde563fb29d1de22a60d54a856385719a4028cf386bcdc88e858d963"
5172 "6d644cea25e0ee54ad1237983d9a06a66ea2f764eb540a4992ba2291ea96d20dfbd98bf5b313322cda4eb6710d"
5173 "020139e085beb8e52a3e69bd05c71c7b02818100c9a7c89b11fcf8d99eb41995b5641472ef972e5aaa1f1446d7"
5174 "ea57a9979e8e64f72ef1cde358649b71be7f21dc19dab52814f9a521d8620bd994a9bb621a8182a250066a0728"
5175 "f0b16ab93a106ed79bc19cd519e83196157a8c6f82b5144a285b9384415394905fe18863b0988b27e77c969a81"
5176 "c34a074e8fef5908fdf3c51ead02818019d5e8c6963ade45640f01523ed96b66fe64b766e7900c0a4f165d9193"
5177 "324a55384d1a1d437ad0f5bed6d78720b3ded4ea069903217e844fd833460acc75986d36ded86a57ddedfd3afd"
5178 "05eb96aa7fdaeeffe148c49c5f711854cac769a068b7d92088ab3c97f5e485eded7b62503ef0898ea679ab1b0a"
5179 "0252950f70e4f35463028181008ff4c027bb8aad17a5cd0a2aaea83854e8a73347340525d38115e0e8c7bd4007"
5180 "e1d1d87ad35e69cbf2423cbdae43a2b70a5b16f0849dd53882663758f6aad763ab7d97669f9fe15bb6456ea706"
5181 "89d2be3fb87d5b1df2f77859c2cd3b79b58ae3fd0640206b813981667d4c3749b7fdf01a0f48ad622e9f2def7e"
5182 "cf0583bd67ad0281805bd8f20cc82cb5e08dc2e7eea977d4180a5ef4c558e01255b8475feb9084475e20328c93"
5183 "5a2247a775c941d64372d01abb27c95ee7d4336b6cbce190808b2f7a8d314d785336397dd6edc0c778f563d37e"
5184 "0057b13695600b92fececc3edb067f69b374f9b9c343220a8b927deb6104768edc72b87751e0a3fb1585e679c9"
5185 "8564");
5186
5187TEST_P(ImportWrappedKeyTest, RsaKey) {
5188 int vsr_api_level = get_vsr_api_level();
5189 if (vsr_api_level < __ANDROID_API_V__) {
5190 /*
5191 * The Keymaster v4 spec introduced `importWrappedKey()` and did not restrict it to
5192 * just symmetric keys. However, the import of asymmetric wrapped keys was not tested
5193 * at the time, so we can only be strict about checking this for implementations claiming
5194 * support for VSR API level 35 and above.
5195 */
5196 GTEST_SKIP() << "Applies only to VSR API level 35, this device is: " << vsr_api_level;
5197 }
5198
5199 auto wrapping_key_desc = AuthorizationSetBuilder()
5200 .RsaEncryptionKey(2048, 65537)
5201 .Digest(Digest::SHA_2_256)
5202 .Padding(PaddingMode::RSA_OAEP)
5203 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5204 .SetDefaultValidity();
5205
5206 ASSERT_EQ(ErrorCode::OK, ImportWrappedKey(wrapped_rsa_key, wrapping_key_for_asym_keys,
5207 wrapping_key_desc, zero_masking_key,
5208 AuthorizationSetBuilder()
5209 .Digest(Digest::SHA_2_256)
5210 .Padding(PaddingMode::RSA_OAEP)));
5211
5212 string message = "Hello World!";
5213 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
5214 string signature = SignMessage(message, params);
5215 LocalVerifyMessage(message, signature, params);
5216}
5217
5218TEST_P(ImportWrappedKeyTest, EcKey) {
5219 int vsr_api_level = get_vsr_api_level();
5220 if (vsr_api_level < __ANDROID_API_V__) {
5221 /*
5222 * The Keymaster v4 spec introduced `importWrappedKey()` and did not restrict it to
5223 * just symmetric keys. However, the import of asymmetric wrapped keys was not tested
5224 * at the time, so we can only be strict about checking this for implementations claiming
5225 * support for VSR API level 35 and above.
5226 */
5227 GTEST_SKIP() << "Applies only to VSR API level 35, this device is: " << vsr_api_level;
5228 }
5229
5230 auto wrapping_key_desc = AuthorizationSetBuilder()
5231 .RsaEncryptionKey(2048, 65537)
5232 .Digest(Digest::SHA_2_256)
5233 .Padding(PaddingMode::RSA_OAEP)
5234 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5235 .SetDefaultValidity();
5236
5237 ASSERT_EQ(ErrorCode::OK, ImportWrappedKey(wrapped_ec_key, wrapping_key_for_asym_keys,
5238 wrapping_key_desc, zero_masking_key,
5239 AuthorizationSetBuilder()
5240 .Digest(Digest::SHA_2_256)
5241 .Padding(PaddingMode::RSA_OAEP)));
5242
5243 string message = "Hello World!";
5244 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
5245 string signature = SignMessage(message, params);
5246 LocalVerifyMessage(message, signature, params);
5247}
5248
Selene Huang31ab4042020-04-29 04:22:39 -07005249INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5250
5251typedef KeyMintAidlTestBase EncryptionOperationsTest;
5252
5253/*
5254 * EncryptionOperationsTest.RsaNoPaddingSuccess
5255 *
David Drysdale59cae642021-05-12 13:52:03 +01005256 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005257 */
5258TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005259 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005260 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005261 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5262 .Authorization(TAG_NO_AUTH_REQUIRED)
5263 .RsaEncryptionKey(2048, exponent)
5264 .Padding(PaddingMode::NONE)
5265 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005266
David Drysdaled2cc8c22021-04-15 13:29:45 +01005267 string message = string(2048 / 8, 'a');
5268 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005269 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005270 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005271
David Drysdale59cae642021-05-12 13:52:03 +01005272 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005273 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005274
David Drysdaled2cc8c22021-04-15 13:29:45 +01005275 // Unpadded RSA is deterministic
5276 EXPECT_EQ(ciphertext1, ciphertext2);
5277
5278 CheckedDeleteKey();
5279 }
Selene Huang31ab4042020-04-29 04:22:39 -07005280}
5281
5282/*
5283 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5284 *
David Drysdale59cae642021-05-12 13:52:03 +01005285 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005286 */
5287TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5288 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5289 .Authorization(TAG_NO_AUTH_REQUIRED)
5290 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005291 .Padding(PaddingMode::NONE)
5292 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005293
5294 string message = "1";
5295 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5296
David Drysdale59cae642021-05-12 13:52:03 +01005297 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005298 EXPECT_EQ(2048U / 8, ciphertext.size());
5299
5300 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5301 string plaintext = DecryptMessage(ciphertext, params);
5302
5303 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005304}
5305
5306/*
Selene Huang31ab4042020-04-29 04:22:39 -07005307 * EncryptionOperationsTest.RsaOaepSuccess
5308 *
David Drysdale59cae642021-05-12 13:52:03 +01005309 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005310 */
5311TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5312 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
Prashant Patil2114dca2023-09-21 14:57:10 +00005313 auto mgf_digest = vector{Digest::SHA1};
Selene Huang31ab4042020-04-29 04:22:39 -07005314
5315 size_t key_size = 2048; // Need largish key for SHA-512 test.
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005316 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5317 .Authorization(TAG_NO_AUTH_REQUIRED)
5318 .RsaEncryptionKey(key_size, 65537)
5319 .Padding(PaddingMode::RSA_OAEP)
5320 .Digest(digests)
Prashant Patil2114dca2023-09-21 14:57:10 +00005321 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005322 .SetDefaultValidity()));
5323
5324 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005325 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Selene Huang31ab4042020-04-29 04:22:39 -07005326
5327 string message = "Hello";
5328
5329 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005330 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5331
5332 auto params = AuthorizationSetBuilder()
5333 .Digest(digest)
5334 .Padding(PaddingMode::RSA_OAEP)
5335 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5336 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005337 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5338 EXPECT_EQ(key_size / 8, ciphertext1.size());
5339
David Drysdale59cae642021-05-12 13:52:03 +01005340 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005341 EXPECT_EQ(key_size / 8, ciphertext2.size());
5342
5343 // OAEP randomizes padding so every result should be different (with astronomically high
5344 // probability).
5345 EXPECT_NE(ciphertext1, ciphertext2);
5346
5347 string plaintext1 = DecryptMessage(ciphertext1, params);
5348 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5349 string plaintext2 = DecryptMessage(ciphertext2, params);
5350 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5351
5352 // Decrypting corrupted ciphertext should fail.
5353 size_t offset_to_corrupt = random() % ciphertext1.size();
5354 char corrupt_byte;
5355 do {
5356 corrupt_byte = static_cast<char>(random() % 256);
5357 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5358 ciphertext1[offset_to_corrupt] = corrupt_byte;
5359
5360 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5361 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005362 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005363 EXPECT_EQ(0U, result.size());
5364 }
5365}
5366
5367/*
5368 * EncryptionOperationsTest.RsaOaepInvalidDigest
5369 *
David Drysdale59cae642021-05-12 13:52:03 +01005370 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005371 * without a digest.
5372 */
5373TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5374 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5375 .Authorization(TAG_NO_AUTH_REQUIRED)
5376 .RsaEncryptionKey(2048, 65537)
5377 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005378 .Digest(Digest::NONE)
5379 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005380
5381 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005382 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005383}
5384
5385/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005386 * EncryptionOperationsTest.RsaOaepInvalidPadding
5387 *
David Drysdale59cae642021-05-12 13:52:03 +01005388 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005389 * with a padding value that is only suitable for signing/verifying.
5390 */
5391TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5392 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5393 .Authorization(TAG_NO_AUTH_REQUIRED)
5394 .RsaEncryptionKey(2048, 65537)
5395 .Padding(PaddingMode::RSA_PSS)
5396 .Digest(Digest::NONE)
5397 .SetDefaultValidity()));
5398
5399 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005400 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005401}
5402
5403/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005404 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005405 *
David Drysdale59cae642021-05-12 13:52:03 +01005406 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005407 * with a different digest than was used to encrypt.
5408 */
5409TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005410 if (SecLevel() == SecurityLevel::STRONGBOX) {
5411 GTEST_SKIP() << "Test not applicable to StrongBox device";
5412 }
Selene Huang31ab4042020-04-29 04:22:39 -07005413
5414 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5415 .Authorization(TAG_NO_AUTH_REQUIRED)
5416 .RsaEncryptionKey(1024, 65537)
5417 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005418 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5419 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005420 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005421 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005422 message,
5423 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5424
5425 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5426 .Digest(Digest::SHA_2_256)
5427 .Padding(PaddingMode::RSA_OAEP)));
5428 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005429 EXPECT_NE(ErrorCode::OK, Finish(ciphertext, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005430 EXPECT_EQ(0U, result.size());
5431}
5432
5433/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005434 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5435 *
David Drysdale59cae642021-05-12 13:52:03 +01005436 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005437 * digests.
5438 */
5439TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5440 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5441
5442 size_t key_size = 2048; // Need largish key for SHA-512 test.
5443 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5444 .OaepMGFDigest(digests)
5445 .Authorization(TAG_NO_AUTH_REQUIRED)
5446 .RsaEncryptionKey(key_size, 65537)
5447 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005448 .Digest(Digest::SHA_2_256)
5449 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005450 if (AidlVersion() >= 3) {
5451 std::vector<Digest> mgf1DigestsInAuths;
5452 mgf1DigestsInAuths.reserve(digests.size());
5453 const auto& hw_auths = SecLevelAuthorizations(key_characteristics_);
5454 std::for_each(hw_auths.begin(), hw_auths.end(), [&](auto& param) {
5455 if (param.tag == Tag::RSA_OAEP_MGF_DIGEST) {
5456 KeyParameterValue value = param.value;
5457 mgf1DigestsInAuths.push_back(param.value.template get<KeyParameterValue::digest>());
5458 }
5459 });
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005460
Prashant Patil2114dca2023-09-21 14:57:10 +00005461 std::sort(digests.begin(), digests.end());
5462 std::sort(mgf1DigestsInAuths.begin(), mgf1DigestsInAuths.end());
5463 EXPECT_EQ(digests, mgf1DigestsInAuths);
5464 }
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005465 string message = "Hello";
5466
5467 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005468 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005469 auto params = AuthorizationSetBuilder()
5470 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5471 .Digest(Digest::SHA_2_256)
5472 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005473 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005474 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5475 EXPECT_EQ(key_size / 8, ciphertext1.size());
5476
David Drysdale59cae642021-05-12 13:52:03 +01005477 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005478 EXPECT_EQ(key_size / 8, ciphertext2.size());
5479
5480 // OAEP randomizes padding so every result should be different (with astronomically high
5481 // probability).
5482 EXPECT_NE(ciphertext1, ciphertext2);
5483
5484 string plaintext1 = DecryptMessage(ciphertext1, params);
5485 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5486 string plaintext2 = DecryptMessage(ciphertext2, params);
5487 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5488
5489 // Decrypting corrupted ciphertext should fail.
5490 size_t offset_to_corrupt = random() % ciphertext1.size();
5491 char corrupt_byte;
5492 do {
5493 corrupt_byte = static_cast<char>(random() % 256);
5494 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5495 ciphertext1[offset_to_corrupt] = corrupt_byte;
5496
5497 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5498 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005499 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005500 EXPECT_EQ(0U, result.size());
5501 }
5502}
5503
5504/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005505 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5506 *
5507 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5508 * specified, defaulting to SHA-1.
5509 */
5510TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5511 size_t key_size = 2048;
5512 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5513 .Authorization(TAG_NO_AUTH_REQUIRED)
5514 .RsaEncryptionKey(key_size, 65537)
5515 .Padding(PaddingMode::RSA_OAEP)
5516 .Digest(Digest::SHA_2_256)
5517 .SetDefaultValidity()));
5518
Prashant Patil2114dca2023-09-21 14:57:10 +00005519 vector defaultDigest = vector{Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005520 // Make sure default mgf-digest (SHA1) is not included in Key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005521 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005522
David Drysdaleae3727b2021-11-11 09:00:14 +00005523 // Do local RSA encryption using the default MGF digest of SHA-1.
5524 string message = "Hello";
5525 auto params =
5526 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5527 string ciphertext = LocalRsaEncryptMessage(message, params);
5528 EXPECT_EQ(key_size / 8, ciphertext.size());
5529
5530 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5531 string plaintext = DecryptMessage(ciphertext, params);
5532 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5533
5534 // Decrypting corrupted ciphertext should fail.
5535 size_t offset_to_corrupt = random() % ciphertext.size();
5536 char corrupt_byte;
5537 do {
5538 corrupt_byte = static_cast<char>(random() % 256);
5539 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5540 ciphertext[offset_to_corrupt] = corrupt_byte;
5541
5542 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5543 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005544 EXPECT_NE(ErrorCode::OK, Finish(ciphertext, &result));
David Drysdaleae3727b2021-11-11 09:00:14 +00005545 EXPECT_EQ(0U, result.size());
5546}
5547
5548/*
5549 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5550 *
5551 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5552 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5553 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5554 */
5555TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5556 size_t key_size = 2048;
Prashant Patil2114dca2023-09-21 14:57:10 +00005557 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005558 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5559 .Authorization(TAG_NO_AUTH_REQUIRED)
Prashant Patil2114dca2023-09-21 14:57:10 +00005560 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005561 .RsaEncryptionKey(key_size, 65537)
5562 .Padding(PaddingMode::RSA_OAEP)
5563 .Digest(Digest::SHA_2_256)
5564 .SetDefaultValidity()));
5565
5566 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005567 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
5568 vector defaultDigest = vector{Digest::SHA1};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005569 // Make sure default mgf-digest is not included in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005570 assert_mgf_digests_present_or_not_in_key_characteristics(defaultDigest, false);
David Drysdaleae3727b2021-11-11 09:00:14 +00005571
5572 // Do local RSA encryption using the default MGF digest of SHA-1.
5573 string message = "Hello";
5574 auto params =
5575 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5576 string ciphertext = LocalRsaEncryptMessage(message, params);
5577 EXPECT_EQ(key_size / 8, ciphertext.size());
5578
5579 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5580 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5581 // is checked against those values, and found absent.
5582 auto result = Begin(KeyPurpose::DECRYPT, params);
5583 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5584 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5585}
5586
5587/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005588 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5589 *
David Drysdale59cae642021-05-12 13:52:03 +01005590 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005591 * with incompatible MGF digest.
5592 */
5593TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
Prashant Patil2114dca2023-09-21 14:57:10 +00005594 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005595 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Prashant Patil2114dca2023-09-21 14:57:10 +00005596 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005597 .Authorization(TAG_NO_AUTH_REQUIRED)
5598 .RsaEncryptionKey(2048, 65537)
5599 .Padding(PaddingMode::RSA_OAEP)
5600 .Digest(Digest::SHA_2_256)
5601 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005602
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005603 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005604 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005605
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005606 string message = "Hello World!";
5607
5608 auto params = AuthorizationSetBuilder()
5609 .Padding(PaddingMode::RSA_OAEP)
5610 .Digest(Digest::SHA_2_256)
5611 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005612 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005613}
5614
5615/*
5616 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5617 *
5618 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5619 * with unsupported MGF digest.
5620 */
5621TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
Prashant Patil2114dca2023-09-21 14:57:10 +00005622 auto mgf_digest = vector{Digest::SHA_2_256};
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005623 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
Prashant Patil2114dca2023-09-21 14:57:10 +00005624 .OaepMGFDigest(mgf_digest)
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005625 .Authorization(TAG_NO_AUTH_REQUIRED)
5626 .RsaEncryptionKey(2048, 65537)
5627 .Padding(PaddingMode::RSA_OAEP)
5628 .Digest(Digest::SHA_2_256)
5629 .SetDefaultValidity()));
Prashant Patil2114dca2023-09-21 14:57:10 +00005630
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005631 // Make sure explicitly specified mgf-digest exist in key characteristics.
Prashant Patil2114dca2023-09-21 14:57:10 +00005632 assert_mgf_digests_present_or_not_in_key_characteristics(mgf_digest, true);
Rajesh Nyamagoud7b9ae3c2023-04-27 00:43:16 +00005633
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005634 string message = "Hello World!";
5635
5636 auto params = AuthorizationSetBuilder()
5637 .Padding(PaddingMode::RSA_OAEP)
5638 .Digest(Digest::SHA_2_256)
5639 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005640 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005641}
5642
5643/*
Selene Huang31ab4042020-04-29 04:22:39 -07005644 * EncryptionOperationsTest.RsaPkcs1Success
5645 *
5646 * Verifies that RSA PKCS encryption/decrypts works.
5647 */
5648TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5649 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5650 .Authorization(TAG_NO_AUTH_REQUIRED)
5651 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005652 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5653 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005654
5655 string message = "Hello World!";
5656 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005657 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005658 EXPECT_EQ(2048U / 8, ciphertext1.size());
5659
David Drysdale59cae642021-05-12 13:52:03 +01005660 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005661 EXPECT_EQ(2048U / 8, ciphertext2.size());
5662
5663 // PKCS1 v1.5 randomizes padding so every result should be different.
5664 EXPECT_NE(ciphertext1, ciphertext2);
5665
5666 string plaintext = DecryptMessage(ciphertext1, params);
5667 EXPECT_EQ(message, plaintext);
5668
5669 // Decrypting corrupted ciphertext should fail.
5670 size_t offset_to_corrupt = random() % ciphertext1.size();
5671 char corrupt_byte;
5672 do {
5673 corrupt_byte = static_cast<char>(random() % 256);
5674 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5675 ciphertext1[offset_to_corrupt] = corrupt_byte;
5676
5677 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5678 string result;
Tri Vo7b565c42023-09-20 19:17:07 -04005679 EXPECT_NE(ErrorCode::OK, Finish(ciphertext1, &result));
Selene Huang31ab4042020-04-29 04:22:39 -07005680 EXPECT_EQ(0U, result.size());
5681}
5682
5683/*
Selene Huang31ab4042020-04-29 04:22:39 -07005684 * EncryptionOperationsTest.EcdsaEncrypt
5685 *
5686 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5687 */
5688TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5689 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5690 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005691 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005692 .Digest(Digest::NONE)
5693 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005694 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5695 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5696 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5697}
5698
5699/*
5700 * EncryptionOperationsTest.HmacEncrypt
5701 *
5702 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5703 */
5704TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5705 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5706 .Authorization(TAG_NO_AUTH_REQUIRED)
5707 .HmacKey(128)
5708 .Digest(Digest::SHA_2_256)
5709 .Padding(PaddingMode::NONE)
5710 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5711 auto params = AuthorizationSetBuilder()
5712 .Digest(Digest::SHA_2_256)
5713 .Padding(PaddingMode::NONE)
5714 .Authorization(TAG_MAC_LENGTH, 128);
5715 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5716 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5717}
5718
5719/*
5720 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5721 *
5722 * Verifies that AES ECB mode works.
5723 */
5724TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5725 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5726 .Authorization(TAG_NO_AUTH_REQUIRED)
5727 .AesEncryptionKey(128)
5728 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5729 .Padding(PaddingMode::NONE)));
5730
5731 ASSERT_GT(key_blob_.size(), 0U);
5732 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5733
5734 // Two-block message.
5735 string message = "12345678901234567890123456789012";
5736 string ciphertext1 = EncryptMessage(message, params);
5737 EXPECT_EQ(message.size(), ciphertext1.size());
5738
5739 string ciphertext2 = EncryptMessage(string(message), params);
5740 EXPECT_EQ(message.size(), ciphertext2.size());
5741
5742 // ECB is deterministic.
5743 EXPECT_EQ(ciphertext1, ciphertext2);
5744
5745 string plaintext = DecryptMessage(ciphertext1, params);
5746 EXPECT_EQ(message, plaintext);
5747}
5748
5749/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005750 * EncryptionOperationsTest.AesEcbUnknownTag
5751 *
5752 * Verifies that AES ECB operations ignore unknown tags.
5753 */
5754TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5755 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5756 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5757 KeyParameter unknown_param;
5758 unknown_param.tag = unknown_tag;
5759
5760 vector<KeyCharacteristics> key_characteristics;
5761 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5762 .Authorization(TAG_NO_AUTH_REQUIRED)
5763 .AesEncryptionKey(128)
5764 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5765 .Padding(PaddingMode::NONE)
5766 .Authorization(unknown_param),
5767 &key_blob_, &key_characteristics));
5768 ASSERT_GT(key_blob_.size(), 0U);
5769
5770 // Unknown tags should not be returned in key characteristics.
5771 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5772 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5773 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5774 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5775
5776 // Encrypt without mentioning the unknown parameter.
5777 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5778 string message = "12345678901234567890123456789012";
5779 string ciphertext = EncryptMessage(message, params);
5780 EXPECT_EQ(message.size(), ciphertext.size());
5781
5782 // Decrypt including the unknown parameter.
5783 auto decrypt_params = AuthorizationSetBuilder()
5784 .BlockMode(BlockMode::ECB)
5785 .Padding(PaddingMode::NONE)
5786 .Authorization(unknown_param);
5787 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5788 EXPECT_EQ(message, plaintext);
5789}
5790
5791/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005792 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005793 *
5794 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5795 */
5796TEST_P(EncryptionOperationsTest, AesWrongMode) {
5797 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5798 .Authorization(TAG_NO_AUTH_REQUIRED)
5799 .AesEncryptionKey(128)
5800 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5801 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005802 ASSERT_GT(key_blob_.size(), 0U);
5803
Selene Huang31ab4042020-04-29 04:22:39 -07005804 EXPECT_EQ(
5805 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5806 Begin(KeyPurpose::ENCRYPT,
5807 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5808}
5809
5810/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005811 * EncryptionOperationsTest.AesWrongPadding
5812 *
5813 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5814 */
5815TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5816 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5817 .Authorization(TAG_NO_AUTH_REQUIRED)
5818 .AesEncryptionKey(128)
5819 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5820 .Padding(PaddingMode::NONE)));
5821 ASSERT_GT(key_blob_.size(), 0U);
5822
5823 EXPECT_EQ(
5824 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5825 Begin(KeyPurpose::ENCRYPT,
5826 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5827}
5828
5829/*
5830 * EncryptionOperationsTest.AesInvalidParams
5831 *
5832 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5833 */
5834TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5835 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5836 .Authorization(TAG_NO_AUTH_REQUIRED)
5837 .AesEncryptionKey(128)
5838 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5839 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5840 .Padding(PaddingMode::NONE)
5841 .Padding(PaddingMode::PKCS7)));
5842 ASSERT_GT(key_blob_.size(), 0U);
5843
5844 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5845 .BlockMode(BlockMode::CBC)
5846 .BlockMode(BlockMode::ECB)
5847 .Padding(PaddingMode::NONE));
5848 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5849 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5850
5851 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5852 .BlockMode(BlockMode::ECB)
5853 .Padding(PaddingMode::NONE)
5854 .Padding(PaddingMode::PKCS7));
5855 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5856 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5857}
5858
5859/*
Selene Huang31ab4042020-04-29 04:22:39 -07005860 * EncryptionOperationsTest.AesWrongPurpose
5861 *
5862 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5863 * specified.
5864 */
5865TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5866 auto err = GenerateKey(AuthorizationSetBuilder()
5867 .Authorization(TAG_NO_AUTH_REQUIRED)
5868 .AesKey(128)
5869 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5870 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5871 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5872 .Padding(PaddingMode::NONE));
5873 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5874 ASSERT_GT(key_blob_.size(), 0U);
5875
5876 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5877 .BlockMode(BlockMode::GCM)
5878 .Padding(PaddingMode::NONE)
5879 .Authorization(TAG_MAC_LENGTH, 128));
5880 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5881
5882 CheckedDeleteKey();
5883
5884 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5885 .Authorization(TAG_NO_AUTH_REQUIRED)
5886 .AesKey(128)
5887 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5888 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5889 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5890 .Padding(PaddingMode::NONE)));
5891
5892 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5893 .BlockMode(BlockMode::GCM)
5894 .Padding(PaddingMode::NONE)
5895 .Authorization(TAG_MAC_LENGTH, 128));
5896 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5897}
5898
5899/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005900 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005901 *
5902 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5903 * multiple of the block size and no padding is specified.
5904 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005905TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5906 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005907 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005908 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5909 .Authorization(TAG_NO_AUTH_REQUIRED)
5910 .AesEncryptionKey(128)
5911 .Authorization(TAG_BLOCK_MODE, blockMode)
5912 .Padding(PaddingMode::NONE)));
5913 // Message is slightly shorter than two blocks.
5914 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005915
David Drysdaled2cc8c22021-04-15 13:29:45 +01005916 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5917 AuthorizationSet out_params;
5918 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5919 string ciphertext;
5920 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5921 EXPECT_EQ(0U, ciphertext.size());
5922
5923 CheckedDeleteKey();
5924 }
Selene Huang31ab4042020-04-29 04:22:39 -07005925}
5926
5927/*
5928 * EncryptionOperationsTest.AesEcbPkcs7Padding
5929 *
5930 * Verifies that AES PKCS7 padding works for any message length.
5931 */
5932TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5933 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5934 .Authorization(TAG_NO_AUTH_REQUIRED)
5935 .AesEncryptionKey(128)
5936 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5937 .Padding(PaddingMode::PKCS7)));
5938
5939 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5940
5941 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005942 for (size_t i = 0; i <= 48; i++) {
5943 SCOPED_TRACE(testing::Message() << "i = " << i);
5944 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5945 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005946 string ciphertext = EncryptMessage(message, params);
5947 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5948 string plaintext = DecryptMessage(ciphertext, params);
5949 EXPECT_EQ(message, plaintext);
5950 }
5951}
5952
5953/*
5954 * EncryptionOperationsTest.AesEcbWrongPadding
5955 *
5956 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5957 * specified.
5958 */
5959TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5960 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5961 .Authorization(TAG_NO_AUTH_REQUIRED)
5962 .AesEncryptionKey(128)
5963 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5964 .Padding(PaddingMode::NONE)));
5965
5966 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5967
5968 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005969 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005970 string message(i, 'a');
5971 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5972 }
5973}
5974
5975/*
5976 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5977 *
5978 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5979 */
5980TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5981 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5982 .Authorization(TAG_NO_AUTH_REQUIRED)
5983 .AesEncryptionKey(128)
5984 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5985 .Padding(PaddingMode::PKCS7)));
5986
5987 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5988
5989 string message = "a";
5990 string ciphertext = EncryptMessage(message, params);
5991 EXPECT_EQ(16U, ciphertext.size());
5992 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005993
Seth Moore7a55ae32021-06-23 14:28:11 -07005994 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5995 ++ciphertext[ciphertext.size() / 2];
5996
5997 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5998 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005999 ErrorCode error = Finish(ciphertext, &plaintext);
6000 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07006001 // This is the expected error, we can exit the test now.
6002 return;
6003 } else {
6004 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01006005 ASSERT_EQ(error, ErrorCode::OK)
6006 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07006007 }
6008 }
6009 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006010}
6011
David Drysdaleb8093292022-04-08 12:22:35 +01006012/*
6013 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
6014 *
6015 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
6016 */
6017TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
6018 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6019 .Authorization(TAG_NO_AUTH_REQUIRED)
6020 .AesEncryptionKey(128)
6021 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
6022 .Padding(PaddingMode::PKCS7)));
6023
6024 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6025
6026 string message = "a";
6027 string ciphertext = EncryptMessage(message, params);
6028 EXPECT_EQ(16U, ciphertext.size());
6029 EXPECT_NE(ciphertext, message);
6030
6031 // Shorten the ciphertext.
6032 ciphertext.resize(ciphertext.size() - 1);
6033 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6034 string plaintext;
6035 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
6036}
6037
Selene Huang31ab4042020-04-29 04:22:39 -07006038vector<uint8_t> CopyIv(const AuthorizationSet& set) {
6039 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006040 EXPECT_TRUE(iv);
6041 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07006042}
6043
6044/*
6045 * EncryptionOperationsTest.AesCtrRoundTripSuccess
6046 *
6047 * Verifies that AES CTR mode works.
6048 */
6049TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
6050 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6051 .Authorization(TAG_NO_AUTH_REQUIRED)
6052 .AesEncryptionKey(128)
6053 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6054 .Padding(PaddingMode::NONE)));
6055
6056 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6057
6058 string message = "123";
6059 AuthorizationSet out_params;
6060 string ciphertext1 = EncryptMessage(message, params, &out_params);
6061 vector<uint8_t> iv1 = CopyIv(out_params);
6062 EXPECT_EQ(16U, iv1.size());
6063
6064 EXPECT_EQ(message.size(), ciphertext1.size());
6065
6066 out_params.Clear();
6067 string ciphertext2 = EncryptMessage(message, params, &out_params);
6068 vector<uint8_t> iv2 = CopyIv(out_params);
6069 EXPECT_EQ(16U, iv2.size());
6070
6071 // IVs should be random, so ciphertexts should differ.
6072 EXPECT_NE(ciphertext1, ciphertext2);
6073
6074 auto params_iv1 =
6075 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
6076 auto params_iv2 =
6077 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
6078
6079 string plaintext = DecryptMessage(ciphertext1, params_iv1);
6080 EXPECT_EQ(message, plaintext);
6081 plaintext = DecryptMessage(ciphertext2, params_iv2);
6082 EXPECT_EQ(message, plaintext);
6083
6084 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
6085 plaintext = DecryptMessage(ciphertext1, params_iv2);
6086 EXPECT_NE(message, plaintext);
6087 plaintext = DecryptMessage(ciphertext2, params_iv1);
6088 EXPECT_NE(message, plaintext);
6089}
6090
6091/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306092 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07006093 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306094 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07006095 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306096TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
6097 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
6098}
Selene Huang31ab4042020-04-29 04:22:39 -07006099
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306100/*
6101 * EncryptionOperationsTest.AesCbcIncremental
6102 *
6103 * Verifies that AES works for CBC block mode, when provided data in various size increments.
6104 */
6105TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
6106 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
6107}
Selene Huang31ab4042020-04-29 04:22:39 -07006108
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306109/*
6110 * EncryptionOperationsTest.AesCtrIncremental
6111 *
6112 * Verifies that AES works for CTR block mode, when provided data in various size increments.
6113 */
6114TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
6115 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
6116}
Selene Huang31ab4042020-04-29 04:22:39 -07006117
anil.hiranniah19a4ca12022-03-03 17:39:30 +05306118/*
6119 * EncryptionOperationsTest.AesGcmIncremental
6120 *
6121 * Verifies that AES works for GCM block mode, when provided data in various size increments.
6122 */
6123TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
6124 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07006125}
6126
Prashant Patildd5f7f02022-07-06 18:58:07 +00006127/*
6128 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
6129 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6130 */
6131TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
6132 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
6133 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
6134 string kat_plaintext =
6135 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
6136 "809FFF37081C22EF278F896AB213A2A631");
6137 string kat_ciphertext =
6138 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
6139 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
6140 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6141 kat_ciphertext);
6142}
6143
6144/*
6145 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
6146 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6147 */
6148TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
6149 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
6150 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
6151 string kat_plaintext =
6152 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
6153 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
6154 string kat_ciphertext =
6155 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
6156 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
6157 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6158 kat_plaintext, kat_ciphertext);
6159}
6160
6161/*
6162 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
6163 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6164 */
6165TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
6166 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
6167 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
6168 string kat_plaintext =
6169 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
6170 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
6171 string kat_ciphertext =
6172 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
6173 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
6174 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6175 kat_ciphertext);
6176}
6177
6178/*
6179 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
6180 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6181 */
6182TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
6183 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
6184 string kat_plaintext =
6185 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
6186 "7B6168A9A27BCE554BEA94EF26E6C742A0");
6187 string kat_ciphertext =
6188 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
6189 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
6190 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6191 kat_ciphertext);
6192}
6193
6194/*
6195 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
6196 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6197 */
6198TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
6199 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
6200 string kat_plaintext =
6201 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
6202 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
6203 string kat_ciphertext =
6204 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6205 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6206 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6207 kat_ciphertext);
6208}
6209
6210/*
6211 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6212 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6213 */
6214TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6215 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6216 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6217 string kat_plaintext =
6218 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6219 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6220 string kat_ciphertext =
6221 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6222 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6223 "bdfcc0cba0");
6224
6225 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6226 kat_ciphertext);
6227}
6228
6229/*
6230 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6231 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6232 */
6233TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6234 if (SecLevel() == SecurityLevel::STRONGBOX) {
6235 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6236 }
6237 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6238 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6239 string kat_plaintext =
6240 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6241 "167f2497c994bd496eb80bfb2ba2c9d5af");
6242 string kat_ciphertext =
6243 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6244 "72c134552f3a138e726fbe493b3a839598");
6245 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6246 kat_ciphertext);
6247}
6248
6249/*
6250 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6251 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6252 */
6253TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6254 if (SecLevel() == SecurityLevel::STRONGBOX) {
6255 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6256 }
6257 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6258 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6259 string kat_plaintext =
6260 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6261 "b170");
6262 string kat_ciphertext =
6263 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6264 "4e3884138ff403a41fd99818708ada301c");
6265 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6266 kat_plaintext, kat_ciphertext);
6267}
6268
6269/*
6270 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6271 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6272 */
6273TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6274 if (SecLevel() == SecurityLevel::STRONGBOX) {
6275 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6276 }
6277 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6278 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6279 string kat_plaintext =
6280 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6281 "28091e09cdbbd3b42b");
6282 string kat_ciphertext =
6283 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6284 "2ae0f90f0c19f42b4a");
6285 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6286 kat_ciphertext);
6287}
6288
6289/*
6290 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6291 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6292 */
6293TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6294 if (SecLevel() == SecurityLevel::STRONGBOX) {
6295 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6296 }
6297 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6298 string kat_plaintext =
6299 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6300 "44ab");
6301 string kat_ciphertext =
6302 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6303 "2453");
6304 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6305 kat_ciphertext);
6306}
6307
6308/*
6309 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6310 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6311 */
6312TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6313 if (SecLevel() == SecurityLevel::STRONGBOX) {
6314 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6315 }
6316 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6317 string kat_plaintext =
6318 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6319 "e2c7");
6320 string kat_ciphertext =
6321 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6322 "bb7e3a889dd4a9589098b44acf1056e7aa");
6323 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6324 kat_ciphertext);
6325}
6326
6327/*
6328 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6329 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6330 */
6331TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6332 if (SecLevel() == SecurityLevel::STRONGBOX) {
6333 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6334 }
6335 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6336 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6337 string kat_plaintext =
6338 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6339 "ff52");
6340 string kat_ciphertext =
6341 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6342 "1413ad70fb0e1970669095ad77ebb5974ae8");
6343
6344 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6345 kat_ciphertext);
6346}
6347
6348/*
6349 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6350 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6351 */
6352TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6353 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6354 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6355 string kat_plaintext =
6356 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6357 "494cb53caca353e4b637ba05687be20f8d");
6358 string kat_ciphertext =
6359 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6360 "6047da1e4fd7c4e1cf2656097f75ae8685");
6361 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6362 kat_ciphertext);
6363}
6364
6365/*
6366 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6367 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6368 */
6369TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6370 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6371 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6372 string kat_plaintext =
6373 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6374 "2545a82b73c48078b9dae62261c65909");
6375 string kat_ciphertext =
6376 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6377 "9403a71987b95124073d69f2a3cb95b0ab");
6378 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6379 kat_plaintext, kat_ciphertext);
6380}
6381
6382/*
6383 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6384 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6385 */
6386TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6387 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6388 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6389 string kat_plaintext =
6390 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6391 "1f6db3c884");
6392 string kat_ciphertext =
6393 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6394 "a7be30d4c3");
6395 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6396 kat_ciphertext);
6397}
6398
6399/*
6400 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6401 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6402 */
6403TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6404 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6405 string kat_plaintext =
6406 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6407 "31a476d6806b8116089c6ec50bb543200f");
6408 string kat_ciphertext =
6409 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6410 "c83e377faf246288931136bef2a07c0be4");
6411 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6412 kat_ciphertext);
6413}
6414
6415/*
6416 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6417 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6418 */
6419TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6420 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6421 string kat_plaintext =
6422 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6423 "6f");
6424 string kat_ciphertext =
6425 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6426 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6427 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6428 kat_ciphertext);
6429}
6430
6431/*
6432 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6433 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6434 */
6435TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6436 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6437 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6438 string kat_plaintext =
6439 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6440 "f0");
6441 string kat_ciphertext =
6442 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6443 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6444
6445 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6446 kat_ciphertext);
6447}
6448
Selene Huang31ab4042020-04-29 04:22:39 -07006449struct AesCtrSp80038aTestVector {
6450 const char* key;
6451 const char* nonce;
6452 const char* plaintext;
6453 const char* ciphertext;
6454};
6455
6456// These test vectors are taken from
6457// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6458static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6459 // AES-128
6460 {
6461 "2b7e151628aed2a6abf7158809cf4f3c",
6462 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6463 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6464 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6465 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6466 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6467 },
6468 // AES-192
6469 {
6470 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6471 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6472 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6473 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6474 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6475 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6476 },
6477 // AES-256
6478 {
6479 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6480 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6481 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6482 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6483 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6484 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6485 },
6486};
6487
6488/*
6489 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6490 *
6491 * Verifies AES CTR implementation against SP800-38A test vectors.
6492 */
6493TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6494 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6495 for (size_t i = 0; i < 3; i++) {
6496 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6497 const string key = hex2str(test.key);
6498 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6499 InvalidSizes.end())
6500 continue;
6501 const string nonce = hex2str(test.nonce);
6502 const string plaintext = hex2str(test.plaintext);
6503 const string ciphertext = hex2str(test.ciphertext);
6504 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6505 }
6506}
6507
6508/*
6509 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6510 *
6511 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6512 */
6513TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6514 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6515 .Authorization(TAG_NO_AUTH_REQUIRED)
6516 .AesEncryptionKey(128)
6517 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6518 .Padding(PaddingMode::PKCS7)));
6519 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6520 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6521}
6522
6523/*
6524 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6525 *
6526 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6527 */
6528TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6529 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6530 .Authorization(TAG_NO_AUTH_REQUIRED)
6531 .AesEncryptionKey(128)
6532 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6533 .Authorization(TAG_CALLER_NONCE)
6534 .Padding(PaddingMode::NONE)));
6535
6536 auto params = AuthorizationSetBuilder()
6537 .BlockMode(BlockMode::CTR)
6538 .Padding(PaddingMode::NONE)
6539 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6540 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6541
6542 params = AuthorizationSetBuilder()
6543 .BlockMode(BlockMode::CTR)
6544 .Padding(PaddingMode::NONE)
6545 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6546 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6547
6548 params = AuthorizationSetBuilder()
6549 .BlockMode(BlockMode::CTR)
6550 .Padding(PaddingMode::NONE)
6551 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6552 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6553}
6554
6555/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006556 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006557 *
6558 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6559 */
6560TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6561 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6562 .Authorization(TAG_NO_AUTH_REQUIRED)
6563 .AesEncryptionKey(128)
6564 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6565 .Padding(PaddingMode::NONE)));
6566 // Two-block message.
6567 string message = "12345678901234567890123456789012";
6568 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6569 AuthorizationSet out_params;
6570 string ciphertext1 = EncryptMessage(message, params, &out_params);
6571 vector<uint8_t> iv1 = CopyIv(out_params);
6572 EXPECT_EQ(message.size(), ciphertext1.size());
6573
6574 out_params.Clear();
6575
6576 string ciphertext2 = EncryptMessage(message, params, &out_params);
6577 vector<uint8_t> iv2 = CopyIv(out_params);
6578 EXPECT_EQ(message.size(), ciphertext2.size());
6579
6580 // IVs should be random, so ciphertexts should differ.
6581 EXPECT_NE(ciphertext1, ciphertext2);
6582
6583 params.push_back(TAG_NONCE, iv1);
6584 string plaintext = DecryptMessage(ciphertext1, params);
6585 EXPECT_EQ(message, plaintext);
6586}
6587
6588/*
Tommy Chiuee705692021-09-23 20:09:13 +08006589 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6590 *
6591 * Verifies that keymaster generates correct output on zero-input with
6592 * NonePadding mode
6593 */
6594TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6595 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6596 .Authorization(TAG_NO_AUTH_REQUIRED)
6597 .AesEncryptionKey(128)
6598 .BlockMode(BlockMode::CBC)
6599 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6600
6601 // Zero input message
6602 string message = "";
6603 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006604 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006605 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6606 AuthorizationSet out_params;
6607 string ciphertext1 = EncryptMessage(message, params, &out_params);
6608 vector<uint8_t> iv1 = CopyIv(out_params);
6609 if (padding == PaddingMode::NONE)
6610 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6611 else
6612 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6613
6614 out_params.Clear();
6615
6616 string ciphertext2 = EncryptMessage(message, params, &out_params);
6617 vector<uint8_t> iv2 = CopyIv(out_params);
6618 if (padding == PaddingMode::NONE)
6619 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6620 else
6621 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6622
6623 // IVs should be random
6624 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6625
6626 params.push_back(TAG_NONCE, iv1);
6627 string plaintext = DecryptMessage(ciphertext1, params);
6628 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6629 }
6630}
6631
6632/*
Selene Huang31ab4042020-04-29 04:22:39 -07006633 * EncryptionOperationsTest.AesCallerNonce
6634 *
6635 * Verifies that AES caller-provided nonces work correctly.
6636 */
6637TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6638 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6639 .Authorization(TAG_NO_AUTH_REQUIRED)
6640 .AesEncryptionKey(128)
6641 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6642 .Authorization(TAG_CALLER_NONCE)
6643 .Padding(PaddingMode::NONE)));
6644
6645 string message = "12345678901234567890123456789012";
6646
6647 // Don't specify nonce, should get a random one.
6648 AuthorizationSetBuilder params =
6649 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6650 AuthorizationSet out_params;
6651 string ciphertext = EncryptMessage(message, params, &out_params);
6652 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006653 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006654
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006655 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006656 string plaintext = DecryptMessage(ciphertext, params);
6657 EXPECT_EQ(message, plaintext);
6658
6659 // Now specify a nonce, should also work.
6660 params = AuthorizationSetBuilder()
6661 .BlockMode(BlockMode::CBC)
6662 .Padding(PaddingMode::NONE)
6663 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6664 out_params.Clear();
6665 ciphertext = EncryptMessage(message, params, &out_params);
6666
6667 // Decrypt with correct nonce.
6668 plaintext = DecryptMessage(ciphertext, params);
6669 EXPECT_EQ(message, plaintext);
6670
6671 // Try with wrong nonce.
6672 params = AuthorizationSetBuilder()
6673 .BlockMode(BlockMode::CBC)
6674 .Padding(PaddingMode::NONE)
6675 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6676 plaintext = DecryptMessage(ciphertext, params);
6677 EXPECT_NE(message, plaintext);
6678}
6679
6680/*
6681 * EncryptionOperationsTest.AesCallerNonceProhibited
6682 *
6683 * Verifies that caller-provided nonces are not permitted when not specified in the key
6684 * authorizations.
6685 */
6686TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6687 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6688 .Authorization(TAG_NO_AUTH_REQUIRED)
6689 .AesEncryptionKey(128)
6690 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6691 .Padding(PaddingMode::NONE)));
6692
6693 string message = "12345678901234567890123456789012";
6694
6695 // Don't specify nonce, should get a random one.
6696 AuthorizationSetBuilder params =
6697 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6698 AuthorizationSet out_params;
6699 string ciphertext = EncryptMessage(message, params, &out_params);
6700 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006701 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006702
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006703 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006704 string plaintext = DecryptMessage(ciphertext, params);
6705 EXPECT_EQ(message, plaintext);
6706
6707 // Now specify a nonce, should fail
6708 params = AuthorizationSetBuilder()
6709 .BlockMode(BlockMode::CBC)
6710 .Padding(PaddingMode::NONE)
6711 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6712 out_params.Clear();
6713 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6714}
6715
6716/*
6717 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6718 *
6719 * Verifies that AES GCM mode works.
6720 */
6721TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6722 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6723 .Authorization(TAG_NO_AUTH_REQUIRED)
6724 .AesEncryptionKey(128)
6725 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6726 .Padding(PaddingMode::NONE)
6727 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6728
6729 string aad = "foobar";
6730 string message = "123456789012345678901234567890123456";
6731
6732 auto begin_params = AuthorizationSetBuilder()
6733 .BlockMode(BlockMode::GCM)
6734 .Padding(PaddingMode::NONE)
6735 .Authorization(TAG_MAC_LENGTH, 128);
6736
Selene Huang31ab4042020-04-29 04:22:39 -07006737 // Encrypt
6738 AuthorizationSet begin_out_params;
6739 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6740 << "Begin encrypt";
6741 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006742 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6743 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006744 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6745
6746 // Grab nonce
6747 begin_params.push_back(begin_out_params);
6748
6749 // Decrypt.
6750 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006751 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006752 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006753 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006754 EXPECT_EQ(message.length(), plaintext.length());
6755 EXPECT_EQ(message, plaintext);
6756}
6757
6758/*
6759 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6760 *
6761 * Verifies that AES GCM mode works, even when there's a long delay
6762 * between operations.
6763 */
6764TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6765 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6766 .Authorization(TAG_NO_AUTH_REQUIRED)
6767 .AesEncryptionKey(128)
6768 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6769 .Padding(PaddingMode::NONE)
6770 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6771
6772 string aad = "foobar";
6773 string message = "123456789012345678901234567890123456";
6774
6775 auto begin_params = AuthorizationSetBuilder()
6776 .BlockMode(BlockMode::GCM)
6777 .Padding(PaddingMode::NONE)
6778 .Authorization(TAG_MAC_LENGTH, 128);
6779
Selene Huang31ab4042020-04-29 04:22:39 -07006780 // Encrypt
6781 AuthorizationSet begin_out_params;
6782 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6783 << "Begin encrypt";
6784 string ciphertext;
6785 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006786 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006787 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006788 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006789
6790 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6791
6792 // Grab nonce
6793 begin_params.push_back(begin_out_params);
6794
6795 // Decrypt.
6796 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6797 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006798 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006799 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006800 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006801 sleep(5);
6802 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6803 EXPECT_EQ(message.length(), plaintext.length());
6804 EXPECT_EQ(message, plaintext);
6805}
6806
6807/*
6808 * EncryptionOperationsTest.AesGcmDifferentNonces
6809 *
6810 * Verifies that encrypting the same data with different nonces produces different outputs.
6811 */
6812TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6813 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6814 .Authorization(TAG_NO_AUTH_REQUIRED)
6815 .AesEncryptionKey(128)
6816 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6817 .Padding(PaddingMode::NONE)
6818 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6819 .Authorization(TAG_CALLER_NONCE)));
6820
6821 string aad = "foobar";
6822 string message = "123456789012345678901234567890123456";
6823 string nonce1 = "000000000000";
6824 string nonce2 = "111111111111";
6825 string nonce3 = "222222222222";
6826
6827 string ciphertext1 =
6828 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6829 string ciphertext2 =
6830 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6831 string ciphertext3 =
6832 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6833
6834 ASSERT_NE(ciphertext1, ciphertext2);
6835 ASSERT_NE(ciphertext1, ciphertext3);
6836 ASSERT_NE(ciphertext2, ciphertext3);
6837}
6838
6839/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006840 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6841 *
6842 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6843 */
6844TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6845 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6846 .Authorization(TAG_NO_AUTH_REQUIRED)
6847 .AesEncryptionKey(128)
6848 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6849 .Padding(PaddingMode::NONE)
6850 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6851
6852 string aad = "foobar";
6853 string message = "123456789012345678901234567890123456";
6854
6855 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6856 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6857 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6858
6859 ASSERT_NE(ciphertext1, ciphertext2);
6860 ASSERT_NE(ciphertext1, ciphertext3);
6861 ASSERT_NE(ciphertext2, ciphertext3);
6862}
6863
6864/*
Selene Huang31ab4042020-04-29 04:22:39 -07006865 * EncryptionOperationsTest.AesGcmTooShortTag
6866 *
6867 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6868 */
6869TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6870 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6871 .Authorization(TAG_NO_AUTH_REQUIRED)
6872 .AesEncryptionKey(128)
6873 .BlockMode(BlockMode::GCM)
6874 .Padding(PaddingMode::NONE)
6875 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6876 string message = "123456789012345678901234567890123456";
6877 auto params = AuthorizationSetBuilder()
6878 .BlockMode(BlockMode::GCM)
6879 .Padding(PaddingMode::NONE)
6880 .Authorization(TAG_MAC_LENGTH, 96);
6881
6882 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6883}
6884
6885/*
6886 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6887 *
6888 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6889 */
6890TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6891 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6892 .Authorization(TAG_NO_AUTH_REQUIRED)
6893 .AesEncryptionKey(128)
6894 .BlockMode(BlockMode::GCM)
6895 .Padding(PaddingMode::NONE)
6896 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6897 string aad = "foobar";
6898 string message = "123456789012345678901234567890123456";
6899 auto params = AuthorizationSetBuilder()
6900 .BlockMode(BlockMode::GCM)
6901 .Padding(PaddingMode::NONE)
6902 .Authorization(TAG_MAC_LENGTH, 128);
6903
Selene Huang31ab4042020-04-29 04:22:39 -07006904 // Encrypt
6905 AuthorizationSet begin_out_params;
6906 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6907 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006908 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006909
6910 AuthorizationSet finish_out_params;
6911 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006912 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6913 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006914
6915 params = AuthorizationSetBuilder()
6916 .Authorizations(begin_out_params)
6917 .BlockMode(BlockMode::GCM)
6918 .Padding(PaddingMode::NONE)
6919 .Authorization(TAG_MAC_LENGTH, 96);
6920
6921 // Decrypt.
6922 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6923}
6924
6925/*
6926 * EncryptionOperationsTest.AesGcmCorruptKey
6927 *
6928 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6929 */
6930TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6931 const uint8_t nonce_bytes[] = {
6932 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6933 };
6934 string nonce = make_string(nonce_bytes);
6935 const uint8_t ciphertext_bytes[] = {
6936 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6937 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6938 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6939 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6940 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6941 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6942 };
6943 string ciphertext = make_string(ciphertext_bytes);
6944
6945 auto params = AuthorizationSetBuilder()
6946 .BlockMode(BlockMode::GCM)
6947 .Padding(PaddingMode::NONE)
6948 .Authorization(TAG_MAC_LENGTH, 128)
6949 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6950
6951 auto import_params = AuthorizationSetBuilder()
6952 .Authorization(TAG_NO_AUTH_REQUIRED)
6953 .AesEncryptionKey(128)
6954 .BlockMode(BlockMode::GCM)
6955 .Padding(PaddingMode::NONE)
6956 .Authorization(TAG_CALLER_NONCE)
6957 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6958
6959 // Import correct key and decrypt
6960 const uint8_t key_bytes[] = {
6961 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6962 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6963 };
6964 string key = make_string(key_bytes);
6965 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6966 string plaintext = DecryptMessage(ciphertext, params);
6967 CheckedDeleteKey();
6968
6969 // Corrupt key and attempt to decrypt
6970 key[0] = 0;
6971 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6972 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6973 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6974 CheckedDeleteKey();
6975}
6976
6977/*
6978 * EncryptionOperationsTest.AesGcmAadNoData
6979 *
6980 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6981 * encrypt.
6982 */
6983TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6984 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6985 .Authorization(TAG_NO_AUTH_REQUIRED)
6986 .AesEncryptionKey(128)
6987 .BlockMode(BlockMode::GCM)
6988 .Padding(PaddingMode::NONE)
6989 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6990
6991 string aad = "1234567890123456";
6992 auto params = AuthorizationSetBuilder()
6993 .BlockMode(BlockMode::GCM)
6994 .Padding(PaddingMode::NONE)
6995 .Authorization(TAG_MAC_LENGTH, 128);
6996
Selene Huang31ab4042020-04-29 04:22:39 -07006997 // Encrypt
6998 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006999 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007000 string ciphertext;
7001 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07007002 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
7003 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007004 EXPECT_TRUE(finish_out_params.empty());
7005
7006 // Grab nonce
7007 params.push_back(begin_out_params);
7008
7009 // Decrypt.
7010 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007011 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007012 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007013 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007014
7015 EXPECT_TRUE(finish_out_params.empty());
7016
7017 EXPECT_EQ("", plaintext);
7018}
7019
7020/*
7021 * EncryptionOperationsTest.AesGcmMultiPartAad
7022 *
7023 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
7024 * chunks.
7025 */
7026TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
7027 const size_t tag_bits = 128;
7028 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7029 .Authorization(TAG_NO_AUTH_REQUIRED)
7030 .AesEncryptionKey(128)
7031 .BlockMode(BlockMode::GCM)
7032 .Padding(PaddingMode::NONE)
7033 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7034
7035 string message = "123456789012345678901234567890123456";
7036 auto begin_params = AuthorizationSetBuilder()
7037 .BlockMode(BlockMode::GCM)
7038 .Padding(PaddingMode::NONE)
7039 .Authorization(TAG_MAC_LENGTH, tag_bits);
7040 AuthorizationSet begin_out_params;
7041
David Drysdale7fc26b92022-05-13 09:54:24 +01007042 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007043
7044 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07007045 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
7046 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007047 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007048 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7049 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007050
Selene Huang31ab4042020-04-29 04:22:39 -07007051 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07007052 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07007053
7054 // Grab nonce.
7055 begin_params.push_back(begin_out_params);
7056
7057 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01007058 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007059 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007060 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007061 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007062 EXPECT_EQ(message, plaintext);
7063}
7064
7065/*
7066 * EncryptionOperationsTest.AesGcmAadOutOfOrder
7067 *
7068 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
7069 */
7070TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
7071 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7072 .Authorization(TAG_NO_AUTH_REQUIRED)
7073 .AesEncryptionKey(128)
7074 .BlockMode(BlockMode::GCM)
7075 .Padding(PaddingMode::NONE)
7076 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7077
7078 string message = "123456789012345678901234567890123456";
7079 auto begin_params = AuthorizationSetBuilder()
7080 .BlockMode(BlockMode::GCM)
7081 .Padding(PaddingMode::NONE)
7082 .Authorization(TAG_MAC_LENGTH, 128);
7083 AuthorizationSet begin_out_params;
7084
David Drysdale7fc26b92022-05-13 09:54:24 +01007085 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007086
Shawn Willden92d79c02021-02-19 07:31:55 -07007087 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007088 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007089 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
7090 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007091
David Drysdaled2cc8c22021-04-15 13:29:45 +01007092 // The failure should have already cancelled the operation.
7093 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
7094
Shawn Willden92d79c02021-02-19 07:31:55 -07007095 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07007096}
7097
7098/*
7099 * EncryptionOperationsTest.AesGcmBadAad
7100 *
7101 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
7102 */
7103TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
7104 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7105 .Authorization(TAG_NO_AUTH_REQUIRED)
7106 .AesEncryptionKey(128)
7107 .BlockMode(BlockMode::GCM)
7108 .Padding(PaddingMode::NONE)
7109 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7110
7111 string message = "12345678901234567890123456789012";
7112 auto begin_params = AuthorizationSetBuilder()
7113 .BlockMode(BlockMode::GCM)
7114 .Padding(PaddingMode::NONE)
7115 .Authorization(TAG_MAC_LENGTH, 128);
7116
Selene Huang31ab4042020-04-29 04:22:39 -07007117 // Encrypt
7118 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007119 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007120 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007121 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007122 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007123
7124 // Grab nonce
7125 begin_params.push_back(begin_out_params);
7126
Selene Huang31ab4042020-04-29 04:22:39 -07007127 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007128 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007129 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07007130 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007131 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007132}
7133
7134/*
7135 * EncryptionOperationsTest.AesGcmWrongNonce
7136 *
7137 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
7138 */
7139TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
7140 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7141 .Authorization(TAG_NO_AUTH_REQUIRED)
7142 .AesEncryptionKey(128)
7143 .BlockMode(BlockMode::GCM)
7144 .Padding(PaddingMode::NONE)
7145 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7146
7147 string message = "12345678901234567890123456789012";
7148 auto begin_params = AuthorizationSetBuilder()
7149 .BlockMode(BlockMode::GCM)
7150 .Padding(PaddingMode::NONE)
7151 .Authorization(TAG_MAC_LENGTH, 128);
7152
Selene Huang31ab4042020-04-29 04:22:39 -07007153 // Encrypt
7154 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007155 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007156 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007157 string ciphertext;
7158 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07007159 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007160
7161 // Wrong nonce
7162 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
7163
7164 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007165 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007166 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07007167 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007168 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007169
7170 // With wrong nonce, should have gotten garbage plaintext (or none).
7171 EXPECT_NE(message, plaintext);
7172}
7173
7174/*
7175 * EncryptionOperationsTest.AesGcmCorruptTag
7176 *
7177 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
7178 */
7179TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
7180 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7181 .Authorization(TAG_NO_AUTH_REQUIRED)
7182 .AesEncryptionKey(128)
7183 .BlockMode(BlockMode::GCM)
7184 .Padding(PaddingMode::NONE)
7185 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7186
7187 string aad = "1234567890123456";
7188 string message = "123456789012345678901234567890123456";
7189
7190 auto params = AuthorizationSetBuilder()
7191 .BlockMode(BlockMode::GCM)
7192 .Padding(PaddingMode::NONE)
7193 .Authorization(TAG_MAC_LENGTH, 128);
7194
Selene Huang31ab4042020-04-29 04:22:39 -07007195 // Encrypt
7196 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007197 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007198 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007199 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007200 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007201
7202 // Corrupt tag
7203 ++(*ciphertext.rbegin());
7204
7205 // Grab nonce
7206 params.push_back(begin_out_params);
7207
7208 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007209 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007210 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007211 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007212 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007213}
7214
7215/*
7216 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7217 *
7218 * Verifies that 3DES is basically functional.
7219 */
7220TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7221 auto auths = AuthorizationSetBuilder()
7222 .TripleDesEncryptionKey(168)
7223 .BlockMode(BlockMode::ECB)
7224 .Authorization(TAG_NO_AUTH_REQUIRED)
7225 .Padding(PaddingMode::NONE);
7226
7227 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7228 // Two-block message.
7229 string message = "1234567890123456";
7230 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7231 string ciphertext1 = EncryptMessage(message, inParams);
7232 EXPECT_EQ(message.size(), ciphertext1.size());
7233
7234 string ciphertext2 = EncryptMessage(string(message), inParams);
7235 EXPECT_EQ(message.size(), ciphertext2.size());
7236
7237 // ECB is deterministic.
7238 EXPECT_EQ(ciphertext1, ciphertext2);
7239
7240 string plaintext = DecryptMessage(ciphertext1, inParams);
7241 EXPECT_EQ(message, plaintext);
7242}
7243
7244/*
7245 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7246 *
7247 * Verifies that CBC keys reject ECB usage.
7248 */
7249TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7250 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7251 .TripleDesEncryptionKey(168)
7252 .BlockMode(BlockMode::CBC)
7253 .Authorization(TAG_NO_AUTH_REQUIRED)
7254 .Padding(PaddingMode::NONE)));
7255
7256 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7257 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7258}
7259
7260/*
7261 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7262 *
7263 * Tests ECB mode with PKCS#7 padding, various message sizes.
7264 */
7265TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7266 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7267 .TripleDesEncryptionKey(168)
7268 .BlockMode(BlockMode::ECB)
7269 .Authorization(TAG_NO_AUTH_REQUIRED)
7270 .Padding(PaddingMode::PKCS7)));
7271
7272 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007273 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007274 string message(i, 'a');
7275 auto inParams =
7276 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7277 string ciphertext = EncryptMessage(message, inParams);
7278 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7279 string plaintext = DecryptMessage(ciphertext, inParams);
7280 EXPECT_EQ(message, plaintext);
7281 }
7282}
7283
7284/*
7285 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7286 *
7287 * Verifies that keys configured for no padding reject PKCS7 padding
7288 */
7289TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7290 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7291 .TripleDesEncryptionKey(168)
7292 .BlockMode(BlockMode::ECB)
7293 .Authorization(TAG_NO_AUTH_REQUIRED)
7294 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007295 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7296 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007297}
7298
7299/*
7300 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7301 *
7302 * Verifies that corrupted padding is detected.
7303 */
7304TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7305 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7306 .TripleDesEncryptionKey(168)
7307 .BlockMode(BlockMode::ECB)
7308 .Authorization(TAG_NO_AUTH_REQUIRED)
7309 .Padding(PaddingMode::PKCS7)));
7310
7311 string message = "a";
7312 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7313 EXPECT_EQ(8U, ciphertext.size());
7314 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007315
7316 AuthorizationSetBuilder begin_params;
7317 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7318 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007319
7320 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7321 ++ciphertext[ciphertext.size() / 2];
7322
David Drysdale7fc26b92022-05-13 09:54:24 +01007323 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007324 string plaintext;
7325 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7326 ErrorCode error = Finish(&plaintext);
7327 if (error == ErrorCode::INVALID_ARGUMENT) {
7328 // This is the expected error, we can exit the test now.
7329 return;
7330 } else {
7331 // Very small chance we got valid decryption, so try again.
7332 ASSERT_EQ(error, ErrorCode::OK);
7333 }
7334 }
7335 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007336}
7337
7338struct TripleDesTestVector {
7339 const char* name;
7340 const KeyPurpose purpose;
7341 const BlockMode block_mode;
7342 const PaddingMode padding_mode;
7343 const char* key;
7344 const char* iv;
7345 const char* input;
7346 const char* output;
7347};
7348
7349// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7350// of the NIST vectors are multiples of the block size.
7351static const TripleDesTestVector kTripleDesTestVectors[] = {
7352 {
7353 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7354 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7355 "", // IV
7356 "329d86bdf1bc5af4", // input
7357 "d946c2756d78633f", // output
7358 },
7359 {
7360 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7361 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7362 "", // IV
7363 "6b1540781b01ce1997adae102dbf3c5b", // input
7364 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7365 },
7366 {
7367 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7368 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7369 "", // IV
7370 "6daad94ce08acfe7", // input
7371 "660e7d32dcc90e79", // output
7372 },
7373 {
7374 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7375 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7376 "", // IV
7377 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7378 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7379 },
7380 {
7381 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7382 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7383 "43f791134c5647ba", // IV
7384 "dcc153cef81d6f24", // input
7385 "92538bd8af18d3ba", // output
7386 },
7387 {
7388 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7389 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7390 "c2e999cb6249023c", // IV
7391 "c689aee38a301bb316da75db36f110b5", // input
7392 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7393 },
7394 {
7395 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7396 PaddingMode::PKCS7,
7397 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7398 "c2e999cb6249023c", // IV
7399 "c689aee38a301bb316da75db36f110b500", // input
7400 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7401 },
7402 {
7403 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7404 PaddingMode::PKCS7,
7405 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7406 "c2e999cb6249023c", // IV
7407 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7408 "c689aee38a301bb316da75db36f110b500", // output
7409 },
7410 {
7411 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7412 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7413 "41746c7e442d3681", // IV
7414 "c53a7b0ec40600fe", // input
7415 "d4f00eb455de1034", // output
7416 },
7417 {
7418 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7419 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7420 "3982bc02c3727d45", // IV
7421 "6006f10adef52991fcc777a1238bbb65", // input
7422 "edae09288e9e3bc05746d872b48e3b29", // output
7423 },
7424};
7425
7426/*
7427 * EncryptionOperationsTest.TripleDesTestVector
7428 *
7429 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7430 */
7431TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7432 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7433 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7434 SCOPED_TRACE(test->name);
7435 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7436 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7437 hex2str(test->output));
7438 }
7439}
7440
7441/*
7442 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7443 *
7444 * Validates CBC mode functionality.
7445 */
7446TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7447 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7448 .TripleDesEncryptionKey(168)
7449 .BlockMode(BlockMode::CBC)
7450 .Authorization(TAG_NO_AUTH_REQUIRED)
7451 .Padding(PaddingMode::NONE)));
7452
7453 ASSERT_GT(key_blob_.size(), 0U);
7454
Brian J Murray734c8412022-01-13 14:55:30 -08007455 // Four-block message.
7456 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007457 vector<uint8_t> iv1;
7458 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7459 EXPECT_EQ(message.size(), ciphertext1.size());
7460
7461 vector<uint8_t> iv2;
7462 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7463 EXPECT_EQ(message.size(), ciphertext2.size());
7464
7465 // IVs should be random, so ciphertexts should differ.
7466 EXPECT_NE(iv1, iv2);
7467 EXPECT_NE(ciphertext1, ciphertext2);
7468
7469 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7470 EXPECT_EQ(message, plaintext);
7471}
7472
7473/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007474 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7475 *
7476 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7477 */
7478TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7479 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7480 .TripleDesEncryptionKey(168)
7481 .BlockMode(BlockMode::CBC)
7482 .Authorization(TAG_NO_AUTH_REQUIRED)
7483 .Authorization(TAG_CALLER_NONCE)
7484 .Padding(PaddingMode::NONE)));
7485 auto params = AuthorizationSetBuilder()
7486 .BlockMode(BlockMode::CBC)
7487 .Padding(PaddingMode::NONE)
7488 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7489 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7490}
7491
7492/*
Selene Huang31ab4042020-04-29 04:22:39 -07007493 * EncryptionOperationsTest.TripleDesCallerIv
7494 *
7495 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7496 */
7497TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7498 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7499 .TripleDesEncryptionKey(168)
7500 .BlockMode(BlockMode::CBC)
7501 .Authorization(TAG_NO_AUTH_REQUIRED)
7502 .Authorization(TAG_CALLER_NONCE)
7503 .Padding(PaddingMode::NONE)));
7504 string message = "1234567890123456";
7505 vector<uint8_t> iv;
7506 // Don't specify IV, should get a random one.
7507 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7508 EXPECT_EQ(message.size(), ciphertext1.size());
7509 EXPECT_EQ(8U, iv.size());
7510
7511 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7512 EXPECT_EQ(message, plaintext);
7513
7514 // Now specify an IV, should also work.
7515 iv = AidlBuf("abcdefgh");
7516 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7517
7518 // Decrypt with correct IV.
7519 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7520 EXPECT_EQ(message, plaintext);
7521
7522 // Now try with wrong IV.
7523 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7524 EXPECT_NE(message, plaintext);
7525}
7526
7527/*
7528 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7529 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007530 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007531 */
7532TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7533 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7534 .TripleDesEncryptionKey(168)
7535 .BlockMode(BlockMode::CBC)
7536 .Authorization(TAG_NO_AUTH_REQUIRED)
7537 .Padding(PaddingMode::NONE)));
7538
7539 string message = "12345678901234567890123456789012";
7540 vector<uint8_t> iv;
7541 // Don't specify nonce, should get a random one.
7542 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7543 EXPECT_EQ(message.size(), ciphertext1.size());
7544 EXPECT_EQ(8U, iv.size());
7545
7546 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7547 EXPECT_EQ(message, plaintext);
7548
7549 // Now specify a nonce, should fail.
7550 auto input_params = AuthorizationSetBuilder()
7551 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7552 .BlockMode(BlockMode::CBC)
7553 .Padding(PaddingMode::NONE);
7554 AuthorizationSet output_params;
7555 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7556 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7557}
7558
7559/*
7560 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7561 *
7562 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7563 */
7564TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7565 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7566 .TripleDesEncryptionKey(168)
7567 .BlockMode(BlockMode::ECB)
7568 .Authorization(TAG_NO_AUTH_REQUIRED)
7569 .Padding(PaddingMode::NONE)));
7570 // Two-block message.
7571 string message = "1234567890123456";
7572 auto begin_params =
7573 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7574 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7575}
7576
7577/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007578 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007579 *
7580 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7581 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007582TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7583 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007584 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007585 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7586 .TripleDesEncryptionKey(168)
7587 .BlockMode(blockMode)
7588 .Authorization(TAG_NO_AUTH_REQUIRED)
7589 .Padding(PaddingMode::NONE)));
7590 // Message is slightly shorter than two blocks.
7591 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007592
David Drysdaled2cc8c22021-04-15 13:29:45 +01007593 auto begin_params =
7594 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7595 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007596 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007597 string ciphertext;
7598 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7599
7600 CheckedDeleteKey();
7601 }
Selene Huang31ab4042020-04-29 04:22:39 -07007602}
7603
7604/*
7605 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7606 *
7607 * Verifies that PKCS7 padding works correctly in CBC mode.
7608 */
7609TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7610 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7611 .TripleDesEncryptionKey(168)
7612 .BlockMode(BlockMode::CBC)
7613 .Authorization(TAG_NO_AUTH_REQUIRED)
7614 .Padding(PaddingMode::PKCS7)));
7615
7616 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007617 for (size_t i = 0; i <= 32; i++) {
7618 SCOPED_TRACE(testing::Message() << "i = " << i);
7619 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7620 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007621 vector<uint8_t> iv;
7622 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7623 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7624 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7625 EXPECT_EQ(message, plaintext);
7626 }
7627}
7628
7629/*
7630 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7631 *
7632 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7633 */
7634TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7635 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7636 .TripleDesEncryptionKey(168)
7637 .BlockMode(BlockMode::CBC)
7638 .Authorization(TAG_NO_AUTH_REQUIRED)
7639 .Padding(PaddingMode::NONE)));
7640
7641 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007642 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007643 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007644 auto begin_params =
7645 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7646 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7647 }
7648}
7649
7650/*
7651 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7652 *
7653 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7654 */
7655TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7656 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7657 .TripleDesEncryptionKey(168)
7658 .BlockMode(BlockMode::CBC)
7659 .Authorization(TAG_NO_AUTH_REQUIRED)
7660 .Padding(PaddingMode::PKCS7)));
7661
7662 string message = "a";
7663 vector<uint8_t> iv;
7664 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7665 EXPECT_EQ(8U, ciphertext.size());
7666 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007667
7668 auto begin_params = AuthorizationSetBuilder()
7669 .BlockMode(BlockMode::CBC)
7670 .Padding(PaddingMode::PKCS7)
7671 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007672
7673 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007674 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007675 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007676 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007677 string plaintext;
7678 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7679 ErrorCode error = Finish(&plaintext);
7680 if (error == ErrorCode::INVALID_ARGUMENT) {
7681 // This is the expected error, we can exit the test now.
7682 return;
7683 } else {
7684 // Very small chance we got valid decryption, so try again.
7685 ASSERT_EQ(error, ErrorCode::OK);
7686 }
7687 }
7688 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007689}
7690
7691/*
7692 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7693 *
7694 * Verifies that 3DES CBC works with many different input sizes.
7695 */
7696TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7697 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7698 .TripleDesEncryptionKey(168)
7699 .BlockMode(BlockMode::CBC)
7700 .Authorization(TAG_NO_AUTH_REQUIRED)
7701 .Padding(PaddingMode::NONE)));
7702
7703 int increment = 7;
7704 string message(240, 'a');
7705 AuthorizationSet input_params =
7706 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7707 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007708 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007709
7710 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007711 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007712 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007713 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7714 EXPECT_EQ(message.size(), ciphertext.size());
7715
7716 // Move TAG_NONCE into input_params
7717 input_params = output_params;
7718 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7719 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7720 output_params.Clear();
7721
David Drysdale7fc26b92022-05-13 09:54:24 +01007722 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007723 string plaintext;
7724 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007725 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007726 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7727 EXPECT_EQ(ciphertext.size(), plaintext.size());
7728 EXPECT_EQ(message, plaintext);
7729}
7730
7731INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7732
7733typedef KeyMintAidlTestBase MaxOperationsTest;
7734
7735/*
7736 * MaxOperationsTest.TestLimitAes
7737 *
7738 * Verifies that the max uses per boot tag works correctly with AES keys.
7739 */
7740TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007741 if (SecLevel() == SecurityLevel::STRONGBOX) {
7742 GTEST_SKIP() << "Test not applicable to StrongBox device";
7743 }
Selene Huang31ab4042020-04-29 04:22:39 -07007744
7745 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7746 .Authorization(TAG_NO_AUTH_REQUIRED)
7747 .AesEncryptionKey(128)
7748 .EcbMode()
7749 .Padding(PaddingMode::NONE)
7750 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7751
7752 string message = "1234567890123456";
7753
7754 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7755
7756 EncryptMessage(message, params);
7757 EncryptMessage(message, params);
7758 EncryptMessage(message, params);
7759
7760 // Fourth time should fail.
7761 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7762}
7763
7764/*
Qi Wud22ec842020-11-26 13:27:53 +08007765 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007766 *
7767 * Verifies that the max uses per boot tag works correctly with RSA keys.
7768 */
7769TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007770 if (SecLevel() == SecurityLevel::STRONGBOX) {
7771 GTEST_SKIP() << "Test not applicable to StrongBox device";
7772 }
Selene Huang31ab4042020-04-29 04:22:39 -07007773
7774 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7775 .Authorization(TAG_NO_AUTH_REQUIRED)
7776 .RsaSigningKey(1024, 65537)
7777 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007778 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7779 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007780
7781 string message = "1234567890123456";
7782
7783 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7784
7785 SignMessage(message, params);
7786 SignMessage(message, params);
7787 SignMessage(message, params);
7788
7789 // Fourth time should fail.
7790 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7791}
7792
7793INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7794
Qi Wud22ec842020-11-26 13:27:53 +08007795typedef KeyMintAidlTestBase UsageCountLimitTest;
7796
7797/*
Qi Wubeefae42021-01-28 23:16:37 +08007798 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007799 *
Qi Wubeefae42021-01-28 23:16:37 +08007800 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007801 */
Qi Wubeefae42021-01-28 23:16:37 +08007802TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007803 if (SecLevel() == SecurityLevel::STRONGBOX) {
7804 GTEST_SKIP() << "Test not applicable to StrongBox device";
7805 }
Qi Wud22ec842020-11-26 13:27:53 +08007806
7807 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7808 .Authorization(TAG_NO_AUTH_REQUIRED)
7809 .AesEncryptionKey(128)
7810 .EcbMode()
7811 .Padding(PaddingMode::NONE)
7812 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7813
7814 // Check the usage count limit tag appears in the authorizations.
7815 AuthorizationSet auths;
7816 for (auto& entry : key_characteristics_) {
7817 auths.push_back(AuthorizationSet(entry.authorizations));
7818 }
7819 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7820 << "key usage count limit " << 1U << " missing";
7821
7822 string message = "1234567890123456";
7823 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7824
Qi Wubeefae42021-01-28 23:16:37 +08007825 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7826 AuthorizationSet keystore_auths =
7827 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7828
Qi Wud22ec842020-11-26 13:27:53 +08007829 // First usage of AES key should work.
7830 EncryptMessage(message, params);
7831
Qi Wud22ec842020-11-26 13:27:53 +08007832 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7833 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7834 // must be invalidated from secure storage (such as RPMB partition).
7835 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7836 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007837 // Usage count limit tag is enforced by keystore, keymint does nothing.
7838 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007839 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007840 }
7841}
7842
7843/*
Qi Wubeefae42021-01-28 23:16:37 +08007844 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007845 *
Qi Wubeefae42021-01-28 23:16:37 +08007846 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007847 */
Qi Wubeefae42021-01-28 23:16:37 +08007848TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007849 if (SecLevel() == SecurityLevel::STRONGBOX) {
7850 GTEST_SKIP() << "Test not applicable to StrongBox device";
7851 }
Qi Wubeefae42021-01-28 23:16:37 +08007852
7853 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7854 .Authorization(TAG_NO_AUTH_REQUIRED)
7855 .AesEncryptionKey(128)
7856 .EcbMode()
7857 .Padding(PaddingMode::NONE)
7858 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7859
7860 // Check the usage count limit tag appears in the authorizations.
7861 AuthorizationSet auths;
7862 for (auto& entry : key_characteristics_) {
7863 auths.push_back(AuthorizationSet(entry.authorizations));
7864 }
7865 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7866 << "key usage count limit " << 3U << " missing";
7867
7868 string message = "1234567890123456";
7869 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7870
7871 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7872 AuthorizationSet keystore_auths =
7873 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7874
7875 EncryptMessage(message, params);
7876 EncryptMessage(message, params);
7877 EncryptMessage(message, params);
7878
7879 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7880 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7881 // must be invalidated from secure storage (such as RPMB partition).
7882 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7883 } else {
7884 // Usage count limit tag is enforced by keystore, keymint does nothing.
7885 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007886 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007887 }
7888}
7889
7890/*
7891 * UsageCountLimitTest.TestSingleUseRsa
7892 *
7893 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7894 */
7895TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007896 if (SecLevel() == SecurityLevel::STRONGBOX) {
7897 GTEST_SKIP() << "Test not applicable to StrongBox device";
7898 }
Qi Wud22ec842020-11-26 13:27:53 +08007899
7900 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7901 .Authorization(TAG_NO_AUTH_REQUIRED)
7902 .RsaSigningKey(1024, 65537)
7903 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007904 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7905 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007906
7907 // Check the usage count limit tag appears in the authorizations.
7908 AuthorizationSet auths;
7909 for (auto& entry : key_characteristics_) {
7910 auths.push_back(AuthorizationSet(entry.authorizations));
7911 }
7912 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7913 << "key usage count limit " << 1U << " missing";
7914
7915 string message = "1234567890123456";
7916 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7917
Qi Wubeefae42021-01-28 23:16:37 +08007918 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7919 AuthorizationSet keystore_auths =
7920 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7921
Qi Wud22ec842020-11-26 13:27:53 +08007922 // First usage of RSA key should work.
7923 SignMessage(message, params);
7924
Qi Wud22ec842020-11-26 13:27:53 +08007925 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7926 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7927 // must be invalidated from secure storage (such as RPMB partition).
7928 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7929 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007930 // Usage count limit tag is enforced by keystore, keymint does nothing.
7931 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007932 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007933 }
7934}
7935
7936/*
7937 * UsageCountLimitTest.TestLimitUseRsa
7938 *
7939 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7940 */
7941TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007942 if (SecLevel() == SecurityLevel::STRONGBOX) {
7943 GTEST_SKIP() << "Test not applicable to StrongBox device";
7944 }
Qi Wubeefae42021-01-28 23:16:37 +08007945
7946 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7947 .Authorization(TAG_NO_AUTH_REQUIRED)
7948 .RsaSigningKey(1024, 65537)
7949 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007950 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7951 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007952
7953 // Check the usage count limit tag appears in the authorizations.
7954 AuthorizationSet auths;
7955 for (auto& entry : key_characteristics_) {
7956 auths.push_back(AuthorizationSet(entry.authorizations));
7957 }
7958 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7959 << "key usage count limit " << 3U << " missing";
7960
7961 string message = "1234567890123456";
7962 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7963
7964 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7965 AuthorizationSet keystore_auths =
7966 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7967
7968 SignMessage(message, params);
7969 SignMessage(message, params);
7970 SignMessage(message, params);
7971
7972 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7973 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7974 // must be invalidated from secure storage (such as RPMB partition).
7975 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7976 } else {
7977 // Usage count limit tag is enforced by keystore, keymint does nothing.
7978 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007979 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007980 }
7981}
7982
Qi Wu8e727f72021-02-11 02:49:33 +08007983/*
7984 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7985 *
7986 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7987 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7988 * in hardware.
7989 */
7990TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
Qi Wu8e727f72021-02-11 02:49:33 +08007991 auto error = GenerateKey(AuthorizationSetBuilder()
7992 .RsaSigningKey(2048, 65537)
7993 .Digest(Digest::NONE)
7994 .Padding(PaddingMode::NONE)
7995 .Authorization(TAG_NO_AUTH_REQUIRED)
7996 .Authorization(TAG_ROLLBACK_RESISTANCE)
7997 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007998 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7999 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08008000 }
David Drysdale513bf122021-10-06 11:53:13 +01008001
8002 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
8003 ASSERT_EQ(ErrorCode::OK, error);
8004 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8005 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
8006 ASSERT_EQ(ErrorCode::OK, DeleteKey());
8007
8008 // The KeyMint should also enforce single use key in hardware when it supports rollback
8009 // resistance.
8010 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8011 .Authorization(TAG_NO_AUTH_REQUIRED)
8012 .RsaSigningKey(1024, 65537)
8013 .NoDigestOrPadding()
8014 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
8015 .SetDefaultValidity()));
8016
8017 // Check the usage count limit tag appears in the hardware authorizations.
8018 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
8019 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
8020 << "key usage count limit " << 1U << " missing";
8021
8022 string message = "1234567890123456";
8023 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
8024
8025 // First usage of RSA key should work.
8026 SignMessage(message, params);
8027
8028 // Usage count limit tag is enforced by hardware. After using the key, the key blob
8029 // must be invalidated from secure storage (such as RPMB partition).
8030 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08008031}
8032
Qi Wud22ec842020-11-26 13:27:53 +08008033INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
8034
David Drysdale7de9feb2021-03-05 14:56:19 +00008035typedef KeyMintAidlTestBase GetHardwareInfoTest;
8036
8037TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
8038 // Retrieving hardware info should give the same result each time.
8039 KeyMintHardwareInfo info;
8040 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
8041 KeyMintHardwareInfo info2;
8042 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
8043 EXPECT_EQ(info, info2);
8044}
8045
8046INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
8047
Selene Huang31ab4042020-04-29 04:22:39 -07008048typedef KeyMintAidlTestBase AddEntropyTest;
8049
8050/*
8051 * AddEntropyTest.AddEntropy
8052 *
8053 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
8054 * is actually added.
8055 */
8056TEST_P(AddEntropyTest, AddEntropy) {
8057 string data = "foo";
8058 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
8059}
8060
8061/*
8062 * AddEntropyTest.AddEmptyEntropy
8063 *
8064 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
8065 */
8066TEST_P(AddEntropyTest, AddEmptyEntropy) {
8067 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
8068}
8069
8070/*
8071 * AddEntropyTest.AddLargeEntropy
8072 *
8073 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
8074 */
8075TEST_P(AddEntropyTest, AddLargeEntropy) {
8076 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
8077}
8078
David Drysdalebb3d85e2021-04-13 11:15:51 +01008079/*
8080 * AddEntropyTest.AddTooLargeEntropy
8081 *
8082 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
8083 */
8084TEST_P(AddEntropyTest, AddTooLargeEntropy) {
8085 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
8086 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
8087}
8088
Selene Huang31ab4042020-04-29 04:22:39 -07008089INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
8090
Selene Huang31ab4042020-04-29 04:22:39 -07008091typedef KeyMintAidlTestBase KeyDeletionTest;
8092
8093/**
8094 * KeyDeletionTest.DeleteKey
8095 *
8096 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
8097 * valid key blob.
8098 */
8099TEST_P(KeyDeletionTest, DeleteKey) {
8100 auto error = GenerateKey(AuthorizationSetBuilder()
8101 .RsaSigningKey(2048, 65537)
8102 .Digest(Digest::NONE)
8103 .Padding(PaddingMode::NONE)
8104 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008105 .Authorization(TAG_ROLLBACK_RESISTANCE)
8106 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008107 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8108 GTEST_SKIP() << "Rollback resistance not supported";
8109 }
Selene Huang31ab4042020-04-29 04:22:39 -07008110
8111 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008112 ASSERT_EQ(ErrorCode::OK, error);
8113 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8114 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008115
David Drysdale513bf122021-10-06 11:53:13 +01008116 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07008117
David Drysdale513bf122021-10-06 11:53:13 +01008118 string message = "12345678901234567890123456789012";
8119 AuthorizationSet begin_out_params;
8120 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8121 Begin(KeyPurpose::SIGN, key_blob_,
8122 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8123 &begin_out_params));
8124 AbortIfNeeded();
8125 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008126}
8127
8128/**
8129 * KeyDeletionTest.DeleteInvalidKey
8130 *
8131 * This test checks that the HAL excepts invalid key blobs..
8132 */
8133TEST_P(KeyDeletionTest, DeleteInvalidKey) {
8134 // Generate key just to check if rollback protection is implemented
8135 auto error = GenerateKey(AuthorizationSetBuilder()
8136 .RsaSigningKey(2048, 65537)
8137 .Digest(Digest::NONE)
8138 .Padding(PaddingMode::NONE)
8139 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08008140 .Authorization(TAG_ROLLBACK_RESISTANCE)
8141 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008142 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8143 GTEST_SKIP() << "Rollback resistance not supported";
8144 }
Selene Huang31ab4042020-04-29 04:22:39 -07008145
8146 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008147 ASSERT_EQ(ErrorCode::OK, error);
8148 AuthorizationSet enforced(SecLevelAuthorizations());
8149 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008150
David Drysdale513bf122021-10-06 11:53:13 +01008151 // Delete the key we don't care about the result at this point.
8152 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07008153
David Drysdale513bf122021-10-06 11:53:13 +01008154 // Now create an invalid key blob and delete it.
8155 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07008156
David Drysdale513bf122021-10-06 11:53:13 +01008157 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07008158}
8159
8160/**
8161 * KeyDeletionTest.DeleteAllKeys
8162 *
8163 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
8164 *
8165 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
8166 * FBE/FDE encryption keys, which means that the device will not even boot until after the
8167 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
8168 * been provisioned. Use this test only on dedicated testing devices that have no valuable
8169 * credentials stored in Keystore/Keymint.
8170 */
8171TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01008172 if (!arm_deleteAllKeys) {
8173 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
8174 return;
8175 }
Selene Huang31ab4042020-04-29 04:22:39 -07008176 auto error = GenerateKey(AuthorizationSetBuilder()
8177 .RsaSigningKey(2048, 65537)
8178 .Digest(Digest::NONE)
8179 .Padding(PaddingMode::NONE)
8180 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06008181 .Authorization(TAG_ROLLBACK_RESISTANCE)
8182 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01008183 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8184 GTEST_SKIP() << "Rollback resistance not supported";
8185 }
Selene Huang31ab4042020-04-29 04:22:39 -07008186
8187 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01008188 ASSERT_EQ(ErrorCode::OK, error);
8189 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8190 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07008191
David Drysdale513bf122021-10-06 11:53:13 +01008192 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07008193
David Drysdale513bf122021-10-06 11:53:13 +01008194 string message = "12345678901234567890123456789012";
8195 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07008196
David Drysdale513bf122021-10-06 11:53:13 +01008197 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8198 Begin(KeyPurpose::SIGN, key_blob_,
8199 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8200 &begin_out_params));
8201 AbortIfNeeded();
8202 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008203}
8204
8205INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8206
David Drysdaled2cc8c22021-04-15 13:29:45 +01008207typedef KeyMintAidlTestBase KeyUpgradeTest;
8208
8209/**
8210 * KeyUpgradeTest.UpgradeInvalidKey
8211 *
8212 * This test checks that the HAL excepts invalid key blobs..
8213 */
8214TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8215 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8216
8217 std::vector<uint8_t> new_blob;
8218 Status result = keymint_->upgradeKey(key_blob,
8219 AuthorizationSetBuilder()
8220 .Authorization(TAG_APPLICATION_ID, "clientid")
8221 .Authorization(TAG_APPLICATION_DATA, "appdata")
8222 .vector_data(),
8223 &new_blob);
8224 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8225}
8226
8227INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8228
Selene Huang31ab4042020-04-29 04:22:39 -07008229using UpgradeKeyTest = KeyMintAidlTestBase;
8230
8231/*
8232 * UpgradeKeyTest.UpgradeKey
8233 *
8234 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8235 */
8236TEST_P(UpgradeKeyTest, UpgradeKey) {
8237 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8238 .AesEncryptionKey(128)
8239 .Padding(PaddingMode::NONE)
8240 .Authorization(TAG_NO_AUTH_REQUIRED)));
8241
8242 auto result = UpgradeKey(key_blob_);
8243
8244 // Key doesn't need upgrading. Should get okay, but no new key blob.
8245 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8246}
8247
8248INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8249
8250using ClearOperationsTest = KeyMintAidlTestBase;
8251
8252/*
8253 * ClearSlotsTest.TooManyOperations
8254 *
8255 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8256 * operations are started without being finished or aborted. Also verifies
8257 * that aborting the operations clears the operations.
8258 *
8259 */
8260TEST_P(ClearOperationsTest, TooManyOperations) {
8261 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8262 .Authorization(TAG_NO_AUTH_REQUIRED)
8263 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008264 .Padding(PaddingMode::NONE)
8265 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008266
8267 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8268 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008269 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008270 AuthorizationSet out_params;
8271 ErrorCode result;
8272 size_t i;
8273
8274 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008275 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008276 if (ErrorCode::OK != result) {
8277 break;
8278 }
8279 }
8280 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8281 // Try again just in case there's a weird overflow bug
8282 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008283 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008284 for (size_t j = 0; j < i; j++) {
8285 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8286 << "Aboort failed for i = " << j << std::endl;
8287 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008288 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008289 AbortIfNeeded();
8290}
8291
8292INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8293
8294typedef KeyMintAidlTestBase TransportLimitTest;
8295
8296/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008297 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008298 *
8299 * Verifies that passing input data to finish succeeds as expected.
8300 */
8301TEST_P(TransportLimitTest, LargeFinishInput) {
8302 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8303 .Authorization(TAG_NO_AUTH_REQUIRED)
8304 .AesEncryptionKey(128)
8305 .BlockMode(BlockMode::ECB)
8306 .Padding(PaddingMode::NONE)));
8307
8308 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008309 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008310 auto cipher_params =
8311 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8312
8313 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008314 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008315
8316 string plain_message = std::string(1 << msg_size, 'x');
8317 string encrypted_message;
8318 auto rc = Finish(plain_message, &encrypted_message);
8319
8320 EXPECT_EQ(ErrorCode::OK, rc);
8321 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8322 << "Encrypt finish returned OK, but did not consume all of the given input";
8323 cipher_params.push_back(out_params);
8324
David Drysdale7fc26b92022-05-13 09:54:24 +01008325 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008326
8327 string decrypted_message;
8328 rc = Finish(encrypted_message, &decrypted_message);
8329 EXPECT_EQ(ErrorCode::OK, rc);
8330 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8331 << "Decrypt finish returned OK, did not consume all of the given input";
8332 }
8333}
8334
8335INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8336
Seth Moored79a0ec2021-12-13 20:03:33 +00008337static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008338 switch (curve) {
8339 case EcCurve::P_224:
8340 return NID_secp224r1;
8341 case EcCurve::P_256:
8342 return NID_X9_62_prime256v1;
8343 case EcCurve::P_384:
8344 return NID_secp384r1;
8345 case EcCurve::P_521:
8346 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008347 case EcCurve::CURVE_25519:
8348 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008349 }
8350}
8351
David Drysdale42fe1892021-10-14 14:43:46 +01008352class KeyAgreementTest : public KeyMintAidlTestBase {
8353 protected:
8354 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8355 std::vector<uint8_t>* localPublicKey) {
8356 // Generate EC key locally (with access to private key material)
8357 if (localCurve == EcCurve::CURVE_25519) {
8358 uint8_t privKeyData[32];
8359 uint8_t pubKeyData[32];
8360 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008361 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8362 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8363 } else {
8364 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8365 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8366 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8367 ASSERT_NE(group, nullptr);
8368 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8369 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8370 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8371 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008372 }
David Drysdalea410b772022-05-09 16:44:13 +01008373
8374 // Get encoded form of the public part of the locally generated key...
8375 unsigned char* p = nullptr;
8376 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8377 ASSERT_GT(localPublicKeySize, 0);
8378 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8379 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8380 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008381 }
8382
8383 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8384 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008385 auto builder = AuthorizationSetBuilder()
8386 .Authorization(TAG_NO_AUTH_REQUIRED)
8387 .Authorization(TAG_EC_CURVE, curve)
8388 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8389 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8390 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8391 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8392 .SetDefaultValidity();
8393 ErrorCode result = GenerateKey(builder);
David Drysdale42fe1892021-10-14 14:43:46 +01008394 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8395 ASSERT_GT(cert_chain_.size(), 0);
8396 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8397 ASSERT_NE(kmKeyCert, nullptr);
8398 // Check that keyAgreement (bit 4) is set in KeyUsage
8399 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8400 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8401 ASSERT_NE(*kmPubKey, nullptr);
8402 if (dump_Attestations) {
8403 for (size_t n = 0; n < cert_chain_.size(); n++) {
8404 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8405 }
8406 }
8407 }
8408
8409 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8410 const std::vector<uint8_t>& localPublicKey) {
8411 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8412 string ZabFromKeyMintStr;
8413 ASSERT_EQ(ErrorCode::OK,
8414 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8415 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8416 vector<uint8_t> ZabFromTest;
8417
8418 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8419 size_t kmPubKeySize = 32;
8420 uint8_t kmPubKeyData[32];
8421 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8422 ASSERT_EQ(kmPubKeySize, 32);
8423
8424 uint8_t localPrivKeyData[32];
8425 size_t localPrivKeySize = 32;
8426 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8427 &localPrivKeySize));
8428 ASSERT_EQ(localPrivKeySize, 32);
8429
8430 uint8_t sharedKey[32];
8431 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8432 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8433 } else {
8434 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8435 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8436 ASSERT_NE(ctx, nullptr);
8437 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8438 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8439 size_t ZabFromTestLen = 0;
8440 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8441 ZabFromTest.resize(ZabFromTestLen);
8442 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8443 }
8444 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8445 }
8446};
8447
David Zeuthene0c40892021-01-08 12:54:11 -05008448/*
8449 * KeyAgreementTest.Ecdh
8450 *
David Drysdale42fe1892021-10-14 14:43:46 +01008451 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008452 */
8453TEST_P(KeyAgreementTest, Ecdh) {
8454 // Because it's possible to use this API with keys on different curves, we
8455 // check all N^2 combinations where N is the number of supported
8456 // curves.
8457 //
8458 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8459 // lot more curves we can be smart about things and just pick |otherCurve| so
8460 // it's not |curve| and that way we end up with only 2*N runs
8461 //
8462 for (auto curve : ValidCurves()) {
8463 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008464 SCOPED_TRACE(testing::Message()
8465 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8466
David Zeuthene0c40892021-01-08 12:54:11 -05008467 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008468 EVP_PKEY_Ptr localPrivKey;
8469 vector<uint8_t> localPublicKey;
8470 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008471
8472 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008473 EVP_PKEY_Ptr kmPubKey;
8474 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008475
8476 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8477 if (curve != localCurve) {
8478 // If the keys are using different curves KeyMint should fail with
8479 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008480 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008481 string ZabFromKeyMintStr;
8482 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008483 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008484 &ZabFromKeyMintStr));
8485
8486 } else {
8487 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008488 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008489 }
8490
8491 CheckedDeleteKey();
8492 }
8493 }
8494}
8495
David Drysdale42fe1892021-10-14 14:43:46 +01008496/*
8497 * KeyAgreementTest.EcdhCurve25519
8498 *
8499 * Verifies that ECDH works for curve25519. This is also covered by the general
8500 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8501 * KeyMint 1.0.
8502 */
8503TEST_P(KeyAgreementTest, EcdhCurve25519) {
8504 if (!Curve25519Supported()) {
8505 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8506 }
8507
8508 // Generate EC key in KeyMint (only access to public key material)
8509 EcCurve curve = EcCurve::CURVE_25519;
8510 EVP_PKEY_Ptr kmPubKey = nullptr;
8511 GenerateKeyMintEcKey(curve, &kmPubKey);
8512
8513 // Generate EC key on same curve locally (with access to private key material).
8514 EVP_PKEY_Ptr privKey;
8515 vector<uint8_t> encodedPublicKey;
8516 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8517
8518 // Agree on a key between local and KeyMint and check it.
8519 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8520
8521 CheckedDeleteKey();
8522}
8523
8524/*
8525 * KeyAgreementTest.EcdhCurve25519Imported
8526 *
8527 * Verifies that ECDH works for an imported curve25519 key.
8528 */
8529TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8530 if (!Curve25519Supported()) {
8531 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8532 }
8533
8534 // Import x25519 key into KeyMint.
8535 EcCurve curve = EcCurve::CURVE_25519;
8536 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8537 .Authorization(TAG_NO_AUTH_REQUIRED)
8538 .EcdsaKey(EcCurve::CURVE_25519)
8539 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8540 .SetDefaultValidity(),
8541 KeyFormat::PKCS8, x25519_pkcs8_key));
8542 ASSERT_GT(cert_chain_.size(), 0);
8543 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8544 ASSERT_NE(kmKeyCert, nullptr);
8545 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8546 ASSERT_NE(kmPubKey.get(), nullptr);
8547
8548 // Expect the import to emit corresponding public key data.
8549 size_t kmPubKeySize = 32;
8550 uint8_t kmPubKeyData[32];
8551 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8552 ASSERT_EQ(kmPubKeySize, 32);
8553 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8554 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8555
8556 // Generate EC key on same curve locally (with access to private key material).
8557 EVP_PKEY_Ptr privKey;
8558 vector<uint8_t> encodedPublicKey;
8559 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8560
8561 // Agree on a key between local and KeyMint and check it.
8562 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8563
8564 CheckedDeleteKey();
8565}
8566
8567/*
8568 * KeyAgreementTest.EcdhCurve25519InvalidSize
8569 *
8570 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8571 */
8572TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8573 if (!Curve25519Supported()) {
8574 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8575 }
8576
8577 // Generate EC key in KeyMint (only access to public key material)
8578 EcCurve curve = EcCurve::CURVE_25519;
8579 EVP_PKEY_Ptr kmPubKey = nullptr;
8580 GenerateKeyMintEcKey(curve, &kmPubKey);
8581
8582 // Generate EC key on same curve locally (with access to private key material).
8583 EVP_PKEY_Ptr privKey;
8584 vector<uint8_t> encodedPublicKey;
8585 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8586
8587 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8588 string ZabFromKeyMintStr;
8589 // Send in an incomplete public key.
8590 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8591 &ZabFromKeyMintStr));
8592
8593 CheckedDeleteKey();
8594}
8595
8596/*
8597 * KeyAgreementTest.EcdhCurve25519Mismatch
8598 *
8599 * Verifies that ECDH fails between curve25519 and other curves.
8600 */
8601TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8602 if (!Curve25519Supported()) {
8603 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8604 }
8605
8606 // Generate EC key in KeyMint (only access to public key material)
8607 EcCurve curve = EcCurve::CURVE_25519;
8608 EVP_PKEY_Ptr kmPubKey = nullptr;
8609 GenerateKeyMintEcKey(curve, &kmPubKey);
8610
8611 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008612 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008613 if (localCurve == curve) {
8614 continue;
8615 }
8616 // Generate EC key on a different curve locally (with access to private key material).
8617 EVP_PKEY_Ptr privKey;
8618 vector<uint8_t> encodedPublicKey;
8619 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8620
David Drysdale7fc26b92022-05-13 09:54:24 +01008621 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008622 string ZabFromKeyMintStr;
8623 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8624 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8625 &ZabFromKeyMintStr));
8626 }
8627
8628 CheckedDeleteKey();
8629}
8630
David Zeuthene0c40892021-01-08 12:54:11 -05008631INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8632
David Drysdaled2cc8c22021-04-15 13:29:45 +01008633using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8634
8635// This is a problematic test, as it can render the device under test permanently unusable.
8636// Re-enable and run at your own risk.
8637TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8638 auto result = DestroyAttestationIds();
8639 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8640}
8641
8642INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8643
Shawn Willdend659c7c2021-02-19 14:51:51 -07008644using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008645
David Drysdaledb0dcf52021-05-18 11:43:31 +01008646/*
8647 * EarlyBootKeyTest.CreateEarlyBootKeys
8648 *
8649 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8650 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008651TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008652 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008653 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8654 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008655 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8656 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8657 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8658 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008659
David Drysdaleadfe6112021-05-27 12:00:53 +01008660 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8661 ASSERT_GT(keyData.blob.size(), 0U);
8662 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8663 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8664 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008665}
8666
David Drysdaledb0dcf52021-05-18 11:43:31 +01008667/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008668 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8669 *
8670 * Verifies that creating an early boot key with attestation succeeds.
8671 */
8672TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8673 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8674 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8675 builder->AttestationChallenge("challenge");
8676 builder->AttestationApplicationId("app_id");
8677 });
David Drysdale1b9febc2023-06-07 13:43:24 +01008678 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8679 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8680 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8681 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
David Drysdaleadfe6112021-05-27 12:00:53 +01008682
8683 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8684 ASSERT_GT(keyData.blob.size(), 0U);
8685 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8686 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8687 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008688}
8689
8690/*
8691 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008692 *
8693 * Verifies that using early boot keys at a later stage fails.
8694 */
8695TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8696 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8697 .Authorization(TAG_NO_AUTH_REQUIRED)
8698 .Authorization(TAG_EARLY_BOOT_ONLY)
8699 .HmacKey(128)
8700 .Digest(Digest::SHA_2_256)
8701 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8702 AuthorizationSet output_params;
8703 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8704 AuthorizationSetBuilder()
8705 .Digest(Digest::SHA_2_256)
8706 .Authorization(TAG_MAC_LENGTH, 256),
8707 &output_params));
8708}
8709
8710/*
8711 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8712 *
8713 * Verifies that importing early boot keys fails.
8714 */
8715TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8716 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8717 .Authorization(TAG_NO_AUTH_REQUIRED)
8718 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008719 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008720 .Digest(Digest::SHA_2_256)
8721 .SetDefaultValidity(),
8722 KeyFormat::PKCS8, ec_256_key));
8723}
8724
David Drysdaled2cc8c22021-04-15 13:29:45 +01008725// 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 +00008726// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8727// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8728// early boot, so you'll have to reboot between runs.
8729TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8730 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8731 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
David Drysdale1b9febc2023-06-07 13:43:24 +01008732 KeyBlobDeleter aes_deleter(keymint_, aesKeyData.blob);
8733 KeyBlobDeleter hmac_deleter(keymint_, hmacKeyData.blob);
8734 KeyBlobDeleter rsa_deleter(keymint_, rsaKeyData.blob);
8735 KeyBlobDeleter ecdsa_deleter(keymint_, ecdsaKeyData.blob);
8736
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008737 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8738 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8739 EXPECT_TRUE(
8740 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8741 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8742 EXPECT_TRUE(
8743 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8744
8745 // Should be able to use keys, since early boot has not ended
8746 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8747 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8748 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8749 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8750
8751 // End early boot
8752 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8753 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8754
8755 // Should not be able to use already-created keys.
8756 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8757 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8758 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8759 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8760
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008761 // Should not be able to create new keys
David Drysdale1b9febc2023-06-07 13:43:24 +01008762 auto [aesKeyData2, hmacKeyData2, rsaKeyData2, ecdsaKeyData2] =
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008763 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
David Drysdale1b9febc2023-06-07 13:43:24 +01008764 KeyBlobDeleter aes_deleter2(keymint_, aesKeyData2.blob);
8765 KeyBlobDeleter hmac_deleter2(keymint_, hmacKeyData2.blob);
8766 KeyBlobDeleter rsa_deleter2(keymint_, rsaKeyData2.blob);
8767 KeyBlobDeleter ecdsa_deleter2(keymint_, ecdsaKeyData2.blob);
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008768}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008769
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008770INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8771
Shawn Willden22fb9c12022-06-02 14:04:33 -06008772using VsrRequirementTest = KeyMintAidlTestBase;
8773
Eran Messeri5fe06ea2023-08-02 22:34:24 +01008774// @VsrTest = VSR-3.10-008
Shawn Willden22fb9c12022-06-02 14:04:33 -06008775TEST_P(VsrRequirementTest, Vsr13Test) {
8776 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008777 if (vsr_api_level < __ANDROID_API_T__) {
Shawn Willden22fb9c12022-06-02 14:04:33 -06008778 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8779 }
8780 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8781}
8782
Eran Messeri5fe06ea2023-08-02 22:34:24 +01008783// @VsrTest = VSR-3.10-013.001
Eran Messerib9346f52022-12-15 14:58:34 +00008784TEST_P(VsrRequirementTest, Vsr14Test) {
8785 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008786 if (vsr_api_level < __ANDROID_API_U__) {
Eran Messerib9346f52022-12-15 14:58:34 +00008787 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8788 }
8789 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8790}
8791
Shawn Willden22fb9c12022-06-02 14:04:33 -06008792INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8793
David Drysdale6c9bdb82024-01-23 09:32:04 +00008794class InstanceTest : public testing::Test {
8795 protected:
8796 static void SetUpTestSuite() {
8797 auto params = ::android::getAidlHalInstanceNames(IKeyMintDevice::descriptor);
8798 for (auto& param : params) {
8799 ASSERT_TRUE(AServiceManager_isDeclared(param.c_str()))
8800 << "IKeyMintDevice instance " << param << " found but not declared.";
8801 ::ndk::SpAIBinder binder(AServiceManager_waitForService(param.c_str()));
8802 auto keymint = IKeyMintDevice::fromBinder(binder);
8803 ASSERT_NE(keymint, nullptr) << "Failed to get IKeyMintDevice instance " << param;
8804
8805 KeyMintHardwareInfo info;
8806 ASSERT_TRUE(keymint->getHardwareInfo(&info).isOk());
8807 ASSERT_EQ(keymints_.count(info.securityLevel), 0)
8808 << "There must be exactly one IKeyMintDevice with security level "
8809 << info.securityLevel;
8810
8811 keymints_[info.securityLevel] = std::move(keymint);
8812 }
8813 }
8814
8815 int32_t AidlVersion(shared_ptr<IKeyMintDevice> keymint) {
8816 int32_t version = 0;
8817 auto status = keymint->getInterfaceVersion(&version);
8818 if (!status.isOk()) {
8819 ADD_FAILURE() << "Failed to determine interface version";
8820 }
8821 return version;
8822 }
8823
8824 static std::map<SecurityLevel, shared_ptr<IKeyMintDevice>> keymints_;
8825};
8826
8827std::map<SecurityLevel, shared_ptr<IKeyMintDevice>> InstanceTest::keymints_;
8828
8829// @VsrTest = VSR-3.10-017
8830// Check that the AIDL version advertised by the HAL service matches
8831// the value in the package manager feature version.
8832TEST_F(InstanceTest, AidlVersionInFeature) {
8833 if (is_gsi_image()) {
8834 GTEST_SKIP() << "Versions not required to match under GSI";
8835 }
8836 if (keymints_.count(SecurityLevel::TRUSTED_ENVIRONMENT) == 1) {
8837 auto tee = keymints_.find(SecurityLevel::TRUSTED_ENVIRONMENT)->second;
8838 int32_t tee_aidl_version = AidlVersion(tee) * 100;
8839 std::optional<int32_t> tee_feature_version = keymint_feature_value(/* strongbox */ false);
8840 ASSERT_TRUE(tee_feature_version.has_value());
8841 EXPECT_EQ(tee_aidl_version, tee_feature_version.value());
8842 }
8843 if (keymints_.count(SecurityLevel::STRONGBOX) == 1) {
8844 auto sb = keymints_.find(SecurityLevel::STRONGBOX)->second;
8845 int32_t sb_aidl_version = AidlVersion(sb) * 100;
8846 std::optional<int32_t> sb_feature_version = keymint_feature_value(/* strongbox */ true);
8847 ASSERT_TRUE(sb_feature_version.has_value());
8848 EXPECT_EQ(sb_aidl_version, sb_feature_version.value());
8849 }
8850}
8851
8852// @VsrTest = VSR-3.10-017
8853// Check that if package manager advertises support for KeyMint of a particular version, that
8854// version is present as a HAL service.
8855TEST_F(InstanceTest, FeatureVersionInAidl) {
8856 if (is_gsi_image()) {
8857 GTEST_SKIP() << "Versions not required to match under GSI";
8858 }
8859 std::optional<int32_t> tee_feature_version = keymint_feature_value(/* strongbox */ false);
8860 if (tee_feature_version.has_value() && tee_feature_version.value() >= 100) {
8861 // Feature flag advertises the existence of KeyMint; check it is present.
8862 ASSERT_EQ(keymints_.count(SecurityLevel::TRUSTED_ENVIRONMENT), 1);
8863 auto tee = keymints_.find(SecurityLevel::TRUSTED_ENVIRONMENT)->second;
8864 int32_t tee_aidl_version = AidlVersion(tee) * 100;
8865 EXPECT_EQ(tee_aidl_version, tee_feature_version.value());
8866 }
8867
8868 std::optional<int32_t> sb_feature_version = keymint_feature_value(/* strongbox */ true);
8869 if (sb_feature_version.has_value() && sb_feature_version.value() >= 100) {
8870 // Feature flag advertises the existence of KeyMint; check it is present.
8871 ASSERT_EQ(keymints_.count(SecurityLevel::STRONGBOX), 1);
8872 auto sb = keymints_.find(SecurityLevel::STRONGBOX)->second;
8873 int32_t sb_aidl_version = AidlVersion(sb) * 100;
8874 EXPECT_EQ(sb_aidl_version, sb_feature_version.value());
8875 }
8876}
8877
Janis Danisevskis24c04702020-12-16 18:28:39 -08008878} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008879
David Drysdale77a86d82024-01-03 11:22:56 +00008880using aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase;
8881
Selene Huang31ab4042020-04-29 04:22:39 -07008882int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008883 std::cout << "Testing ";
David Drysdale77a86d82024-01-03 11:22:56 +00008884 auto halInstances = KeyMintAidlTestBase::build_params();
Shawn Willden7c130392020-12-21 09:58:22 -07008885 std::cout << "HAL instances:\n";
8886 for (auto& entry : halInstances) {
8887 std::cout << " " << entry << '\n';
8888 }
8889
Selene Huang31ab4042020-04-29 04:22:39 -07008890 ::testing::InitGoogleTest(&argc, argv);
8891 for (int i = 1; i < argc; ++i) {
8892 if (argv[i][0] == '-') {
8893 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
David Drysdale77a86d82024-01-03 11:22:56 +00008894 KeyMintAidlTestBase::arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008895 }
8896 if (std::string(argv[i]) == "--dump_attestations") {
David Drysdale77a86d82024-01-03 11:22:56 +00008897 KeyMintAidlTestBase::dump_Attestations = true;
Shawn Willden7c130392020-12-21 09:58:22 -07008898 } else {
8899 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008900 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008901 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8902 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8903 // be run in emulated environments that don't have the normal bootloader
8904 // interactions.
8905 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8906 }
David Drysdale9f5c0c52022-11-03 15:10:16 +00008907 if (std::string(argv[i]) == "--keyblob_dir") {
8908 if (i + 1 >= argc) {
8909 std::cerr << "Missing argument for --keyblob_dir\n";
8910 return 1;
8911 }
David Drysdale77a86d82024-01-03 11:22:56 +00008912 KeyMintAidlTestBase::keyblob_dir = std::string(argv[i + 1]);
David Drysdale9f5c0c52022-11-03 15:10:16 +00008913 ++i;
8914 }
Tommy Chiu025f3c52023-05-15 06:23:44 +00008915 if (std::string(argv[i]) == "--expect_upgrade") {
8916 if (i + 1 >= argc) {
8917 std::cerr << "Missing argument for --expect_upgrade\n";
8918 return 1;
8919 }
8920 std::string arg = argv[i + 1];
David Drysdale77a86d82024-01-03 11:22:56 +00008921 KeyMintAidlTestBase::expect_upgrade =
8922 arg == "yes" ? true
8923 : (arg == "no" ? false : std::optional<bool>(std::nullopt));
8924 if (KeyMintAidlTestBase::expect_upgrade.has_value()) {
8925 std::cout << "expect_upgrade = "
8926 << (KeyMintAidlTestBase::expect_upgrade.value() ? "true" : "false")
8927 << std::endl;
8928 } else {
8929 std::cerr << "Error! Option --expect_upgrade " << arg << " unrecognized"
8930 << std::endl;
8931 }
Tommy Chiu025f3c52023-05-15 06:23:44 +00008932 ++i;
8933 }
Selene Huang31ab4042020-04-29 04:22:39 -07008934 }
8935 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008936 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008937}