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