blob: c6b8906af9ae40a575d918c919a0c45c4fbe14dd [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>
24
David Drysdale42fe1892021-10-14 14:43:46 +010025#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027#include <openssl/evp.h>
28#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050029#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070030
31#include <cutils/properties.h>
32
David Drysdale4dc01072021-04-01 12:17:35 +010033#include <android/binder_manager.h>
34
35#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080036#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
Shawn Willden08a7e432020-12-11 13:05:27 +000038#include <keymint_support/key_param_output.h>
39#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070040
41#include "KeyMintAidlTestBase.h"
42
Janis Danisevskis24c04702020-12-16 18:28:39 -080043using aidl::android::hardware::security::keymint::AuthorizationSet;
44using aidl::android::hardware::security::keymint::KeyCharacteristics;
45using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070046
Selene Huang31ab4042020-04-29 04:22:39 -070047namespace std {
48
Janis Danisevskis24c04702020-12-16 18:28:39 -080049using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070050
51template <>
52struct std::equal_to<KeyCharacteristics> {
53 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070054 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070055
Shawn Willden7f424372021-01-10 18:06:50 -070056 // this isn't very efficient. Oh, well.
57 AuthorizationSet a_auths(a.authorizations);
58 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070059
Shawn Willden7f424372021-01-10 18:06:50 -070060 a_auths.Sort();
61 b_auths.Sort();
62
63 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070064 }
65};
66
67} // namespace std
68
Janis Danisevskis24c04702020-12-16 18:28:39 -080069namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000070
Selene Huang31ab4042020-04-29 04:22:39 -070071namespace {
72
David Drysdalefeab5d92022-01-06 15:46:23 +000073// Maximum supported Ed25519 message size.
74const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
75
David Drysdaledbbbe2e2021-12-02 07:44:23 +000076// Whether to check that BOOT_PATCHLEVEL is populated.
77bool check_boot_pl = true;
78
Seth Moore7a55ae32021-06-23 14:28:11 -070079// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000080// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070081// is a small (roughly 1/256) chance that corrupting ciphertext still results
82// in valid PKCS7 padding.
83constexpr size_t kMaxPaddingCorruptionRetries = 8;
84
Selene Huang31ab4042020-04-29 04:22:39 -070085template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000086bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
87 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080089 if (auto p = authorizationValue(ttag, param)) {
90 return *p == expected_value;
91 }
92 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070093 });
94 return (it != set.end());
95}
96
97template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000098bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070099 auto it = std::find_if(set.begin(), set.end(),
100 [&](const KeyParameter& param) { return param.tag == tag; });
101 return (it != set.end());
102}
103
104constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
108 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
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
121string hex2str(string a) {
122 string b;
123 size_t num = a.size() / 2;
124 b.resize(num);
125 for (size_t i = 0; i < num; i++) {
126 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
127 }
128 return b;
129}
130
David Drysdaled2cc8c22021-04-15 13:29:45 +0100131string rsa_key = hex2str(
132 // RFC 5208 s5
133 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
134 "020100" // INTEGER length 1 value 0x00 (version)
135 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
136 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
137 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
138 "0500" // NULL (parameters)
139 // } end SEQUENCE (AlgorithmIdentifier)
140 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
141 // RFC 8017 A.1.2
142 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
143 "020100" // INTEGER length 1 value 0x00 (version)
144 "028181" // INTEGER length 0x81 value (modulus) ...
145 "00c6095409047d8634812d5a218176e4"
146 "5c41d60a75b13901f234226cffe77652"
147 "1c5a77b9e389417b71c0b6a44d13afe4"
148 "e4a2805d46c9da2935adb1ff0c1f24ea"
149 "06e62b20d776430a4d435157233c6f91"
150 "6783c30e310fcbd89b85c2d567711697"
151 "85ac12bca244abda72bfb19fc44d27c8"
152 "1e1d92de284f4061edfd99280745ea6d"
153 "25"
154 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
155 "028180" // INTEGER length 0x80 (privateExponent) value...
156 "1be0f04d9cae3718691f035338308e91"
157 "564b55899ffb5084d2460e6630257e05"
158 "b3ceab02972dfabcd6ce5f6ee2589eb6"
159 "7911ed0fac16e43a444b8c861e544a05"
160 "93365772f8baf6b22fc9e3c5f1024b06"
161 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
162 "ace7240290bef16c0b3f7f3cdd64ce3a"
163 "b5912cf6e32f39ab188358afcccd8081"
164 "0241" // INTEGER length 0x41 (prime1)
165 "00e4b49ef50f765d3b24dde01aceaaf1"
166 "30f2c76670a91a61ae08af497b4a82be"
167 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
168 "8c92bfab137fba2285227b83c342ff7c"
169 "55"
170 "0241" // INTEGER length 0x41 (prime2)
171 "00ddabb5839c4c7f6bf3d4183231f005"
172 "b31aa58affdda5c79e4cce217f6bc930"
173 "dbe563d480706c24e9ebfcab28a6cdef"
174 "d324b77e1bf7251b709092c24ff501fd"
175 "91"
176 "0240" // INTEGER length 0x40 (exponent1)
177 "23d4340eda3445d8cd26c14411da6fdc"
178 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
179 "842c1d280405bc2f6c1bea214a1d742a"
180 "b996b35b63a82a5e470fa88dbf823cdd"
181 "0240" // INTEGER length 0x40 (exponent2)
182 "1b7b57449ad30d1518249a5f56bb9829"
183 "4d4b6ac12ffc86940497a5a5837a6cf9"
184 "46262b494526d328c11e1126380fde04"
185 "c24f916dec250892db09a6d77cdba351"
186 "0240" // INTEGER length 0x40 (coefficient)
187 "7762cd8f4d050da56bd591adb515d24d"
188 "7ccd32cca0d05f866d583514bd7324d5"
189 "f33645e8ed8b4a1cb3cc4a1d67987399"
190 "f2a09f5b3fb68c88d5e5d90ac33492d6"
191 // } end SEQUENCE (PrivateKey)
192 // } end SEQUENCE (PrivateKeyInfo)
193);
Selene Huang31ab4042020-04-29 04:22:39 -0700194
Selene Huange5727e62021-04-13 22:41:20 -0700195/*
196 * DER-encoded PKCS#8 format RSA key. Generated using:
197 *
198 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
199 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100200string rsa_2048_key = hex2str(
201 // RFC 5208 s5
202 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
203 "020100" // INTEGER length 1 value 0x00 (version)
204 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
205 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
206 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
207 "0500" // NULL (parameters)
208 // } end SEQUENCE (AlgorithmIdentifier)
209 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
210 // RFC 8017 A.1.2
211 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
212 "020100" // INTEGER length 1 value 0x00 (version)
213 "02820101" // INTEGER length 0x101 value (modulus) ...
214 "00BEBC342B56D443B1299F9A6A7056E8"
215 "0A897E318476A5A18029E63B2ED739A6"
216 "1791D339F58DC763D9D14911F2EDEC38"
217 "3DEE11F6319B44510E7A3ECD9B79B973"
218 "82E49500ACF8117DC89CAF0E621F7775"
219 "6554A2FD4664BFE7AB8B59AB48340DBF"
220 "A27B93B5A81F6ECDEB02D0759307128D"
221 "F3E3BAD4055C8B840216DFAA5700670E"
222 "6C5126F0962FCB70FF308F25049164CC"
223 "F76CC2DA66A7DD9A81A714C2809D6918"
224 "6133D29D84568E892B6FFBF3199BDB14"
225 "383EE224407F190358F111A949552ABA"
226 "6714227D1BD7F6B20DD0CB88F9467B71"
227 "9339F33BFF35B3870B3F62204E4286B0"
228 "948EA348B524544B5F9838F29EE643B0"
229 "79EEF8A713B220D7806924CDF7295070"
230 "C5"
231 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
232 "02820100" // INTEGER length 0x100 (privateExponent) value...
233 "69F377F35F2F584EF075353CCD1CA997"
234 "38DB3DBC7C7FF35F9366CE176DFD1B13"
235 "5AB10030344ABF5FBECF1D4659FDEF1C"
236 "0FC430834BE1BE3911951377BB3D563A"
237 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
238 "2686C7B4B3C09A7B8354133E6F93F790"
239 "D59EAEB92E84C9A4339302CCE28FDF04"
240 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
241 "6AB706645BF074A4E4090D06FB163124"
242 "365FD5EE7A20D350E9958CC30D91326E"
243 "1B292E9EF5DB408EC42DAF737D201497"
244 "04D0A678A0FB5B5446863B099228A352"
245 "D604BA8091A164D01D5AB05397C71EAD"
246 "20BE2A08FC528FE442817809C787FEE4"
247 "AB97F97B9130D022153EDC6EB6CBE7B0"
248 "F8E3473F2E901209B5DB10F93604DB01"
249 "028181" // INTEGER length 0x81 (prime1)
250 "00E83C0998214941EA4F9293F1B77E2E"
251 "99E6CF305FAF358238E126124FEAF2EB"
252 "9724B2EA7B78E6032343821A80E55D1D"
253 "88FB12D220C3F41A56142FEC85796D19"
254 "17F1E8C774F142B67D3D6E7B7E6B4383"
255 "E94DB5929089DBB346D5BDAB40CC2D96"
256 "EE0409475E175C63BF78CFD744136740"
257 "838127EA723FF3FE7FA368C1311B4A4E"
258 "05"
259 "028181" // INTEGER length 0x81 (prime2)
260 "00D240FCC0F5D7715CDE21CB2DC86EA1"
261 "46132EA3B06F61FF2AF54BF38473F59D"
262 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
263 "B1B58C39F95E4798CCBB43E83D0119AC"
264 "F532F359CA743C85199F0286610E2009"
265 "97D7312917179AC9B67558773212EC96"
266 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
267 "94D94E066A0900B7B70E82A44FB30053"
268 "C1"
269 "028181" // INTEGER length 0x81 (exponent1)
270 "00AD15DA1CBD6A492B66851BA8C316D3"
271 "8AB700E2CFDDD926A658003513C54BAA"
272 "152B30021D667D20078F500F8AD3E7F3"
273 "945D74A891ED1A28EAD0FEEAEC8C14A8"
274 "E834CF46A13D1378C99D18940823CFDD"
275 "27EC5810D59339E0C34198AC638E09C8"
276 "7CBB1B634A9864AE9F4D5EB2D53514F6"
277 "7B4CAEC048C8AB849A02E397618F3271"
278 "35"
279 "028180" // INTEGER length 0x80 (exponent2)
280 "1FA2C1A5331880A92D8F3E281C617108"
281 "BF38244F16E352E69ED417C7153F9EC3"
282 "18F211839C643DCF8B4DD67CE2AC312E"
283 "95178D5D952F06B1BF779F4916924B70"
284 "F582A23F11304E02A5E7565AE22A35E7"
285 "4FECC8B6FDC93F92A1A37703E4CF0E63"
286 "783BD02EB716A7ECBBFA606B10B74D01"
287 "579522E7EF84D91FC522292108D902C1"
288 "028180" // INTEGER length 0x80 (coefficient)
289 "796FE3825F9DCC85DF22D58690065D93"
290 "898ACD65C087BEA8DA3A63BF4549B795"
291 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
292 "0D74F40DED8E1102C52152A31B6165F8"
293 "3A6722AECFCC35A493D7634664B888A0"
294 "8D3EB034F12EA28BFEE346E205D33482"
295 "7F778B16ED40872BD29FCB36536B6E93"
296 "FFB06778696B4A9D81BB0A9423E63DE5"
297 // } end SEQUENCE (PrivateKey)
298 // } end SEQUENCE (PrivateKeyInfo)
299);
Selene Huange5727e62021-04-13 22:41:20 -0700300
David Drysdaled2cc8c22021-04-15 13:29:45 +0100301string ec_256_key = hex2str(
302 // RFC 5208 s5
303 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
304 "020100" // INTEGER length 1 value 0 (version)
305 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
306 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
307 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
308 "0608" // OBJECT IDENTIFIER length 8 (param)
309 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
310 // } end SEQUENCE (AlgorithmIdentifier)
311 "046d" // OCTET STRING length 0x6d (privateKey) holding...
312 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
313 "020101" // INTEGER length 1 value 1 (version)
314 "0420" // OCTET STRING length 0x20 (privateKey)
315 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
316 "941eed09366bc03299986481f3a4d859"
317 "a144" // TAG [1] len 0x44 (publicKey) {
318 "03420004bf85d7720d07c25461683bc6"
319 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
320 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
321 "bcc41c6eb00083cf3376d11fd44949e0"
322 "b2183bfe"
323 // } end SEQUENCE (ECPrivateKey)
324 // } end SEQUENCE (PrivateKeyInfo)
325);
Selene Huang31ab4042020-04-29 04:22:39 -0700326
David Drysdaled2cc8c22021-04-15 13:29:45 +0100327string ec_521_key = hex2str(
328 // RFC 5208 s5
329 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
330 "020100" // INTEGER length 1 value 0 (version)
331 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
332 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
333 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
334 "0605" // OBJECT IDENTIFIER length 5 (param)
335 "2B81040023" // 1.3.132.0.35 (secp521r1)
336 // } end SEQUENCE (AlgorithmIdentifier)
337 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
338 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
339 "020101" // INTEGER length 1 value 1 (version)
340 "0442" // OCTET STRING length 0x42 (privateKey)
341 "0011458C586DB5DAA92AFAB03F4FE46A"
342 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
343 "9D18D7D08B5BCFA0E53C75B064AD51C4"
344 "49BAE0258D54B94B1E885DED08ED4FB2"
345 "5CE9"
346 "A18189" // TAG [1] len 0x89 (publicKey) {
347 "03818600040149EC11C6DF0FA122C6A9"
348 "AFD9754A4FA9513A627CA329E349535A"
349 "5629875A8ADFBE27DCB932C051986377"
350 "108D054C28C6F39B6F2C9AF81802F9F3"
351 "26B842FF2E5F3C00AB7635CFB36157FC"
352 "0882D574A10D839C1A0C049DC5E0D775"
353 "E2EE50671A208431BB45E78E70BEFE93"
354 "0DB34818EE4D5C26259F5C6B8E28A652"
355 "950F9F88D7B4B2C9D9"
356 // } end SEQUENCE (ECPrivateKey)
357 // } end SEQUENCE (PrivateKeyInfo)
358);
Selene Huang31ab4042020-04-29 04:22:39 -0700359
David Drysdaled2cc8c22021-04-15 13:29:45 +0100360string ec_256_key_rfc5915 = hex2str(
361 // RFC 5208 s5
362 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
363 "020100" // INTEGER length 1 value 0 (version)
364 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
365 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
366 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
367 "0608" // OBJECT IDENTIFIER length 8 (param)
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end SEQUENCE (AlgorithmIdentifier)
370 "0479" // OCTET STRING length 0x79 (privateKey) holding...
371 // RFC 5915 s3
372 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
373 "020101" // INTEGER length 1 value 1 (version)
374 "0420" // OCTET STRING length 0x42 (privateKey)
375 "782370a8c8ce5537baadd04dcff079c8"
376 "158cfa9c67b818b38e8d21c9fa750c1d"
377 "a00a" // TAG [0] length 0xa (parameters)
378 "0608" // OBJECT IDENTIFIER length 8
379 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
380 // } end TAG [0]
381 "a144" // TAG [1] length 0x44 (publicKey) {
382 "0342" // BIT STRING length 0x42
383 "00" // no pad bits
384 "04e2cc561ee701da0ad0ef0d176bb0c9"
385 "19d42e79c393fdc1bd6c4010d85cf2cf"
386 "8e68c905464666f98dad4f01573ba810"
387 "78b3428570a439ba3229fbc026c55068"
388 "2f"
389 // } end SEQUENCE (ECPrivateKey)
390 // } end SEQUENCE (PrivateKeyInfo)
391);
Selene Huang31ab4042020-04-29 04:22:39 -0700392
David Drysdaled2cc8c22021-04-15 13:29:45 +0100393string ec_256_key_sec1 = hex2str(
394 // RFC 5208 s5
395 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
396 "020100" // INTEGER length 1 value 0 (version)
397 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
398 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
399 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
400 "0608" // OBJECT IDENTIFIER length 8 (param)
401 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
402 // } end SEQUENCE (AlgorithmIdentifier)
403 "046d" // OCTET STRING length 0x6d (privateKey) holding...
404 // SEC1-v2 C.4
405 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
406 "020101" // INTEGER length 1 value 0x01 (version)
407 "0420" // OCTET STRING length 0x20 (privateKey)
408 "782370a8c8ce5537baadd04dcff079c8"
409 "158cfa9c67b818b38e8d21c9fa750c1d"
410 "a144" // TAG [1] length 0x44 (publicKey) {
411 "0342" // BIT STRING length 0x42
412 "00" // no pad bits
413 "04e2cc561ee701da0ad0ef0d176bb0c9"
414 "19d42e79c393fdc1bd6c4010d85cf2cf"
415 "8e68c905464666f98dad4f01573ba810"
416 "78b3428570a439ba3229fbc026c55068"
417 "2f"
418 // } end TAG [1] (publicKey)
419 // } end SEQUENCE (PrivateKeyInfo)
420);
Selene Huang31ab4042020-04-29 04:22:39 -0700421
David Drysdale42fe1892021-10-14 14:43:46 +0100422/**
423 * Ed25519 key pair generated as follows:
424 * ```
425 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
426 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
427 * Generating a ED25519 private key writing new private key to
428 * 'ed25519_priv.key'
429 * -----
430 * % cat ed25519_priv.key
431 * -----BEGIN PRIVATE KEY-----
432 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
433 * -----END PRIVATE KEY-----
434 * % der2ascii -pem -i ed25519_priv.key
435 * SEQUENCE {
436 * INTEGER { 0 }
437 * SEQUENCE {
438 * # ed25519
439 * OBJECT_IDENTIFIER { 1.3.101.112 }
440 * }
441 * OCTET_STRING {
442 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
443 * }
444 * }
445 * % cat ed25519.pem
446 * -----BEGIN CERTIFICATE-----
447 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
448 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
449 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
450 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
451 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
452 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
453 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
454 * -----END CERTIFICATE-----
455 * % openssl x509 -in ed25519.pem -text -noout
456 * Certificate:
457 * Data:
458 * Version: 3 (0x2)
459 * Serial Number:
460 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
461 * Signature Algorithm: ED25519
462 * Issuer: CN = fake.ed25519.com
463 * Validity
464 * Not Before: Oct 20 08:27:42 2021 GMT
465 * Not After : Sep 20 08:27:42 2023 GMT
466 * Subject: CN = fake.ed25519.com
467 * Subject Public Key Info:
468 * Public Key Algorithm: ED25519
469 * ED25519 Public-Key:
470 * pub:
471 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
472 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
473 * 56:91
474 * X509v3 extensions:
475 * X509v3 Subject Key Identifier:
476 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
477 * X509v3 Authority Key Identifier:
478 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
479 *
480 * X509v3 Basic Constraints: critical
481 * CA:TRUE
482 * Signature Algorithm: ED25519
483 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
484 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
485 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
486 * e7:07:32:60:32:8d:bb:eb:f6:0f
487 * ```
488 */
489string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
490string ed25519_pkcs8_key = hex2str(
491 // RFC 5208 s5
492 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
493 "0201" // INTEGER length 1 (Version)
494 "00" // version 0
495 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
496 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
497 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
498 // } end SEQUENCE (AlgorithmIdentifier)
499 "0422" // OCTET STRING length 0x22 (PrivateKey)
500 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
501 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
502 // } end SEQUENCE (PrivateKeyInfo)
503);
504string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
505
506/**
507 * X25519 key pair generated as follows:
508 * ```
509 * % openssl genpkey -algorithm X25519 > x25519_priv.key
510 * % cat x25519_priv.key
511 * -----BEGIN PRIVATE KEY-----
512 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
513 * -----END PRIVATE KEY-----
514 * % der2ascii -pem -i x25519_priv.key
515 * SEQUENCE {
516 * INTEGER { 0 }
517 * SEQUENCE {
518 * # x25519
519 * OBJECT_IDENTIFIER { 1.3.101.110 }
520 * }
521 * OCTET_STRING {
522 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
523 * }
524 * }
525 * ```
526 */
527
528string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
529string x25519_pkcs8_key = hex2str(
530 // RFC 5208 s5
531 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
532 "0201" // INTEGER length 1 (Version)
533 "00" // version 0
534 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
535 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
536 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
537 "0422" // OCTET STRING length 0x22 (PrivateKey)
538 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
539 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
540string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
541
Selene Huang31ab4042020-04-29 04:22:39 -0700542struct RSA_Delete {
543 void operator()(RSA* p) { RSA_free(p); }
544};
545
Selene Huang31ab4042020-04-29 04:22:39 -0700546std::string make_string(const uint8_t* data, size_t length) {
547 return std::string(reinterpret_cast<const char*>(data), length);
548}
549
550template <size_t N>
551std::string make_string(const uint8_t (&a)[N]) {
552 return make_string(a, N);
553}
554
555class AidlBuf : public vector<uint8_t> {
556 typedef vector<uint8_t> super;
557
558 public:
559 AidlBuf() {}
560 AidlBuf(const super& other) : super(other) {}
561 AidlBuf(super&& other) : super(std::move(other)) {}
562 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
563
564 AidlBuf& operator=(const super& other) {
565 super::operator=(other);
566 return *this;
567 }
568
569 AidlBuf& operator=(super&& other) {
570 super::operator=(std::move(other));
571 return *this;
572 }
573
574 AidlBuf& operator=(const string& other) {
575 resize(other.size());
576 for (size_t i = 0; i < other.size(); ++i) {
577 (*this)[i] = static_cast<uint8_t>(other[i]);
578 }
579 return *this;
580 }
581
582 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
583};
584
David Drysdale4dc01072021-04-01 12:17:35 +0100585string device_suffix(const string& name) {
586 size_t pos = name.find('/');
587 if (pos == string::npos) {
588 return name;
589 }
590 return name.substr(pos + 1);
591}
592
593bool matching_rp_instance(const string& km_name,
594 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
595 string km_suffix = device_suffix(km_name);
596
597 vector<string> rp_names =
598 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
599 for (const string& rp_name : rp_names) {
600 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
601 // KeyMint instance, assume they match.
602 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
603 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
604 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
605 return true;
606 }
607 }
608 return false;
609}
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));
697
698 EXPECT_GT(key_blob.size(), 0U);
699 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100700 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000701
702 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
703
704 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
705 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
706 << "Key size " << key_size << "missing";
707
708 CheckedDeleteKey(&key_blob);
709 }
710 }
711 }
712}
713
714/*
715 * NewKeyGenerationTest.AesInvalidSize
716 *
717 * Verifies that specifying an invalid key size for AES key generation returns
718 * UNSUPPORTED_KEY_SIZE.
719 */
720TEST_P(NewKeyGenerationTest, AesInvalidSize) {
721 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
722 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
723 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
724 SCOPED_TRACE(testing::Message()
725 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
726 vector<uint8_t> key_blob;
727 vector<KeyCharacteristics> key_characteristics;
728 auto builder = AuthorizationSetBuilder()
729 .AesEncryptionKey(key_size)
730 .BlockMode(block_mode)
731 .Padding(padding_mode)
732 .SetDefaultValidity();
733 if (block_mode == BlockMode::GCM) {
734 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
735 }
736 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
737 GenerateKey(builder, &key_blob, &key_characteristics));
738 }
739 }
740 }
741
742 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
743 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100744 SCOPED_TRACE(testing::Message() << "AES-unknown-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000745 vector<uint8_t> key_blob;
746 vector<KeyCharacteristics> key_characteristics;
747 // No key size specified
748 auto builder = AuthorizationSetBuilder()
749 .Authorization(TAG_ALGORITHM, Algorithm::AES)
750 .BlockMode(block_mode)
751 .Padding(padding_mode)
752 .SetDefaultValidity();
753 if (block_mode == BlockMode::GCM) {
754 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
755 }
756 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
757 GenerateKey(builder, &key_blob, &key_characteristics));
758 }
759 }
760}
761
762/*
763 * NewKeyGenerationTest.AesInvalidPadding
764 *
765 * Verifies that specifying an invalid padding on AES keys gives a failure
766 * somewhere along the way.
767 */
768TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
769 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
770 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
771 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
772 SCOPED_TRACE(testing::Message()
773 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000774 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800775 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000776 .AesEncryptionKey(key_size)
777 .BlockMode(block_mode)
778 .Padding(padding_mode)
779 .SetDefaultValidity();
780 if (block_mode == BlockMode::GCM) {
781 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
782 }
783
Tommy Chiu3950b452021-05-03 22:01:46 +0800784 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000785 if (result == ErrorCode::OK) {
786 // Key creation was OK but has generated a key that cannot be used.
787 auto params =
788 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800789 if (block_mode == BlockMode::GCM) {
790 params.Authorization(TAG_MAC_LENGTH, 128);
791 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000792 auto result = Begin(KeyPurpose::ENCRYPT, params);
793 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100794 result == ErrorCode::INVALID_KEY_BLOB)
795 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000796 } else {
797 // The KeyMint implementation detected that the generated key
798 // is unusable.
799 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
800 }
801 }
802 }
803 }
804}
805
806/*
807 * NewKeyGenerationTest.AesGcmMissingMinMac
808 *
809 * Verifies that specifying an invalid key size for AES key generation returns
810 * UNSUPPORTED_KEY_SIZE.
811 */
812TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
813 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
814 BlockMode block_mode = BlockMode::GCM;
815 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
816 SCOPED_TRACE(testing::Message()
817 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
818 vector<uint8_t> key_blob;
819 vector<KeyCharacteristics> key_characteristics;
820 // No MIN_MAC_LENGTH provided.
821 auto builder = AuthorizationSetBuilder()
822 .AesEncryptionKey(key_size)
823 .BlockMode(block_mode)
824 .Padding(padding_mode)
825 .SetDefaultValidity();
826 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
827 GenerateKey(builder, &key_blob, &key_characteristics));
828 }
829 }
830}
831
832/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100833 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
834 *
835 * Verifies that specifying an invalid min MAC size for AES key generation returns
836 * UNSUPPORTED_MIN_MAC_LENGTH.
837 */
838TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
839 for (size_t min_mac_len : {88, 136}) {
840 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
841 BlockMode block_mode = BlockMode::GCM;
842 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
843 SCOPED_TRACE(testing::Message()
844 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
845 vector<uint8_t> key_blob;
846 vector<KeyCharacteristics> key_characteristics;
847 auto builder = AuthorizationSetBuilder()
848 .AesEncryptionKey(key_size)
849 .BlockMode(block_mode)
850 .Padding(padding_mode)
851 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
852 .SetDefaultValidity();
853 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
854 GenerateKey(builder, &key_blob, &key_characteristics));
855 }
856 }
857 }
858}
859
860/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000861 * NewKeyGenerationTest.TripleDes
862 *
863 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
864 * have correct characteristics.
865 */
866TEST_P(NewKeyGenerationTest, TripleDes) {
867 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
868 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
869 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
870 SCOPED_TRACE(testing::Message()
871 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
872 vector<uint8_t> key_blob;
873 vector<KeyCharacteristics> key_characteristics;
874 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
875 .TripleDesEncryptionKey(key_size)
876 .BlockMode(block_mode)
877 .Padding(padding_mode)
878 .Authorization(TAG_NO_AUTH_REQUIRED)
879 .SetDefaultValidity(),
880 &key_blob, &key_characteristics));
881
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";
891
892 CheckedDeleteKey(&key_blob);
893 }
894 }
895 }
896}
897
898/*
899 * NewKeyGenerationTest.TripleDesWithAttestation
900 *
901 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
902 * have correct characteristics.
903 *
904 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
905 * put in a certificate) but which isn't an error.
906 */
907TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
908 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
909 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
910 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
911 SCOPED_TRACE(testing::Message()
912 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
913
914 auto challenge = "hello";
915 auto app_id = "foo";
916
917 vector<uint8_t> key_blob;
918 vector<KeyCharacteristics> key_characteristics;
919 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
920 .TripleDesEncryptionKey(key_size)
921 .BlockMode(block_mode)
922 .Padding(padding_mode)
923 .Authorization(TAG_NO_AUTH_REQUIRED)
924 .AttestationChallenge(challenge)
925 .AttestationApplicationId(app_id)
926 .SetDefaultValidity(),
927 &key_blob, &key_characteristics));
928
929 EXPECT_GT(key_blob.size(), 0U);
930 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100931 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000932
933 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
934
935 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
936 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
937 << "Key size " << key_size << "missing";
938
939 CheckedDeleteKey(&key_blob);
940 }
941 }
942 }
943}
944
945/*
946 * NewKeyGenerationTest.TripleDesInvalidSize
947 *
948 * Verifies that specifying an invalid key size for 3-DES key generation returns
949 * UNSUPPORTED_KEY_SIZE.
950 */
951TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
952 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
953 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
954 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
955 SCOPED_TRACE(testing::Message()
956 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
957 vector<uint8_t> key_blob;
958 vector<KeyCharacteristics> key_characteristics;
959 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
960 GenerateKey(AuthorizationSetBuilder()
961 .TripleDesEncryptionKey(key_size)
962 .BlockMode(block_mode)
963 .Padding(padding_mode)
964 .Authorization(TAG_NO_AUTH_REQUIRED)
965 .SetDefaultValidity(),
966 &key_blob, &key_characteristics));
967 }
968 }
969 }
970
971 // Omitting the key size fails.
972 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
973 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
974 SCOPED_TRACE(testing::Message()
975 << "3DES-default-" << block_mode << "-" << padding_mode);
976 vector<uint8_t> key_blob;
977 vector<KeyCharacteristics> key_characteristics;
978 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
979 GenerateKey(AuthorizationSetBuilder()
980 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
981 .BlockMode(block_mode)
982 .Padding(padding_mode)
983 .Authorization(TAG_NO_AUTH_REQUIRED)
984 .SetDefaultValidity(),
985 &key_blob, &key_characteristics));
986 }
987 }
988}
989
990/*
Selene Huang31ab4042020-04-29 04:22:39 -0700991 * NewKeyGenerationTest.Rsa
992 *
993 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
994 * have correct characteristics.
995 */
996TEST_P(NewKeyGenerationTest, Rsa) {
997 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100998 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -0700999 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001000 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1002 .RsaSigningKey(key_size, 65537)
1003 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001004 .Padding(PaddingMode::NONE)
1005 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001006 &key_blob, &key_characteristics));
1007
1008 ASSERT_GT(key_blob.size(), 0U);
1009 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001010 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001011
Shawn Willden7f424372021-01-10 18:06:50 -07001012 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001013
1014 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1015 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1016 << "Key size " << key_size << "missing";
1017 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1018
1019 CheckedDeleteKey(&key_blob);
1020 }
1021}
1022
1023/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001024 * NewKeyGenerationTest.RsaWithMissingValidity
1025 *
1026 * Verifies that keymint returns an error while generating asymmetric key
1027 * without providing NOT_BEFORE and NOT_AFTER parameters.
1028 */
1029TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
Seth Moore7dc1fda2022-12-12 16:56:20 -08001030 if (AidlVersion() < 3) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001031 /*
1032 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1033 * specified for asymmetric key generation. However, this was not
1034 * checked at the time so we can only be strict about checking this for
1035 * implementations of KeyMint version 2 and above.
1036 */
1037 GTEST_SKIP() << "Validity strict since KeyMint v2";
1038 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001039 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1040 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1041 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1042
1043 vector<uint8_t> key_blob;
1044 vector<KeyCharacteristics> key_characteristics;
1045 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1046 GenerateKey(AuthorizationSetBuilder()
1047 .RsaSigningKey(2048, 65537)
1048 .Digest(Digest::NONE)
1049 .Padding(PaddingMode::NONE)
1050 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1051 kUndefinedExpirationDateTime),
1052 &key_blob, &key_characteristics));
1053
1054 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1055 GenerateKey(AuthorizationSetBuilder()
1056 .RsaSigningKey(2048, 65537)
1057 .Digest(Digest::NONE)
1058 .Padding(PaddingMode::NONE)
1059 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1060 &key_blob, &key_characteristics));
1061}
1062
1063/*
Qi Wud22ec842020-11-26 13:27:53 +08001064 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001065 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001066 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1067 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001068 */
1069TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001070 auto challenge = "hello";
1071 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001072
Selene Huang6e46f142021-04-20 19:20:11 -07001073 auto subject = "cert subj 2";
1074 vector<uint8_t> subject_der(make_name_from_str(subject));
1075
1076 uint64_t serial_int = 66;
1077 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1078
Selene Huang4f64c222021-04-13 19:54:36 -07001079 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001080 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001081 vector<uint8_t> key_blob;
1082 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001083 auto builder = AuthorizationSetBuilder()
1084 .RsaSigningKey(key_size, 65537)
1085 .Digest(Digest::NONE)
1086 .Padding(PaddingMode::NONE)
1087 .AttestationChallenge(challenge)
1088 .AttestationApplicationId(app_id)
1089 .Authorization(TAG_NO_AUTH_REQUIRED)
1090 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1091 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1092 .SetDefaultValidity();
1093
1094 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001095 // Strongbox may not support factory provisioned attestation key.
1096 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001097 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1098 result = GenerateKeyWithSelfSignedAttestKey(
1099 AuthorizationSetBuilder()
1100 .RsaKey(key_size, 65537)
1101 .AttestKey()
1102 .SetDefaultValidity(), /* attest key params */
1103 builder, &key_blob, &key_characteristics);
1104 }
subrahmanyaman05642492022-02-05 07:10:56 +00001105 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001106 ASSERT_EQ(ErrorCode::OK, result);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001107 ASSERT_GT(key_blob.size(), 0U);
1108 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001109 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001110
1111 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1112
1113 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1114 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1115 << "Key size " << key_size << "missing";
1116 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1117
David Drysdalea8a888e2022-06-08 12:43:56 +01001118 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001119 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001120 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001121
1122 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1123 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001124 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001125 sw_enforced, hw_enforced, SecLevel(),
1126 cert_chain_[0].encodedCertificate));
1127
1128 CheckedDeleteKey(&key_blob);
1129 }
1130}
1131
1132/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001133 * NewKeyGenerationTest.RsaWithRkpAttestation
David Drysdale4dc01072021-04-01 12:17:35 +01001134 *
Seth Moore7dc1fda2022-12-12 16:56:20 -08001135 * Verifies that keymint can generate all required RSA key sizes using an attestation key
David Drysdale4dc01072021-04-01 12:17:35 +01001136 * that has been generated using an associate IRemotelyProvisionedComponent.
1137 */
Seth Moore7dc1fda2022-12-12 16:56:20 -08001138TEST_P(NewKeyGenerationTest, RsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001139 if (!IsRkpSupportRequired()) {
1140 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001141 }
1142
David Drysdale4dc01072021-04-01 12:17:35 +01001143 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1144 // instance.
1145 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1146 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1147 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1148
1149 // Generate a P-256 keypair to use as an attestation key.
1150 MacedPublicKey macedPubKey;
1151 std::vector<uint8_t> privateKeyBlob;
1152 auto status =
1153 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1154 ASSERT_TRUE(status.isOk());
1155 vector<uint8_t> coseKeyData;
1156 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1157
1158 AttestationKey attestation_key;
1159 attestation_key.keyBlob = std::move(privateKeyBlob);
1160 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1161
1162 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001163 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdale4dc01072021-04-01 12:17:35 +01001164 auto challenge = "hello";
1165 auto app_id = "foo";
1166
1167 vector<uint8_t> key_blob;
1168 vector<KeyCharacteristics> key_characteristics;
1169 ASSERT_EQ(ErrorCode::OK,
1170 GenerateKey(AuthorizationSetBuilder()
1171 .RsaSigningKey(key_size, 65537)
1172 .Digest(Digest::NONE)
1173 .Padding(PaddingMode::NONE)
1174 .AttestationChallenge(challenge)
1175 .AttestationApplicationId(app_id)
1176 .Authorization(TAG_NO_AUTH_REQUIRED)
1177 .SetDefaultValidity(),
1178 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1179
1180 ASSERT_GT(key_blob.size(), 0U);
1181 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001182 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001183
1184 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1185
1186 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1187 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1188 << "Key size " << key_size << "missing";
1189 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1190
1191 // Attestation by itself is not valid (last entry is not self-signed).
1192 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1193
1194 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001195 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001196 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1197 ASSERT_TRUE(key_cert.get());
1198 EVP_PKEY_Ptr signing_pubkey;
1199 p256_pub_key(coseKeyData, &signing_pubkey);
1200 ASSERT_TRUE(signing_pubkey.get());
1201
1202 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1203 << "Verification of attested certificate failed "
1204 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1205
1206 CheckedDeleteKey(&key_blob);
1207 }
1208}
1209
1210/*
Seth Moore7dc1fda2022-12-12 16:56:20 -08001211 * NewKeyGenerationTest.EcdsaWithRkpAttestation
1212 *
1213 * Verifies that keymint can generate all required ECDSA key sizes using an attestation key
1214 * that has been generated using an associate IRemotelyProvisionedComponent.
1215 */
1216TEST_P(NewKeyGenerationTest, EcdsaWithRkpAttestation) {
Seth Moorea12ac742023-03-03 13:40:30 -08001217 if (!IsRkpSupportRequired()) {
1218 GTEST_SKIP() << "RKP support is not required on this platform";
Seth Moore7dc1fda2022-12-12 16:56:20 -08001219 }
1220
1221 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1222 // instance.
1223 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1224 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1225 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1226
1227 // Generate a P-256 keypair to use as an attestation key.
1228 MacedPublicKey macedPubKey;
1229 std::vector<uint8_t> privateKeyBlob;
1230 auto status =
1231 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1232 ASSERT_TRUE(status.isOk());
1233 vector<uint8_t> coseKeyData;
1234 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1235
1236 AttestationKey attestation_key;
1237 attestation_key.keyBlob = std::move(privateKeyBlob);
1238 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1239
1240 for (auto curve : ValidCurves()) {
1241 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
1242 auto challenge = "hello";
1243 auto app_id = "foo";
1244
1245 vector<uint8_t> key_blob;
1246 vector<KeyCharacteristics> key_characteristics;
1247 ASSERT_EQ(ErrorCode::OK,
1248 GenerateKey(AuthorizationSetBuilder()
1249 .EcdsaSigningKey(curve)
1250 .Digest(Digest::NONE)
1251 .AttestationChallenge(challenge)
1252 .AttestationApplicationId(app_id)
1253 .Authorization(TAG_NO_AUTH_REQUIRED)
1254 .SetDefaultValidity(),
1255 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1256
1257 ASSERT_GT(key_blob.size(), 0U);
1258 CheckBaseParams(key_characteristics);
1259 CheckCharacteristics(key_blob, key_characteristics);
1260
1261 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1262
1263 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1264 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1265
1266 // Attestation by itself is not valid (last entry is not self-signed).
1267 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1268
1269 // The signature over the attested key should correspond to the P256 public key.
1270 ASSERT_GT(cert_chain_.size(), 0);
1271 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1272 ASSERT_TRUE(key_cert.get());
1273 EVP_PKEY_Ptr signing_pubkey;
1274 p256_pub_key(coseKeyData, &signing_pubkey);
1275 ASSERT_TRUE(signing_pubkey.get());
1276
1277 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1278 << "Verification of attested certificate failed "
1279 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1280
1281 CheckedDeleteKey(&key_blob);
1282 }
1283}
1284
1285/*
Selene Huang4f64c222021-04-13 19:54:36 -07001286 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1287 *
1288 * Verifies that keymint attestation for RSA encryption keys with challenge and
1289 * app id is also successful.
1290 */
1291TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1292 auto key_size = 2048;
1293 auto challenge = "hello";
1294 auto app_id = "foo";
1295
Selene Huang6e46f142021-04-20 19:20:11 -07001296 auto subject = "subj 2";
1297 vector<uint8_t> subject_der(make_name_from_str(subject));
1298
1299 uint64_t serial_int = 111166;
1300 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1301
Selene Huang4f64c222021-04-13 19:54:36 -07001302 vector<uint8_t> key_blob;
1303 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001304 auto builder = AuthorizationSetBuilder()
1305 .RsaEncryptionKey(key_size, 65537)
1306 .Padding(PaddingMode::NONE)
1307 .AttestationChallenge(challenge)
1308 .AttestationApplicationId(app_id)
1309 .Authorization(TAG_NO_AUTH_REQUIRED)
1310 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1311 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1312 .SetDefaultValidity();
1313
1314 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001315 // Strongbox may not support factory provisioned attestation key.
1316 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001317 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1318 result = GenerateKeyWithSelfSignedAttestKey(
1319 AuthorizationSetBuilder()
1320 .RsaKey(key_size, 65537)
1321 .AttestKey()
1322 .SetDefaultValidity(), /* attest key params */
1323 builder, &key_blob, &key_characteristics);
1324 }
subrahmanyaman05642492022-02-05 07:10:56 +00001325 }
1326 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001327
1328 ASSERT_GT(key_blob.size(), 0U);
1329 AuthorizationSet auths;
1330 for (auto& entry : key_characteristics) {
1331 auths.push_back(AuthorizationSet(entry.authorizations));
1332 }
1333
1334 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1335 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1336
1337 // Verify that App data and ROT are NOT included.
1338 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1339 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1340
1341 // Check that some unexpected tags/values are NOT present.
1342 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1343 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1344
1345 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1346
1347 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1348 ASSERT_TRUE(os_ver);
1349 EXPECT_EQ(*os_ver, os_version());
1350
1351 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1352
1353 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1354 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1355 << "Key size " << key_size << "missing";
1356 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1357
David Drysdalea8a888e2022-06-08 12:43:56 +01001358 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001359 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001360 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001361
1362 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1363 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001364 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001365 sw_enforced, hw_enforced, SecLevel(),
1366 cert_chain_[0].encodedCertificate));
1367
1368 CheckedDeleteKey(&key_blob);
1369}
1370
1371/*
1372 * NewKeyGenerationTest.RsaWithSelfSign
1373 *
1374 * Verifies that attesting to RSA key generation is successful, and returns
1375 * self signed certificate if no challenge is provided. And signing etc
1376 * works as expected.
1377 */
1378TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001379 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1380 vector<uint8_t> subject_der(make_name_from_str(subject));
1381
1382 uint64_t serial_int = 0;
1383 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1384
Selene Huang4f64c222021-04-13 19:54:36 -07001385 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001386 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang4f64c222021-04-13 19:54:36 -07001387 vector<uint8_t> key_blob;
1388 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001389 ASSERT_EQ(ErrorCode::OK,
1390 GenerateKey(AuthorizationSetBuilder()
1391 .RsaSigningKey(key_size, 65537)
1392 .Digest(Digest::NONE)
1393 .Padding(PaddingMode::NONE)
1394 .Authorization(TAG_NO_AUTH_REQUIRED)
1395 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1396 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1397 .SetDefaultValidity(),
1398 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001399
1400 ASSERT_GT(key_blob.size(), 0U);
1401 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001402 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001403
1404 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1405
1406 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1407 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1408 << "Key size " << key_size << "missing";
1409 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1410
David Drysdalea8a888e2022-06-08 12:43:56 +01001411 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001412 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001413 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001414
1415 CheckedDeleteKey(&key_blob);
1416 }
1417}
1418
1419/*
1420 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1421 *
1422 * Verifies that attesting to RSA checks for missing app ID.
1423 */
1424TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1425 auto challenge = "hello";
1426 vector<uint8_t> key_blob;
1427 vector<KeyCharacteristics> key_characteristics;
1428
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001429 auto builder = AuthorizationSetBuilder()
1430 .RsaSigningKey(2048, 65537)
1431 .Digest(Digest::NONE)
1432 .Padding(PaddingMode::NONE)
1433 .AttestationChallenge(challenge)
1434 .Authorization(TAG_NO_AUTH_REQUIRED)
1435 .SetDefaultValidity();
1436
1437 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001438 // Strongbox may not support factory provisioned attestation key.
1439 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001440 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1441 result = GenerateKeyWithSelfSignedAttestKey(
1442 AuthorizationSetBuilder()
1443 .RsaKey(2048, 65537)
1444 .AttestKey()
1445 .SetDefaultValidity(), /* attest key params */
1446 builder, &key_blob, &key_characteristics);
1447 }
subrahmanyaman05642492022-02-05 07:10:56 +00001448 }
1449 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001450}
1451
1452/*
1453 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1454 *
1455 * Verifies that attesting to RSA ignores app id if challenge is missing.
1456 */
1457TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1458 auto key_size = 2048;
1459 auto app_id = "foo";
1460
Selene Huang6e46f142021-04-20 19:20:11 -07001461 auto subject = "cert subj 2";
1462 vector<uint8_t> subject_der(make_name_from_str(subject));
1463
1464 uint64_t serial_int = 1;
1465 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1466
Selene Huang4f64c222021-04-13 19:54:36 -07001467 vector<uint8_t> key_blob;
1468 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001469 ASSERT_EQ(ErrorCode::OK,
1470 GenerateKey(AuthorizationSetBuilder()
1471 .RsaSigningKey(key_size, 65537)
1472 .Digest(Digest::NONE)
1473 .Padding(PaddingMode::NONE)
1474 .AttestationApplicationId(app_id)
1475 .Authorization(TAG_NO_AUTH_REQUIRED)
1476 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1477 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1478 .SetDefaultValidity(),
1479 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001480
1481 ASSERT_GT(key_blob.size(), 0U);
1482 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001483 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001484
1485 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1486
1487 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1488 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1489 << "Key size " << key_size << "missing";
1490 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1491
David Drysdalea8a888e2022-06-08 12:43:56 +01001492 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001493 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001494 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1495 ASSERT_EQ(cert_chain_.size(), 1);
1496
1497 CheckedDeleteKey(&key_blob);
1498}
1499
1500/*
Qi Wud22ec842020-11-26 13:27:53 +08001501 * NewKeyGenerationTest.LimitedUsageRsa
1502 *
1503 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1504 * resulting keys have correct characteristics.
1505 */
1506TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1507 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001508 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wud22ec842020-11-26 13:27:53 +08001509 vector<uint8_t> key_blob;
1510 vector<KeyCharacteristics> key_characteristics;
1511 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1512 .RsaSigningKey(key_size, 65537)
1513 .Digest(Digest::NONE)
1514 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001515 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1516 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001517 &key_blob, &key_characteristics));
1518
1519 ASSERT_GT(key_blob.size(), 0U);
1520 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001521 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001522
1523 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1524
1525 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1526 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1527 << "Key size " << key_size << "missing";
1528 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1529
1530 // Check the usage count limit tag appears in the authorizations.
1531 AuthorizationSet auths;
1532 for (auto& entry : key_characteristics) {
1533 auths.push_back(AuthorizationSet(entry.authorizations));
1534 }
1535 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1536 << "key usage count limit " << 1U << " missing";
1537
1538 CheckedDeleteKey(&key_blob);
1539 }
1540}
1541
1542/*
Qi Wubeefae42021-01-28 23:16:37 +08001543 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1544 *
1545 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1546 * resulting keys have correct characteristics and attestation.
1547 */
1548TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001549 auto challenge = "hello";
1550 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001551
Selene Huang6e46f142021-04-20 19:20:11 -07001552 auto subject = "cert subj 2";
1553 vector<uint8_t> subject_der(make_name_from_str(subject));
1554
1555 uint64_t serial_int = 66;
1556 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1557
Selene Huang4f64c222021-04-13 19:54:36 -07001558 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001559 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wubeefae42021-01-28 23:16:37 +08001560 vector<uint8_t> key_blob;
1561 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001562 auto builder = AuthorizationSetBuilder()
1563 .RsaSigningKey(key_size, 65537)
1564 .Digest(Digest::NONE)
1565 .Padding(PaddingMode::NONE)
1566 .AttestationChallenge(challenge)
1567 .AttestationApplicationId(app_id)
1568 .Authorization(TAG_NO_AUTH_REQUIRED)
1569 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1570 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1571 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1572 .SetDefaultValidity();
1573
1574 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001575 // Strongbox may not support factory provisioned attestation key.
1576 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001577 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1578 result = GenerateKeyWithSelfSignedAttestKey(
1579 AuthorizationSetBuilder()
1580 .RsaKey(key_size, 65537)
1581 .AttestKey()
1582 .SetDefaultValidity(), /* attest key params */
1583 builder, &key_blob, &key_characteristics);
1584 }
subrahmanyaman05642492022-02-05 07:10:56 +00001585 }
1586 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001587
1588 ASSERT_GT(key_blob.size(), 0U);
1589 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001590 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001591
1592 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1593
1594 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1595 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1596 << "Key size " << key_size << "missing";
1597 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1598
1599 // Check the usage count limit tag appears in the authorizations.
1600 AuthorizationSet auths;
1601 for (auto& entry : key_characteristics) {
1602 auths.push_back(AuthorizationSet(entry.authorizations));
1603 }
1604 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1605 << "key usage count limit " << 1U << " missing";
1606
1607 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001608 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001609 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001610 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001611
1612 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1613 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001614 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001615 sw_enforced, hw_enforced, SecLevel(),
1616 cert_chain_[0].encodedCertificate));
1617
1618 CheckedDeleteKey(&key_blob);
1619 }
1620}
1621
1622/*
Selene Huang31ab4042020-04-29 04:22:39 -07001623 * NewKeyGenerationTest.NoInvalidRsaSizes
1624 *
1625 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1626 */
1627TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1628 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001629 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07001630 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001631 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001632 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1633 GenerateKey(AuthorizationSetBuilder()
1634 .RsaSigningKey(key_size, 65537)
1635 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001636 .Padding(PaddingMode::NONE)
1637 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001638 &key_blob, &key_characteristics));
1639 }
1640}
1641
1642/*
1643 * NewKeyGenerationTest.RsaNoDefaultSize
1644 *
1645 * Verifies that failing to specify a key size for RSA key generation returns
1646 * UNSUPPORTED_KEY_SIZE.
1647 */
1648TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1649 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1650 GenerateKey(AuthorizationSetBuilder()
1651 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1652 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001653 .SigningKey()
1654 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001655}
1656
1657/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001658 * NewKeyGenerationTest.RsaMissingParams
1659 *
1660 * Verifies that omitting optional tags works.
1661 */
1662TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1663 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001664 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdaled2cc8c22021-04-15 13:29:45 +01001665 ASSERT_EQ(ErrorCode::OK,
1666 GenerateKey(
1667 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1668 CheckedDeleteKey();
1669 }
1670}
1671
1672/*
Selene Huang31ab4042020-04-29 04:22:39 -07001673 * NewKeyGenerationTest.Ecdsa
1674 *
David Drysdale42fe1892021-10-14 14:43:46 +01001675 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001676 * have correct characteristics.
1677 */
1678TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001679 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001680 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07001681 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001682 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001683 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001684 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001685 .Digest(Digest::NONE)
1686 .SetDefaultValidity(),
1687 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001688 ASSERT_GT(key_blob.size(), 0U);
1689 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001690 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001691
Shawn Willden7f424372021-01-10 18:06:50 -07001692 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001693
1694 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001695 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001696
1697 CheckedDeleteKey(&key_blob);
1698 }
1699}
1700
1701/*
David Drysdale42fe1892021-10-14 14:43:46 +01001702 * NewKeyGenerationTest.EcdsaCurve25519
1703 *
1704 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1705 * has correct characteristics.
1706 */
1707TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1708 if (!Curve25519Supported()) {
1709 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1710 }
1711
1712 EcCurve curve = EcCurve::CURVE_25519;
1713 vector<uint8_t> key_blob;
1714 vector<KeyCharacteristics> key_characteristics;
1715 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1716 .EcdsaSigningKey(curve)
1717 .Digest(Digest::NONE)
1718 .SetDefaultValidity(),
1719 &key_blob, &key_characteristics);
1720 ASSERT_EQ(result, ErrorCode::OK);
1721 ASSERT_GT(key_blob.size(), 0U);
1722
1723 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1724 ASSERT_GT(cert_chain_.size(), 0);
1725
1726 CheckBaseParams(key_characteristics);
1727 CheckCharacteristics(key_blob, key_characteristics);
1728
1729 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1730
1731 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1732 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1733
1734 CheckedDeleteKey(&key_blob);
1735}
1736
1737/*
1738 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1739 *
1740 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1741 * SIGN and AGREE_KEY.
1742 */
1743TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1744 if (!Curve25519Supported()) {
1745 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1746 }
1747
1748 EcCurve curve = EcCurve::CURVE_25519;
1749 vector<uint8_t> key_blob;
1750 vector<KeyCharacteristics> key_characteristics;
1751 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1752 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1753 .EcdsaSigningKey(curve)
1754 .Digest(Digest::NONE)
1755 .SetDefaultValidity(),
1756 &key_blob, &key_characteristics);
1757 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1758}
1759
1760/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001761 * NewKeyGenerationTest.EcdsaWithMissingValidity
1762 *
1763 * Verifies that keymint returns an error while generating asymmetric key
1764 * without providing NOT_BEFORE and NOT_AFTER parameters.
1765 */
1766TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001767 if (AidlVersion() < 2) {
1768 /*
1769 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1770 * specified for asymmetric key generation. However, this was not
1771 * checked at the time so we can only be strict about checking this for
1772 * implementations of KeyMint version 2 and above.
1773 */
1774 GTEST_SKIP() << "Validity strict since KeyMint v2";
1775 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001776 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1777 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1778 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1779
1780 vector<uint8_t> key_blob;
1781 vector<KeyCharacteristics> key_characteristics;
1782 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1783 GenerateKey(AuthorizationSetBuilder()
1784 .EcdsaSigningKey(EcCurve::P_256)
1785 .Digest(Digest::NONE)
1786 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1787 kUndefinedExpirationDateTime),
1788 &key_blob, &key_characteristics));
1789
1790 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1791 GenerateKey(AuthorizationSetBuilder()
1792 .EcdsaSigningKey(EcCurve::P_256)
1793 .Digest(Digest::NONE)
1794 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1795 &key_blob, &key_characteristics));
1796}
1797
1798/*
Selene Huang4f64c222021-04-13 19:54:36 -07001799 * NewKeyGenerationTest.EcdsaAttestation
1800 *
1801 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1802 * an attestation will be generated.
1803 */
1804TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1805 auto challenge = "hello";
1806 auto app_id = "foo";
1807
Selene Huang6e46f142021-04-20 19:20:11 -07001808 auto subject = "cert subj 2";
1809 vector<uint8_t> subject_der(make_name_from_str(subject));
1810
1811 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1812 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1813
David Drysdaledf09e542021-06-08 15:46:11 +01001814 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001815 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07001816 vector<uint8_t> key_blob;
1817 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001818 auto builder = AuthorizationSetBuilder()
1819 .Authorization(TAG_NO_AUTH_REQUIRED)
1820 .EcdsaSigningKey(curve)
1821 .Digest(Digest::NONE)
1822 .AttestationChallenge(challenge)
1823 .AttestationApplicationId(app_id)
1824 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1825 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1826 .SetDefaultValidity();
1827
1828 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001829 // Strongbox may not support factory provisioned attestation key.
1830 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001831 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1832 result = GenerateKeyWithSelfSignedAttestKey(
1833 AuthorizationSetBuilder()
1834 .EcdsaKey(curve)
1835 .AttestKey()
1836 .SetDefaultValidity(), /* attest key params */
1837 builder, &key_blob, &key_characteristics);
1838 }
subrahmanyaman05642492022-02-05 07:10:56 +00001839 }
1840 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001841 ASSERT_GT(key_blob.size(), 0U);
1842 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001843 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001844
1845 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1846
1847 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001848 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001849
1850 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1851 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001852 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001853
1854 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1855 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001856 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001857 sw_enforced, hw_enforced, SecLevel(),
1858 cert_chain_[0].encodedCertificate));
1859
1860 CheckedDeleteKey(&key_blob);
1861 }
1862}
1863
1864/*
David Drysdale42fe1892021-10-14 14:43:46 +01001865 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1866 *
1867 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1868 * an attestation will be generated.
1869 */
1870TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1871 if (!Curve25519Supported()) {
1872 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1873 }
1874
1875 EcCurve curve = EcCurve::CURVE_25519;
1876 auto challenge = "hello";
1877 auto app_id = "foo";
1878
1879 auto subject = "cert subj 2";
1880 vector<uint8_t> subject_der(make_name_from_str(subject));
1881
1882 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1883 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1884
1885 vector<uint8_t> key_blob;
1886 vector<KeyCharacteristics> key_characteristics;
1887 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1888 .Authorization(TAG_NO_AUTH_REQUIRED)
1889 .EcdsaSigningKey(curve)
1890 .Digest(Digest::NONE)
1891 .AttestationChallenge(challenge)
1892 .AttestationApplicationId(app_id)
1893 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1894 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1895 .SetDefaultValidity(),
1896 &key_blob, &key_characteristics);
1897 ASSERT_EQ(ErrorCode::OK, result);
1898 ASSERT_GT(key_blob.size(), 0U);
1899 CheckBaseParams(key_characteristics);
1900 CheckCharacteristics(key_blob, key_characteristics);
1901
1902 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1903
1904 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1905 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1906
1907 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1908 ASSERT_GT(cert_chain_.size(), 0);
1909 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1910
1911 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1912 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1913 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1914 sw_enforced, hw_enforced, SecLevel(),
1915 cert_chain_[0].encodedCertificate));
1916
1917 CheckedDeleteKey(&key_blob);
1918}
1919
1920/*
David Drysdale37af4b32021-05-14 16:46:59 +01001921 * NewKeyGenerationTest.EcdsaAttestationTags
1922 *
1923 * Verifies that creation of an attested ECDSA key includes various tags in the
1924 * attestation extension.
1925 */
1926TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1927 auto challenge = "hello";
1928 auto app_id = "foo";
1929 auto subject = "cert subj 2";
1930 vector<uint8_t> subject_der(make_name_from_str(subject));
1931 uint64_t serial_int = 0x1010;
1932 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1933 const AuthorizationSetBuilder base_builder =
1934 AuthorizationSetBuilder()
1935 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001936 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001937 .Digest(Digest::NONE)
1938 .AttestationChallenge(challenge)
1939 .AttestationApplicationId(app_id)
1940 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1941 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1942 .SetDefaultValidity();
1943
1944 // Various tags that map to fields in the attestation extension ASN.1 schema.
1945 auto extra_tags = AuthorizationSetBuilder()
1946 .Authorization(TAG_ROLLBACK_RESISTANCE)
1947 .Authorization(TAG_EARLY_BOOT_ONLY)
1948 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1949 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1950 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1951 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1952 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1953 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1954 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1955 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1956 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1957 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001958
David Drysdale37af4b32021-05-14 16:46:59 +01001959 for (const KeyParameter& tag : extra_tags) {
1960 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1961 vector<uint8_t> key_blob;
1962 vector<KeyCharacteristics> key_characteristics;
1963 AuthorizationSetBuilder builder = base_builder;
1964 builder.push_back(tag);
1965 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1966 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1967 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1968 continue;
1969 }
Seth Mooreb393b082021-07-12 14:18:28 -07001970 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1971 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001972 continue;
1973 }
subrahmanyaman05642492022-02-05 07:10:56 +00001974 // Strongbox may not support factory provisioned attestation key.
1975 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001976 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1977 result = GenerateKeyWithSelfSignedAttestKey(
1978 AuthorizationSetBuilder()
1979 .EcdsaKey(EcCurve::P_256)
1980 .AttestKey()
1981 .SetDefaultValidity(), /* attest key params */
1982 builder, &key_blob, &key_characteristics);
1983 }
subrahmanyaman05642492022-02-05 07:10:56 +00001984 }
David Drysdale37af4b32021-05-14 16:46:59 +01001985 ASSERT_EQ(result, ErrorCode::OK);
1986 ASSERT_GT(key_blob.size(), 0U);
1987
1988 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1989 ASSERT_GT(cert_chain_.size(), 0);
1990 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1991
1992 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1993 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001994 // Some tags are optional, so don't require them to be in the enforcements.
1995 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001996 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1997 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1998 }
1999
2000 // Verifying the attestation record will check for the specific tag because
2001 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002002 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2003 hw_enforced, SecLevel(),
2004 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002005
2006 CheckedDeleteKey(&key_blob);
2007 }
2008
David Drysdalec53b7d92021-10-11 12:35:58 +01002009 // Collection of invalid attestation ID tags.
2010 auto invalid_tags =
2011 AuthorizationSetBuilder()
2012 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
2013 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
2014 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
2015 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
2016 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
2017 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
2018 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
2019 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01002020 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01002021 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01002022 vector<uint8_t> key_blob;
2023 vector<KeyCharacteristics> key_characteristics;
2024 AuthorizationSetBuilder builder =
2025 AuthorizationSetBuilder()
2026 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002027 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01002028 .Digest(Digest::NONE)
2029 .AttestationChallenge(challenge)
2030 .AttestationApplicationId(app_id)
2031 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2032 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2033 .SetDefaultValidity();
2034 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002035
2036 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
2037 // Strongbox may not support factory provisioned attestation key.
2038 if (SecLevel() == SecurityLevel::STRONGBOX) {
2039 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2040 error = GenerateKeyWithSelfSignedAttestKey(
2041 AuthorizationSetBuilder()
2042 .EcdsaKey(EcCurve::P_256)
2043 .AttestKey()
2044 .SetDefaultValidity(), /* attest key params */
2045 builder, &key_blob, &key_characteristics);
2046 }
2047 }
2048 ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
David Drysdale37af4b32021-05-14 16:46:59 +01002049 }
2050}
2051
2052/*
David Drysdalec53b7d92021-10-11 12:35:58 +01002053 * NewKeyGenerationTest.EcdsaAttestationIdTags
2054 *
2055 * Verifies that creation of an attested ECDSA key includes various ID tags in the
2056 * attestation extension.
2057 */
2058TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01002059 if (is_gsi_image()) {
2060 // GSI sets up a standard set of device identifiers that may not match
2061 // the device identifiers held by the device.
2062 GTEST_SKIP() << "Test not applicable under GSI";
2063 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002064 auto challenge = "hello";
2065 auto app_id = "foo";
2066 auto subject = "cert subj 2";
2067 vector<uint8_t> subject_der(make_name_from_str(subject));
2068 uint64_t serial_int = 0x1010;
2069 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2070 const AuthorizationSetBuilder base_builder =
2071 AuthorizationSetBuilder()
2072 .Authorization(TAG_NO_AUTH_REQUIRED)
2073 .EcdsaSigningKey(EcCurve::P_256)
2074 .Digest(Digest::NONE)
2075 .AttestationChallenge(challenge)
2076 .AttestationApplicationId(app_id)
2077 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2078 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2079 .SetDefaultValidity();
2080
2081 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2082 auto extra_tags = AuthorizationSetBuilder();
Prashant Patil8d779bf2022-09-28 16:09:29 +01002083 // Use ro.product.brand_for_attestation property for attestation if it is present else fallback
2084 // to ro.product.brand
2085 std::string prop_value =
2086 ::android::base::GetProperty("ro.product.brand_for_attestation", /* default= */ "");
2087 if (!prop_value.empty()) {
2088 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND,
2089 "ro.product.brand_for_attestation");
2090 } else {
2091 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
2092 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002093 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
Prashant Patil8d779bf2022-09-28 16:09:29 +01002094 // Use ro.product.name_for_attestation property for attestation if it is present else fallback
2095 // to ro.product.name
2096 prop_value = ::android::base::GetProperty("ro.product.name_for_attestation", /* default= */ "");
2097 if (!prop_value.empty()) {
2098 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT,
2099 "ro.product.name_for_attestation");
2100 } else {
2101 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
2102 }
Tri Vo799e4352022-11-07 17:23:50 -08002103 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
David Drysdalec53b7d92021-10-11 12:35:58 +01002104 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
Prashant Patil8d779bf2022-09-28 16:09:29 +01002105 // Use ro.product.model_for_attestation property for attestation if it is present else fallback
2106 // to ro.product.model
2107 prop_value =
2108 ::android::base::GetProperty("ro.product.model_for_attestation", /* default= */ "");
2109 if (!prop_value.empty()) {
2110 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL,
2111 "ro.product.model_for_attestation");
2112 } else {
2113 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
2114 }
David Drysdalec53b7d92021-10-11 12:35:58 +01002115
2116 for (const KeyParameter& tag : extra_tags) {
2117 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2118 vector<uint8_t> key_blob;
2119 vector<KeyCharacteristics> key_characteristics;
2120 AuthorizationSetBuilder builder = base_builder;
2121 builder.push_back(tag);
2122 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002123 // Strongbox may not support factory provisioned attestation key.
2124 if (SecLevel() == SecurityLevel::STRONGBOX) {
2125 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2126 }
Prashant Patil88ad1892022-03-15 16:31:02 +00002127 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2128 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002129 continue;
2130 }
2131 ASSERT_EQ(result, ErrorCode::OK);
2132 ASSERT_GT(key_blob.size(), 0U);
2133
2134 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2135 ASSERT_GT(cert_chain_.size(), 0);
2136 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2137
2138 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2139 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2140
2141 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2142 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2143 // attestation extension should contain them, so make sure the extra tag is added.
2144 hw_enforced.push_back(tag);
2145
2146 // Verifying the attestation record will check for the specific tag because
2147 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002148 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2149 hw_enforced, SecLevel(),
2150 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002151
2152 CheckedDeleteKey(&key_blob);
2153 }
2154}
2155
2156/*
David Drysdale565ccc72021-10-11 12:49:50 +01002157 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2158 *
2159 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2160 */
2161TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2162 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002163 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002164 auto challenge = "hello";
2165 auto subject = "cert subj 2";
2166 vector<uint8_t> subject_der(make_name_from_str(subject));
2167 uint64_t serial_int = 0x1010;
2168 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002169 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002170 AuthorizationSetBuilder()
2171 .Authorization(TAG_NO_AUTH_REQUIRED)
2172 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2173 .EcdsaSigningKey(EcCurve::P_256)
2174 .Digest(Digest::NONE)
2175 .AttestationChallenge(challenge)
2176 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2177 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2178 .AttestationApplicationId(app_id)
2179 .Authorization(TAG_CREATION_DATETIME, datetime)
2180 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002181 if (reset) {
2182 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2183 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002184 auto result = GenerateKey(builder);
2185 if (SecLevel() == SecurityLevel::STRONGBOX) {
2186 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2187 result = GenerateKeyWithSelfSignedAttestKey(
2188 AuthorizationSetBuilder()
2189 .EcdsaKey(EcCurve::P_256)
2190 .AttestKey()
2191 .SetDefaultValidity(), /* attest key params */
2192 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2193 }
2194 }
2195 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002196 ASSERT_GT(key_blob_.size(), 0U);
2197
2198 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2199 ASSERT_GT(cert_chain_.size(), 0);
2200 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2201
2202 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2203 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2204
2205 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002206 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2207 hw_enforced, SecLevel(),
2208 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002209 EXPECT_GT(unique_id->size(), 0);
2210 CheckedDeleteKey();
2211 };
2212
2213 // Generate unique ID
2214 auto app_id = "foo";
2215 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2216 vector<uint8_t> unique_id;
2217 get_unique_id(app_id, cert_date, &unique_id);
2218
2219 // Generating a new key with the same parameters should give the same unique ID.
2220 vector<uint8_t> unique_id2;
2221 get_unique_id(app_id, cert_date, &unique_id2);
2222 EXPECT_EQ(unique_id, unique_id2);
2223
2224 // Generating a new key with a slightly different date should give the same unique ID.
2225 uint64_t rounded_date = cert_date / 2592000000LLU;
2226 uint64_t min_date = rounded_date * 2592000000LLU;
2227 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2228
2229 vector<uint8_t> unique_id3;
2230 get_unique_id(app_id, min_date, &unique_id3);
2231 EXPECT_EQ(unique_id, unique_id3);
2232
2233 vector<uint8_t> unique_id4;
2234 get_unique_id(app_id, max_date, &unique_id4);
2235 EXPECT_EQ(unique_id, unique_id4);
2236
2237 // A different attestation application ID should yield a different unique ID.
2238 auto app_id2 = "different_foo";
2239 vector<uint8_t> unique_id5;
2240 get_unique_id(app_id2, cert_date, &unique_id5);
2241 EXPECT_NE(unique_id, unique_id5);
2242
2243 // A radically different date should yield a different unique ID.
2244 vector<uint8_t> unique_id6;
2245 get_unique_id(app_id, 1611621648000, &unique_id6);
2246 EXPECT_NE(unique_id, unique_id6);
2247
2248 vector<uint8_t> unique_id7;
2249 get_unique_id(app_id, max_date + 1, &unique_id7);
2250 EXPECT_NE(unique_id, unique_id7);
2251
2252 vector<uint8_t> unique_id8;
2253 get_unique_id(app_id, min_date - 1, &unique_id8);
2254 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002255
2256 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2257 vector<uint8_t> unique_id9;
2258 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2259 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002260}
2261
2262/*
David Drysdale37af4b32021-05-14 16:46:59 +01002263 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2264 *
2265 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2266 */
2267TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2268 auto challenge = "hello";
2269 auto attest_app_id = "foo";
2270 auto subject = "cert subj 2";
2271 vector<uint8_t> subject_der(make_name_from_str(subject));
2272 uint64_t serial_int = 0x1010;
2273 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2274
2275 // Earlier versions of the attestation extension schema included a slot:
2276 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2277 // This should never have been included, and should never be filled in.
2278 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2279 // to confirm that this field never makes it into the attestation extension.
2280 vector<uint8_t> key_blob;
2281 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002282 auto builder = AuthorizationSetBuilder()
2283 .Authorization(TAG_NO_AUTH_REQUIRED)
2284 .EcdsaSigningKey(EcCurve::P_256)
2285 .Digest(Digest::NONE)
2286 .AttestationChallenge(challenge)
2287 .AttestationApplicationId(attest_app_id)
2288 .Authorization(TAG_APPLICATION_ID, "client_id")
2289 .Authorization(TAG_APPLICATION_DATA, "appdata")
2290 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2291 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2292 .SetDefaultValidity();
2293
2294 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002295 // Strongbox may not support factory provisioned attestation key.
2296 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002297 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2298 result = GenerateKeyWithSelfSignedAttestKey(
2299 AuthorizationSetBuilder()
2300 .EcdsaKey(EcCurve::P_256)
2301 .AttestKey()
2302 .SetDefaultValidity(), /* attest key params */
2303 builder, &key_blob, &key_characteristics);
2304 }
subrahmanyaman05642492022-02-05 07:10:56 +00002305 }
David Drysdale37af4b32021-05-14 16:46:59 +01002306 ASSERT_EQ(result, ErrorCode::OK);
2307 ASSERT_GT(key_blob.size(), 0U);
2308
2309 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2310 ASSERT_GT(cert_chain_.size(), 0);
2311 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2312
2313 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2314 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002315 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2316 hw_enforced, SecLevel(),
2317 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002318
2319 // Check that the app id is not in the cert.
2320 string app_id = "clientid";
2321 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2322 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2323 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2324 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2325 cert_chain_[0].encodedCertificate.end());
2326
2327 CheckedDeleteKey(&key_blob);
2328}
2329
2330/*
Selene Huang4f64c222021-04-13 19:54:36 -07002331 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2332 *
2333 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2334 * the key will generate a self signed attestation.
2335 */
2336TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002337 auto subject = "cert subj 2";
2338 vector<uint8_t> subject_der(make_name_from_str(subject));
2339
2340 uint64_t serial_int = 0x123456FFF1234;
2341 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2342
David Drysdaledf09e542021-06-08 15:46:11 +01002343 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002344 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002345 vector<uint8_t> key_blob;
2346 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002347 ASSERT_EQ(ErrorCode::OK,
2348 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002349 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002350 .Digest(Digest::NONE)
2351 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2352 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2353 .SetDefaultValidity(),
2354 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002355 ASSERT_GT(key_blob.size(), 0U);
2356 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002357 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002358
2359 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2360
2361 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002362 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002363
2364 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2365 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002366 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002367
2368 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2369 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2370
2371 CheckedDeleteKey(&key_blob);
2372 }
2373}
2374
2375/*
2376 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2377 *
2378 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2379 * app id must also be provided or else it will fail.
2380 */
2381TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2382 auto challenge = "hello";
2383 vector<uint8_t> key_blob;
2384 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002385 auto builder = AuthorizationSetBuilder()
2386 .EcdsaSigningKey(EcCurve::P_256)
2387 .Digest(Digest::NONE)
2388 .AttestationChallenge(challenge)
2389 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002390
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002391 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002392 // Strongbox may not support factory provisioned attestation key.
2393 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002394 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2395 result = GenerateKeyWithSelfSignedAttestKey(
2396 AuthorizationSetBuilder()
2397 .EcdsaKey(EcCurve::P_256)
2398 .AttestKey()
2399 .SetDefaultValidity(), /* attest key params */
2400 builder, &key_blob, &key_characteristics);
2401 }
subrahmanyaman05642492022-02-05 07:10:56 +00002402 }
2403 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002404}
2405
2406/*
2407 * NewKeyGenerationTest.EcdsaIgnoreAppId
2408 *
2409 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2410 * any appid will be ignored, and keymint will generate a self sign certificate.
2411 */
2412TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2413 auto app_id = "foo";
2414
David Drysdaledf09e542021-06-08 15:46:11 +01002415 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002416 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002417 vector<uint8_t> key_blob;
2418 vector<KeyCharacteristics> key_characteristics;
2419 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002420 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002421 .Digest(Digest::NONE)
2422 .AttestationApplicationId(app_id)
2423 .SetDefaultValidity(),
2424 &key_blob, &key_characteristics));
2425
2426 ASSERT_GT(key_blob.size(), 0U);
2427 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002428 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002429
2430 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2431
2432 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002433 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002434
2435 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2436 ASSERT_EQ(cert_chain_.size(), 1);
2437
2438 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2439 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2440
2441 CheckedDeleteKey(&key_blob);
2442 }
2443}
2444
2445/*
2446 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2447 *
2448 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2449 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2450 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2451 * to specify how many following bytes will be used to encode the length.
2452 */
2453TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2454 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002455 std::vector<uint32_t> app_id_lengths{143, 258};
2456
2457 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002458 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002459 const string app_id(length, 'a');
2460 vector<uint8_t> key_blob;
2461 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002462 auto builder = AuthorizationSetBuilder()
2463 .Authorization(TAG_NO_AUTH_REQUIRED)
2464 .EcdsaSigningKey(EcCurve::P_256)
2465 .Digest(Digest::NONE)
2466 .AttestationChallenge(challenge)
2467 .AttestationApplicationId(app_id)
2468 .SetDefaultValidity();
2469
2470 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002471 // Strongbox may not support factory provisioned attestation key.
2472 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002473 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2474 result = GenerateKeyWithSelfSignedAttestKey(
2475 AuthorizationSetBuilder()
2476 .EcdsaKey(EcCurve::P_256)
2477 .AttestKey()
2478 .SetDefaultValidity(), /* attest key params */
2479 builder, &key_blob, &key_characteristics);
2480 }
subrahmanyaman05642492022-02-05 07:10:56 +00002481 }
2482 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002483 ASSERT_GT(key_blob.size(), 0U);
2484 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002485 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002486
2487 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2488
2489 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002490 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002491
2492 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2493 ASSERT_GT(cert_chain_.size(), 0);
2494
2495 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2496 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002497 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002498 sw_enforced, hw_enforced, SecLevel(),
2499 cert_chain_[0].encodedCertificate));
2500
2501 CheckedDeleteKey(&key_blob);
2502 }
2503}
2504
2505/*
Qi Wud22ec842020-11-26 13:27:53 +08002506 * NewKeyGenerationTest.LimitedUsageEcdsa
2507 *
2508 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2509 * resulting keys have correct characteristics.
2510 */
2511TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002512 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002513 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002514 vector<uint8_t> key_blob;
2515 vector<KeyCharacteristics> key_characteristics;
2516 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002517 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002518 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002519 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2520 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002521 &key_blob, &key_characteristics));
2522
2523 ASSERT_GT(key_blob.size(), 0U);
2524 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002525 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002526
2527 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2528
2529 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002530 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002531
2532 // Check the usage count limit tag appears in the authorizations.
2533 AuthorizationSet auths;
2534 for (auto& entry : key_characteristics) {
2535 auths.push_back(AuthorizationSet(entry.authorizations));
2536 }
2537 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2538 << "key usage count limit " << 1U << " missing";
2539
2540 CheckedDeleteKey(&key_blob);
2541 }
2542}
2543
2544/*
Selene Huang31ab4042020-04-29 04:22:39 -07002545 * NewKeyGenerationTest.EcdsaDefaultSize
2546 *
David Drysdaledf09e542021-06-08 15:46:11 +01002547 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002548 * UNSUPPORTED_KEY_SIZE.
2549 */
2550TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2551 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2552 GenerateKey(AuthorizationSetBuilder()
2553 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2554 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002555 .Digest(Digest::NONE)
2556 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002557}
2558
2559/*
David Drysdale42fe1892021-10-14 14:43:46 +01002560 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002561 *
David Drysdale42fe1892021-10-14 14:43:46 +01002562 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002563 * UNSUPPORTED_KEY_SIZE.
2564 */
David Drysdale42fe1892021-10-14 14:43:46 +01002565TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002566 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002567 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002568 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002569 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002570 auto result = GenerateKey(AuthorizationSetBuilder()
2571 .EcdsaSigningKey(curve)
2572 .Digest(Digest::NONE)
2573 .SetDefaultValidity(),
2574 &key_blob, &key_characteristics);
2575 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2576 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002577 }
2578
David Drysdaledf09e542021-06-08 15:46:11 +01002579 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2580 GenerateKey(AuthorizationSetBuilder()
2581 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2582 .Authorization(TAG_KEY_SIZE, 190)
2583 .SigningKey()
2584 .Digest(Digest::NONE)
2585 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002586}
2587
2588/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002589 * NewKeyGenerationTest.EcdsaMissingCurve
2590 *
2591 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2592 */
2593TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2594 if (AidlVersion() < 2) {
2595 /*
2596 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2597 * However, this was not checked at the time so we can only be strict about checking this
2598 * for implementations of KeyMint version 2 and above.
2599 */
2600 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2601 }
2602 /* If EC_CURVE not provided, generateKey
2603 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2604 */
2605 auto result = GenerateKey(
2606 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2607 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2608 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2609}
2610
2611/*
Selene Huang31ab4042020-04-29 04:22:39 -07002612 * NewKeyGenerationTest.EcdsaMismatchKeySize
2613 *
2614 * Verifies that specifying mismatched key size and curve for EC key generation returns
2615 * INVALID_ARGUMENT.
2616 */
2617TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002618 if (SecLevel() == SecurityLevel::STRONGBOX) {
2619 GTEST_SKIP() << "Test not applicable to StrongBox device";
2620 }
Selene Huang31ab4042020-04-29 04:22:39 -07002621
David Drysdaledf09e542021-06-08 15:46:11 +01002622 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002623 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002624 .Authorization(TAG_KEY_SIZE, 224)
2625 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002626 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002627 .Digest(Digest::NONE)
2628 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002629 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002630}
2631
2632/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002633 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002634 *
2635 * Verifies that keymint does not support any curve designated as unsupported.
2636 */
2637TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2638 Digest digest;
2639 if (SecLevel() == SecurityLevel::STRONGBOX) {
2640 digest = Digest::SHA_2_256;
2641 } else {
2642 digest = Digest::SHA_2_512;
2643 }
2644 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002645 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002646 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2647 .EcdsaSigningKey(curve)
2648 .Digest(digest)
2649 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002650 << "Failed to generate key on curve: " << curve;
2651 CheckedDeleteKey();
2652 }
2653}
2654
2655/*
2656 * NewKeyGenerationTest.Hmac
2657 *
2658 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2659 * characteristics.
2660 */
2661TEST_P(NewKeyGenerationTest, Hmac) {
2662 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002663 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002664 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002665 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002666 constexpr size_t key_size = 128;
2667 ASSERT_EQ(ErrorCode::OK,
2668 GenerateKey(
2669 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2670 TAG_MIN_MAC_LENGTH, 128),
2671 &key_blob, &key_characteristics));
2672
2673 ASSERT_GT(key_blob.size(), 0U);
2674 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002675 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002676
Shawn Willden7f424372021-01-10 18:06:50 -07002677 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2678 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2679 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2680 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002681
2682 CheckedDeleteKey(&key_blob);
2683 }
2684}
2685
2686/*
Selene Huang4f64c222021-04-13 19:54:36 -07002687 * NewKeyGenerationTest.HmacNoAttestation
2688 *
2689 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2690 * and app id are provided.
2691 */
2692TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2693 auto challenge = "hello";
2694 auto app_id = "foo";
2695
2696 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002697 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002698 vector<uint8_t> key_blob;
2699 vector<KeyCharacteristics> key_characteristics;
2700 constexpr size_t key_size = 128;
2701 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2702 .HmacKey(key_size)
2703 .Digest(digest)
2704 .AttestationChallenge(challenge)
2705 .AttestationApplicationId(app_id)
2706 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2707 &key_blob, &key_characteristics));
2708
2709 ASSERT_GT(key_blob.size(), 0U);
2710 ASSERT_EQ(cert_chain_.size(), 0);
2711 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002712 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002713
2714 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2715 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2716 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2717 << "Key size " << key_size << "missing";
2718
2719 CheckedDeleteKey(&key_blob);
2720 }
2721}
2722
2723/*
Qi Wud22ec842020-11-26 13:27:53 +08002724 * NewKeyGenerationTest.LimitedUsageHmac
2725 *
2726 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2727 * resulting keys have correct characteristics.
2728 */
2729TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2730 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002731 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002732 vector<uint8_t> key_blob;
2733 vector<KeyCharacteristics> key_characteristics;
2734 constexpr size_t key_size = 128;
2735 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2736 .HmacKey(key_size)
2737 .Digest(digest)
2738 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2739 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2740 &key_blob, &key_characteristics));
2741
2742 ASSERT_GT(key_blob.size(), 0U);
2743 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002744 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002745
2746 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2747 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2748 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2749 << "Key size " << key_size << "missing";
2750
2751 // Check the usage count limit tag appears in the authorizations.
2752 AuthorizationSet auths;
2753 for (auto& entry : key_characteristics) {
2754 auths.push_back(AuthorizationSet(entry.authorizations));
2755 }
2756 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2757 << "key usage count limit " << 1U << " missing";
2758
2759 CheckedDeleteKey(&key_blob);
2760 }
2761}
2762
2763/*
Selene Huang31ab4042020-04-29 04:22:39 -07002764 * NewKeyGenerationTest.HmacCheckKeySizes
2765 *
2766 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2767 */
2768TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2769 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002770 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002771 if (key_size < 64 || key_size % 8 != 0) {
2772 // To keep this test from being very slow, we only test a random fraction of
2773 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2774 // them, we expect to run ~40 of them in each run.
2775 if (key_size % 8 == 0 || random() % 10 == 0) {
2776 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2777 GenerateKey(AuthorizationSetBuilder()
2778 .HmacKey(key_size)
2779 .Digest(Digest::SHA_2_256)
2780 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2781 << "HMAC key size " << key_size << " invalid";
2782 }
2783 } else {
2784 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2785 .HmacKey(key_size)
2786 .Digest(Digest::SHA_2_256)
2787 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2788 << "Failed to generate HMAC key of size " << key_size;
2789 CheckedDeleteKey();
2790 }
2791 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002792 if (SecLevel() == SecurityLevel::STRONGBOX) {
2793 // STRONGBOX devices must not support keys larger than 512 bits.
2794 size_t key_size = 520;
2795 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2796 GenerateKey(AuthorizationSetBuilder()
2797 .HmacKey(key_size)
2798 .Digest(Digest::SHA_2_256)
2799 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2800 << "HMAC key size " << key_size << " unexpectedly valid";
2801 }
Selene Huang31ab4042020-04-29 04:22:39 -07002802}
2803
2804/*
2805 * NewKeyGenerationTest.HmacCheckMinMacLengths
2806 *
2807 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2808 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2809 * specific MAC length that failed, so reproducing a failed run will be easy.
2810 */
2811TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2812 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002813 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002814 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2815 // To keep this test from being very long, we only test a random fraction of
2816 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2817 // we expect to run ~17 of them in each run.
2818 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2819 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2820 GenerateKey(AuthorizationSetBuilder()
2821 .HmacKey(128)
2822 .Digest(Digest::SHA_2_256)
2823 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2824 << "HMAC min mac length " << min_mac_length << " invalid.";
2825 }
2826 } else {
2827 EXPECT_EQ(ErrorCode::OK,
2828 GenerateKey(AuthorizationSetBuilder()
2829 .HmacKey(128)
2830 .Digest(Digest::SHA_2_256)
2831 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2832 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2833 CheckedDeleteKey();
2834 }
2835 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002836
2837 // Minimum MAC length must be no more than 512 bits.
2838 size_t min_mac_length = 520;
2839 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2840 GenerateKey(AuthorizationSetBuilder()
2841 .HmacKey(128)
2842 .Digest(Digest::SHA_2_256)
2843 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2844 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002845}
2846
2847/*
2848 * NewKeyGenerationTest.HmacMultipleDigests
2849 *
2850 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2851 */
2852TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002853 if (SecLevel() == SecurityLevel::STRONGBOX) {
2854 GTEST_SKIP() << "Test not applicable to StrongBox device";
2855 }
Selene Huang31ab4042020-04-29 04:22:39 -07002856
2857 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2858 GenerateKey(AuthorizationSetBuilder()
2859 .HmacKey(128)
2860 .Digest(Digest::SHA1)
2861 .Digest(Digest::SHA_2_256)
2862 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2863}
2864
2865/*
2866 * NewKeyGenerationTest.HmacDigestNone
2867 *
2868 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2869 */
2870TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2871 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2872 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2873 128)));
2874
2875 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2876 GenerateKey(AuthorizationSetBuilder()
2877 .HmacKey(128)
2878 .Digest(Digest::NONE)
2879 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2880}
2881
Selene Huang4f64c222021-04-13 19:54:36 -07002882/*
2883 * NewKeyGenerationTest.AesNoAttestation
2884 *
2885 * Verifies that attestation parameters to AES keys are ignored and generateKey
2886 * will succeed.
2887 */
2888TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2889 auto challenge = "hello";
2890 auto app_id = "foo";
2891
2892 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2893 .Authorization(TAG_NO_AUTH_REQUIRED)
2894 .AesEncryptionKey(128)
2895 .EcbMode()
2896 .Padding(PaddingMode::PKCS7)
2897 .AttestationChallenge(challenge)
2898 .AttestationApplicationId(app_id)));
2899
2900 ASSERT_EQ(cert_chain_.size(), 0);
2901}
2902
2903/*
2904 * NewKeyGenerationTest.TripleDesNoAttestation
2905 *
2906 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2907 * will be successful. No attestation should be generated.
2908 */
2909TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2910 auto challenge = "hello";
2911 auto app_id = "foo";
2912
2913 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2914 .TripleDesEncryptionKey(168)
2915 .BlockMode(BlockMode::ECB)
2916 .Authorization(TAG_NO_AUTH_REQUIRED)
2917 .Padding(PaddingMode::NONE)
2918 .AttestationChallenge(challenge)
2919 .AttestationApplicationId(app_id)));
2920 ASSERT_EQ(cert_chain_.size(), 0);
2921}
2922
Selene Huang31ab4042020-04-29 04:22:39 -07002923INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2924
2925typedef KeyMintAidlTestBase SigningOperationsTest;
2926
2927/*
2928 * SigningOperationsTest.RsaSuccess
2929 *
2930 * Verifies that raw RSA signature operations succeed.
2931 */
2932TEST_P(SigningOperationsTest, RsaSuccess) {
2933 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2934 .RsaSigningKey(2048, 65537)
2935 .Digest(Digest::NONE)
2936 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002937 .Authorization(TAG_NO_AUTH_REQUIRED)
2938 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002939 string message = "12345678901234567890123456789012";
2940 string signature = SignMessage(
2941 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002942 LocalVerifyMessage(message, signature,
2943 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2944}
2945
2946/*
2947 * SigningOperationsTest.RsaAllPaddingsAndDigests
2948 *
2949 * Verifies RSA signature/verification for all padding modes and digests.
2950 */
2951TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2952 auto authorizations = AuthorizationSetBuilder()
2953 .Authorization(TAG_NO_AUTH_REQUIRED)
2954 .RsaSigningKey(2048, 65537)
2955 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2956 .Padding(PaddingMode::NONE)
2957 .Padding(PaddingMode::RSA_PSS)
2958 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2959 .SetDefaultValidity();
2960
2961 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2962
2963 string message(128, 'a');
2964 string corrupt_message(message);
2965 ++corrupt_message[corrupt_message.size() / 2];
2966
2967 for (auto padding :
2968 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2969 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002970 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002971 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2972 // Digesting only makes sense with padding.
2973 continue;
2974 }
2975
2976 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2977 // PSS requires digesting.
2978 continue;
2979 }
2980
2981 string signature =
2982 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2983 LocalVerifyMessage(message, signature,
2984 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2985 }
2986 }
Selene Huang31ab4042020-04-29 04:22:39 -07002987}
2988
2989/*
2990 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2991 *
Shawn Willden7f424372021-01-10 18:06:50 -07002992 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002993 */
2994TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2995 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2996 .Authorization(TAG_NO_AUTH_REQUIRED)
2997 .RsaSigningKey(2048, 65537)
2998 .Digest(Digest::NONE)
2999 .Padding(PaddingMode::NONE)
3000 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003001 .Authorization(TAG_APPLICATION_DATA, "appdata")
3002 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003003
3004 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3005
Selene Huang31ab4042020-04-29 04:22:39 -07003006 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3007 Begin(KeyPurpose::SIGN,
3008 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3009 AbortIfNeeded();
3010 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3011 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3012 .Digest(Digest::NONE)
3013 .Padding(PaddingMode::NONE)
3014 .Authorization(TAG_APPLICATION_ID, "clientid")));
3015 AbortIfNeeded();
3016 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3017 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3018 .Digest(Digest::NONE)
3019 .Padding(PaddingMode::NONE)
3020 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3021 AbortIfNeeded();
3022 EXPECT_EQ(ErrorCode::OK,
3023 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3024 .Digest(Digest::NONE)
3025 .Padding(PaddingMode::NONE)
3026 .Authorization(TAG_APPLICATION_DATA, "appdata")
3027 .Authorization(TAG_APPLICATION_ID, "clientid")));
3028 AbortIfNeeded();
3029}
3030
3031/*
3032 * SigningOperationsTest.RsaPssSha256Success
3033 *
3034 * Verifies that RSA-PSS signature operations succeed.
3035 */
3036TEST_P(SigningOperationsTest, RsaPssSha256Success) {
3037 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3038 .RsaSigningKey(2048, 65537)
3039 .Digest(Digest::SHA_2_256)
3040 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003041 .Authorization(TAG_NO_AUTH_REQUIRED)
3042 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003043 // Use large message, which won't work without digesting.
3044 string message(1024, 'a');
3045 string signature = SignMessage(
3046 message,
3047 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
3048}
3049
3050/*
3051 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
3052 *
3053 * Verifies that keymint rejects signature operations that specify a padding mode when the key
3054 * supports only unpadded operations.
3055 */
3056TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
3057 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3058 .RsaSigningKey(2048, 65537)
3059 .Digest(Digest::NONE)
3060 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003061 .Padding(PaddingMode::NONE)
3062 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003063 string message = "12345678901234567890123456789012";
3064 string signature;
3065
3066 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3067 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3068 .Digest(Digest::NONE)
3069 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3070}
3071
3072/*
3073 * SigningOperationsTest.NoUserConfirmation
3074 *
3075 * Verifies that keymint rejects signing operations for keys with
3076 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
3077 * presented.
3078 */
3079TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01003080 if (SecLevel() == SecurityLevel::STRONGBOX) {
3081 GTEST_SKIP() << "Test not applicable to StrongBox device";
3082 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08003083 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3084 .RsaSigningKey(1024, 65537)
3085 .Digest(Digest::NONE)
3086 .Padding(PaddingMode::NONE)
3087 .Authorization(TAG_NO_AUTH_REQUIRED)
3088 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3089 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003090
3091 const string message = "12345678901234567890123456789012";
3092 EXPECT_EQ(ErrorCode::OK,
3093 Begin(KeyPurpose::SIGN,
3094 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3095 string signature;
3096 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3097}
3098
3099/*
3100 * SigningOperationsTest.RsaPkcs1Sha256Success
3101 *
3102 * Verifies that digested RSA-PKCS1 signature operations succeed.
3103 */
3104TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3105 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3106 .RsaSigningKey(2048, 65537)
3107 .Digest(Digest::SHA_2_256)
3108 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003109 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3110 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003111 string message(1024, 'a');
3112 string signature = SignMessage(message, AuthorizationSetBuilder()
3113 .Digest(Digest::SHA_2_256)
3114 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3115}
3116
3117/*
3118 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3119 *
3120 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3121 */
3122TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3123 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3124 .RsaSigningKey(2048, 65537)
3125 .Digest(Digest::NONE)
3126 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003127 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3128 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003129 string message(53, 'a');
3130 string signature = SignMessage(message, AuthorizationSetBuilder()
3131 .Digest(Digest::NONE)
3132 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3133}
3134
3135/*
3136 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3137 *
3138 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3139 * given a too-long message.
3140 */
3141TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3142 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3143 .RsaSigningKey(2048, 65537)
3144 .Digest(Digest::NONE)
3145 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003146 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3147 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003148 string message(257, 'a');
3149
3150 EXPECT_EQ(ErrorCode::OK,
3151 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3152 .Digest(Digest::NONE)
3153 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3154 string signature;
3155 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3156}
3157
3158/*
3159 * SigningOperationsTest.RsaPssSha512TooSmallKey
3160 *
3161 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3162 * used with a key that is too small for the message.
3163 *
3164 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3165 * keymint specification requires that salt_size == digest_size, so the message will be
3166 * digest_size * 2 +
3167 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3168 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3169 * for a 1024-bit key.
3170 */
3171TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003172 if (SecLevel() == SecurityLevel::STRONGBOX) {
3173 GTEST_SKIP() << "Test not applicable to StrongBox device";
3174 }
Selene Huang31ab4042020-04-29 04:22:39 -07003175 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3176 .RsaSigningKey(1024, 65537)
3177 .Digest(Digest::SHA_2_512)
3178 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003179 .Padding(PaddingMode::RSA_PSS)
3180 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003181 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3182 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3183 .Digest(Digest::SHA_2_512)
3184 .Padding(PaddingMode::RSA_PSS)));
3185}
3186
3187/*
3188 * SigningOperationsTest.RsaNoPaddingTooLong
3189 *
3190 * Verifies that raw RSA signature operations fail with the correct error code when
3191 * given a too-long message.
3192 */
3193TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3194 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3195 .RsaSigningKey(2048, 65537)
3196 .Digest(Digest::NONE)
3197 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003198 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3199 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003200 // One byte too long
3201 string message(2048 / 8 + 1, 'a');
3202 ASSERT_EQ(ErrorCode::OK,
3203 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3204 .Digest(Digest::NONE)
3205 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3206 string result;
3207 ErrorCode finish_error_code = Finish(message, &result);
3208 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3209 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3210
3211 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3212 message = string(128 * 1024, 'a');
3213 ASSERT_EQ(ErrorCode::OK,
3214 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3215 .Digest(Digest::NONE)
3216 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3217 finish_error_code = Finish(message, &result);
3218 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3219 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3220}
3221
3222/*
3223 * SigningOperationsTest.RsaAbort
3224 *
3225 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3226 * test, but the behavior should be algorithm and purpose-independent.
3227 */
3228TEST_P(SigningOperationsTest, RsaAbort) {
3229 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3230 .RsaSigningKey(2048, 65537)
3231 .Digest(Digest::NONE)
3232 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003233 .Padding(PaddingMode::NONE)
3234 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003235
3236 ASSERT_EQ(ErrorCode::OK,
3237 Begin(KeyPurpose::SIGN,
3238 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3239 EXPECT_EQ(ErrorCode::OK, Abort());
3240
3241 // Another abort should fail
3242 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3243
3244 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003245 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003246}
3247
3248/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003249 * SigningOperationsTest.RsaNonUniqueParams
3250 *
3251 * Verifies that an operation with multiple padding modes is rejected.
3252 */
3253TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3254 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3255 .RsaSigningKey(2048, 65537)
3256 .Digest(Digest::NONE)
3257 .Digest(Digest::SHA1)
3258 .Authorization(TAG_NO_AUTH_REQUIRED)
3259 .Padding(PaddingMode::NONE)
3260 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3261 .SetDefaultValidity()));
3262
3263 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3264 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3265 .Digest(Digest::NONE)
3266 .Padding(PaddingMode::NONE)
3267 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3268
Tommy Chiuc93c4392021-05-11 18:36:50 +08003269 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3270 .Digest(Digest::NONE)
3271 .Digest(Digest::SHA1)
3272 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3273 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003274
3275 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3276 Begin(KeyPurpose::SIGN,
3277 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3278}
3279
3280/*
Selene Huang31ab4042020-04-29 04:22:39 -07003281 * SigningOperationsTest.RsaUnsupportedPadding
3282 *
3283 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3284 * with a padding mode inappropriate for RSA.
3285 */
3286TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3287 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3288 .RsaSigningKey(2048, 65537)
3289 .Authorization(TAG_NO_AUTH_REQUIRED)
3290 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003291 .Padding(PaddingMode::PKCS7)
3292 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003293 ASSERT_EQ(
3294 ErrorCode::UNSUPPORTED_PADDING_MODE,
3295 Begin(KeyPurpose::SIGN,
3296 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003297 CheckedDeleteKey();
3298
3299 ASSERT_EQ(ErrorCode::OK,
3300 GenerateKey(
3301 AuthorizationSetBuilder()
3302 .RsaSigningKey(2048, 65537)
3303 .Authorization(TAG_NO_AUTH_REQUIRED)
3304 .Digest(Digest::SHA_2_256 /* supported digest */)
3305 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3306 .SetDefaultValidity()));
3307 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3308 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3309 .Digest(Digest::SHA_2_256)
3310 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003311}
3312
3313/*
3314 * SigningOperationsTest.RsaPssNoDigest
3315 *
3316 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3317 */
3318TEST_P(SigningOperationsTest, RsaNoDigest) {
3319 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3320 .RsaSigningKey(2048, 65537)
3321 .Authorization(TAG_NO_AUTH_REQUIRED)
3322 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003323 .Padding(PaddingMode::RSA_PSS)
3324 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003325 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3326 Begin(KeyPurpose::SIGN,
3327 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3328
3329 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3330 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3331}
3332
3333/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003334 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003335 *
3336 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3337 * supported in some cases (as validated in other tests), but a mode must be specified.
3338 */
3339TEST_P(SigningOperationsTest, RsaNoPadding) {
3340 // Padding must be specified
3341 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3342 .RsaKey(2048, 65537)
3343 .Authorization(TAG_NO_AUTH_REQUIRED)
3344 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003345 .Digest(Digest::NONE)
3346 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003347 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3348 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3349}
3350
3351/*
3352 * SigningOperationsTest.RsaShortMessage
3353 *
3354 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3355 */
3356TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3357 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3358 .Authorization(TAG_NO_AUTH_REQUIRED)
3359 .RsaSigningKey(2048, 65537)
3360 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003361 .Padding(PaddingMode::NONE)
3362 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003363
3364 // Barely shorter
3365 string message(2048 / 8 - 1, 'a');
3366 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3367
3368 // Much shorter
3369 message = "a";
3370 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3371}
3372
3373/*
3374 * SigningOperationsTest.RsaSignWithEncryptionKey
3375 *
3376 * Verifies that RSA encryption keys cannot be used to sign.
3377 */
3378TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3379 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3380 .Authorization(TAG_NO_AUTH_REQUIRED)
3381 .RsaEncryptionKey(2048, 65537)
3382 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003383 .Padding(PaddingMode::NONE)
3384 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003385 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3386 Begin(KeyPurpose::SIGN,
3387 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3388}
3389
3390/*
3391 * SigningOperationsTest.RsaSignTooLargeMessage
3392 *
3393 * Verifies that attempting a raw signature of a message which is the same length as the key,
3394 * but numerically larger than the public modulus, fails with the correct error.
3395 */
3396TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3397 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3398 .Authorization(TAG_NO_AUTH_REQUIRED)
3399 .RsaSigningKey(2048, 65537)
3400 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003401 .Padding(PaddingMode::NONE)
3402 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003403
3404 // Largest possible message will always be larger than the public modulus.
3405 string message(2048 / 8, static_cast<char>(0xff));
3406 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3407 .Authorization(TAG_NO_AUTH_REQUIRED)
3408 .Digest(Digest::NONE)
3409 .Padding(PaddingMode::NONE)));
3410 string signature;
3411 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3412}
3413
3414/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003415 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3416 *
David Drysdale42fe1892021-10-14 14:43:46 +01003417 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003418 */
3419TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003420
3421 string message = "1234567890";
3422 string corrupt_message = "2234567890";
3423 for (auto curve : ValidCurves()) {
3424 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003425 // Ed25519 only allows Digest::NONE.
3426 auto digests = (curve == EcCurve::CURVE_25519)
3427 ? std::vector<Digest>(1, Digest::NONE)
3428 : ValidDigests(true /* withNone */, false /* withMD5 */);
3429
David Drysdaledf8f52e2021-05-06 08:10:58 +01003430 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3431 .Authorization(TAG_NO_AUTH_REQUIRED)
3432 .EcdsaSigningKey(curve)
3433 .Digest(digests)
3434 .SetDefaultValidity());
3435 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3436 if (error != ErrorCode::OK) {
3437 continue;
3438 }
3439
3440 for (auto digest : digests) {
3441 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3442 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3443 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3444 }
3445
3446 auto rc = DeleteKey();
3447 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3448 }
3449}
3450
3451/*
Selene Huang31ab4042020-04-29 04:22:39 -07003452 * SigningOperationsTest.EcdsaAllCurves
3453 *
David Drysdale42fe1892021-10-14 14:43:46 +01003454 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003455 */
3456TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3457 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003458 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3459 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003460 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3461 .Authorization(TAG_NO_AUTH_REQUIRED)
3462 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003463 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003464 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003465 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3466 if (error != ErrorCode::OK) continue;
3467
3468 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003469 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003470 CheckedDeleteKey();
3471 }
3472}
3473
3474/*
David Drysdale42fe1892021-10-14 14:43:46 +01003475 * SigningOperationsTest.EcdsaCurve25519
3476 *
3477 * Verifies that ECDSA operations succeed with curve25519.
3478 */
3479TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3480 if (!Curve25519Supported()) {
3481 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3482 }
3483
3484 EcCurve curve = EcCurve::CURVE_25519;
3485 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3486 .Authorization(TAG_NO_AUTH_REQUIRED)
3487 .EcdsaSigningKey(curve)
3488 .Digest(Digest::NONE)
3489 .SetDefaultValidity());
3490 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3491
3492 string message(1024, 'a');
3493 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3494 CheckedDeleteKey();
3495}
3496
3497/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003498 * SigningOperationsTest.EcdsaCurve25519MaxSize
3499 *
3500 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3501 */
3502TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3503 if (!Curve25519Supported()) {
3504 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3505 }
3506
3507 EcCurve curve = EcCurve::CURVE_25519;
3508 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3509 .Authorization(TAG_NO_AUTH_REQUIRED)
3510 .EcdsaSigningKey(curve)
3511 .Digest(Digest::NONE)
3512 .SetDefaultValidity());
3513 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3514
3515 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3516
3517 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3518 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3519 string message(msg_size, 'a');
3520
3521 // Attempt to sign via Begin+Finish.
3522 AuthorizationSet out_params;
3523 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3524 EXPECT_TRUE(out_params.empty());
3525 string signature;
3526 auto result = Finish(message, &signature);
3527 EXPECT_EQ(result, ErrorCode::OK);
3528 LocalVerifyMessage(message, signature, params);
3529
3530 // Attempt to sign via Begin+Update+Finish
3531 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3532 EXPECT_TRUE(out_params.empty());
3533 string output;
3534 result = Update(message, &output);
3535 EXPECT_EQ(result, ErrorCode::OK);
3536 EXPECT_EQ(output.size(), 0);
3537 string signature2;
3538 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3539 LocalVerifyMessage(message, signature2, params);
3540 }
3541
3542 CheckedDeleteKey();
3543}
3544
3545/*
3546 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3547 *
3548 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3549 */
3550TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3551 if (!Curve25519Supported()) {
3552 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3553 }
3554
3555 EcCurve curve = EcCurve::CURVE_25519;
3556 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3557 .Authorization(TAG_NO_AUTH_REQUIRED)
3558 .EcdsaSigningKey(curve)
3559 .Digest(Digest::NONE)
3560 .SetDefaultValidity());
3561 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3562
3563 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3564
3565 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3566 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3567 string message(msg_size, 'a');
3568
3569 // Attempt to sign via Begin+Finish.
3570 AuthorizationSet out_params;
3571 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3572 EXPECT_TRUE(out_params.empty());
3573 string signature;
3574 auto result = Finish(message, &signature);
3575 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3576
3577 // Attempt to sign via Begin+Update (but never get to Finish)
3578 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3579 EXPECT_TRUE(out_params.empty());
3580 string output;
3581 result = Update(message, &output);
3582 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3583 }
3584
3585 CheckedDeleteKey();
3586}
3587
3588/*
Selene Huang31ab4042020-04-29 04:22:39 -07003589 * SigningOperationsTest.EcdsaNoDigestHugeData
3590 *
3591 * Verifies that ECDSA operations support very large messages, even without digesting. This
3592 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3593 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3594 * the framework.
3595 */
3596TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3597 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3598 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003599 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003600 .Digest(Digest::NONE)
3601 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003602 string message(1 * 1024, 'a');
3603 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3604}
3605
3606/*
3607 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3608 *
3609 * Verifies that using an EC key requires the correct app ID/data.
3610 */
3611TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3612 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3613 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003614 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003615 .Digest(Digest::NONE)
3616 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003617 .Authorization(TAG_APPLICATION_DATA, "appdata")
3618 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003619
3620 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3621
Selene Huang31ab4042020-04-29 04:22:39 -07003622 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3623 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3624 AbortIfNeeded();
3625 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3626 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3627 .Digest(Digest::NONE)
3628 .Authorization(TAG_APPLICATION_ID, "clientid")));
3629 AbortIfNeeded();
3630 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3631 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3632 .Digest(Digest::NONE)
3633 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3634 AbortIfNeeded();
3635 EXPECT_EQ(ErrorCode::OK,
3636 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3637 .Digest(Digest::NONE)
3638 .Authorization(TAG_APPLICATION_DATA, "appdata")
3639 .Authorization(TAG_APPLICATION_ID, "clientid")));
3640 AbortIfNeeded();
3641}
3642
3643/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003644 * SigningOperationsTest.EcdsaIncompatibleDigest
3645 *
3646 * Verifies that using an EC key requires compatible digest.
3647 */
3648TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3649 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3650 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003651 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003652 .Digest(Digest::NONE)
3653 .Digest(Digest::SHA1)
3654 .SetDefaultValidity()));
3655 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3656 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3657 AbortIfNeeded();
3658}
3659
3660/*
Selene Huang31ab4042020-04-29 04:22:39 -07003661 * SigningOperationsTest.AesEcbSign
3662 *
3663 * Verifies that attempts to use AES keys to sign fail in the correct way.
3664 */
3665TEST_P(SigningOperationsTest, AesEcbSign) {
3666 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3667 .Authorization(TAG_NO_AUTH_REQUIRED)
3668 .SigningKey()
3669 .AesEncryptionKey(128)
3670 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3671
3672 AuthorizationSet out_params;
3673 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3674 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3675 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3676 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3677}
3678
3679/*
3680 * SigningOperationsTest.HmacAllDigests
3681 *
3682 * Verifies that HMAC works with all digests.
3683 */
3684TEST_P(SigningOperationsTest, HmacAllDigests) {
3685 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003686 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003687 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3688 .Authorization(TAG_NO_AUTH_REQUIRED)
3689 .HmacKey(128)
3690 .Digest(digest)
3691 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3692 << "Failed to create HMAC key with digest " << digest;
3693 string message = "12345678901234567890123456789012";
3694 string signature = MacMessage(message, digest, 160);
3695 EXPECT_EQ(160U / 8U, signature.size())
3696 << "Failed to sign with HMAC key with digest " << digest;
3697 CheckedDeleteKey();
3698 }
3699}
3700
3701/*
3702 * SigningOperationsTest.HmacSha256TooLargeMacLength
3703 *
3704 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3705 * digest size.
3706 */
3707TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3708 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3709 .Authorization(TAG_NO_AUTH_REQUIRED)
3710 .HmacKey(128)
3711 .Digest(Digest::SHA_2_256)
3712 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3713 AuthorizationSet output_params;
3714 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3715 AuthorizationSetBuilder()
3716 .Digest(Digest::SHA_2_256)
3717 .Authorization(TAG_MAC_LENGTH, 264),
3718 &output_params));
3719}
3720
3721/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003722 * SigningOperationsTest.HmacSha256InvalidMacLength
3723 *
3724 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3725 * not a multiple of 8.
3726 */
3727TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3728 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3729 .Authorization(TAG_NO_AUTH_REQUIRED)
3730 .HmacKey(128)
3731 .Digest(Digest::SHA_2_256)
3732 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3733 AuthorizationSet output_params;
3734 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3735 AuthorizationSetBuilder()
3736 .Digest(Digest::SHA_2_256)
3737 .Authorization(TAG_MAC_LENGTH, 161),
3738 &output_params));
3739}
3740
3741/*
Selene Huang31ab4042020-04-29 04:22:39 -07003742 * SigningOperationsTest.HmacSha256TooSmallMacLength
3743 *
3744 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3745 * specified minimum MAC length.
3746 */
3747TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3748 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3749 .Authorization(TAG_NO_AUTH_REQUIRED)
3750 .HmacKey(128)
3751 .Digest(Digest::SHA_2_256)
3752 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3753 AuthorizationSet output_params;
3754 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3755 AuthorizationSetBuilder()
3756 .Digest(Digest::SHA_2_256)
3757 .Authorization(TAG_MAC_LENGTH, 120),
3758 &output_params));
3759}
3760
3761/*
3762 * SigningOperationsTest.HmacRfc4231TestCase3
3763 *
3764 * Validates against the test vectors from RFC 4231 test case 3.
3765 */
3766TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3767 string key(20, 0xaa);
3768 string message(50, 0xdd);
3769 uint8_t sha_224_expected[] = {
3770 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3771 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3772 };
3773 uint8_t sha_256_expected[] = {
3774 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3775 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3776 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3777 };
3778 uint8_t sha_384_expected[] = {
3779 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3780 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3781 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3782 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3783 };
3784 uint8_t sha_512_expected[] = {
3785 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3786 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3787 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3788 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3789 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3790 };
3791
3792 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3793 if (SecLevel() != SecurityLevel::STRONGBOX) {
3794 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3795 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3796 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3797 }
3798}
3799
3800/*
3801 * SigningOperationsTest.HmacRfc4231TestCase5
3802 *
3803 * Validates against the test vectors from RFC 4231 test case 5.
3804 */
3805TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3806 string key(20, 0x0c);
3807 string message = "Test With Truncation";
3808
3809 uint8_t sha_224_expected[] = {
3810 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3811 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3812 };
3813 uint8_t sha_256_expected[] = {
3814 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3815 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3816 };
3817 uint8_t sha_384_expected[] = {
3818 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3819 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3820 };
3821 uint8_t sha_512_expected[] = {
3822 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3823 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3824 };
3825
3826 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3827 if (SecLevel() != SecurityLevel::STRONGBOX) {
3828 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3829 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3830 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3831 }
3832}
3833
3834INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3835
3836typedef KeyMintAidlTestBase VerificationOperationsTest;
3837
3838/*
Selene Huang31ab4042020-04-29 04:22:39 -07003839 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3840 *
3841 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3842 */
3843TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3844 string key_material = "HelloThisIsAKey";
3845
3846 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003847 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003848 EXPECT_EQ(ErrorCode::OK,
3849 ImportKey(AuthorizationSetBuilder()
3850 .Authorization(TAG_NO_AUTH_REQUIRED)
3851 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3852 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3853 .Digest(Digest::SHA_2_256)
3854 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3855 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3856 EXPECT_EQ(ErrorCode::OK,
3857 ImportKey(AuthorizationSetBuilder()
3858 .Authorization(TAG_NO_AUTH_REQUIRED)
3859 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3860 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3861 .Digest(Digest::SHA_2_256)
3862 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3863 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3864
3865 string message = "This is a message.";
3866 string signature = SignMessage(
3867 signing_key, message,
3868 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3869
3870 // Signing key should not work.
3871 AuthorizationSet out_params;
3872 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3873 Begin(KeyPurpose::VERIFY, signing_key,
3874 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3875
3876 // Verification key should work.
3877 VerifyMessage(verification_key, message, signature,
3878 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3879
3880 CheckedDeleteKey(&signing_key);
3881 CheckedDeleteKey(&verification_key);
3882}
3883
Prashant Patildec9fdc2021-12-08 15:25:47 +00003884/*
3885 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3886 *
3887 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3888 */
3889TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3890 string key_material = "HelloThisIsAKey";
3891
3892 vector<uint8_t> signing_key, verification_key;
3893 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3894 EXPECT_EQ(ErrorCode::OK,
3895 ImportKey(AuthorizationSetBuilder()
3896 .Authorization(TAG_NO_AUTH_REQUIRED)
3897 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3898 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3899 .Digest(Digest::SHA_2_256)
3900 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3901 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3902 EXPECT_EQ(ErrorCode::OK,
3903 ImportKey(AuthorizationSetBuilder()
3904 .Authorization(TAG_NO_AUTH_REQUIRED)
3905 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3906 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3907 .Digest(Digest::SHA_2_256)
3908 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3909 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3910
3911 string message = "This is a message.";
3912 string signature = SignMessage(
3913 signing_key, message,
3914 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3915
3916 AuthorizationSet begin_out_params;
3917 ASSERT_EQ(ErrorCode::OK,
3918 Begin(KeyPurpose::VERIFY, verification_key,
3919 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3920
3921 string corruptMessage = "This is b message."; // Corrupted message
3922 string output;
3923 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3924
3925 ASSERT_EQ(ErrorCode::OK,
3926 Begin(KeyPurpose::VERIFY, verification_key,
3927 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3928
3929 signature[0] += 1; // Corrupt a signature
3930 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3931
3932 CheckedDeleteKey(&signing_key);
3933 CheckedDeleteKey(&verification_key);
3934}
3935
Selene Huang31ab4042020-04-29 04:22:39 -07003936INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3937
3938typedef KeyMintAidlTestBase ExportKeyTest;
3939
3940/*
3941 * ExportKeyTest.RsaUnsupportedKeyFormat
3942 *
3943 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3944 */
3945// TODO(seleneh) add ExportKey to GenerateKey
3946// check result
3947
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003948class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003949 public:
3950 template <TagType tag_type, Tag tag, typename ValueT>
3951 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3952 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003953 for (auto& entry : key_characteristics_) {
3954 if (entry.securityLevel == SecLevel()) {
3955 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3956 << "Tag " << tag << " with value " << expected
3957 << " not found at security level" << entry.securityLevel;
3958 } else {
3959 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3960 << "Tag " << tag << " found at security level " << entry.securityLevel;
3961 }
Selene Huang31ab4042020-04-29 04:22:39 -07003962 }
3963 }
3964
3965 void CheckOrigin() {
3966 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003967 // Origin isn't a crypto param, but it always lives with them.
3968 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003969 }
3970};
3971
3972/*
3973 * ImportKeyTest.RsaSuccess
3974 *
3975 * Verifies that importing and using an RSA key pair works correctly.
3976 */
3977TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003978 uint32_t key_size;
3979 string key;
3980
3981 if (SecLevel() == SecurityLevel::STRONGBOX) {
3982 key_size = 2048;
3983 key = rsa_2048_key;
3984 } else {
3985 key_size = 1024;
3986 key = rsa_key;
3987 }
3988
Selene Huang31ab4042020-04-29 04:22:39 -07003989 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3990 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003991 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003992 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003993 .Padding(PaddingMode::RSA_PSS)
3994 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003995 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003996
3997 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003998 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003999 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4000 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4001 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4002 CheckOrigin();
4003
4004 string message(1024 / 8, 'a');
4005 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4006 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004007 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004008}
4009
4010/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004011 * ImportKeyTest.RsaSuccessWithoutParams
4012 *
4013 * Verifies that importing and using an RSA key pair without specifying parameters
4014 * works correctly.
4015 */
4016TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
4017 uint32_t key_size;
4018 string key;
4019
4020 if (SecLevel() == SecurityLevel::STRONGBOX) {
4021 key_size = 2048;
4022 key = rsa_2048_key;
4023 } else {
4024 key_size = 1024;
4025 key = rsa_key;
4026 }
4027
4028 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4029 .Authorization(TAG_NO_AUTH_REQUIRED)
4030 .SigningKey()
4031 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4032 .Digest(Digest::SHA_2_256)
4033 .Padding(PaddingMode::RSA_PSS)
4034 .SetDefaultValidity(),
4035 KeyFormat::PKCS8, key));
4036
4037 // Key size and public exponent are determined from the imported key material.
4038 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4039 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4040
4041 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4042 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4043 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4044 CheckOrigin();
4045
4046 string message(1024 / 8, 'a');
4047 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4048 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004049 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004050}
4051
4052/*
Selene Huang31ab4042020-04-29 04:22:39 -07004053 * ImportKeyTest.RsaKeySizeMismatch
4054 *
4055 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4056 * correct way.
4057 */
4058TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4059 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4060 ImportKey(AuthorizationSetBuilder()
4061 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4062 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004063 .Padding(PaddingMode::NONE)
4064 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004065 KeyFormat::PKCS8, rsa_key));
4066}
4067
4068/*
4069 * ImportKeyTest.RsaPublicExponentMismatch
4070 *
4071 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4072 * fails in the correct way.
4073 */
4074TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4075 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4076 ImportKey(AuthorizationSetBuilder()
4077 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4078 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004079 .Padding(PaddingMode::NONE)
4080 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004081 KeyFormat::PKCS8, rsa_key));
4082}
4083
4084/*
David Drysdalee60248c2021-10-04 12:54:13 +01004085 * ImportKeyTest.RsaAttestMultiPurposeFail
4086 *
4087 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4088 */
4089TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004090 if (AidlVersion() < 2) {
4091 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4092 // with other key purposes. However, this was not checked at the time
4093 // so we can only be strict about checking this for implementations of KeyMint
4094 // version 2 and above.
4095 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4096 }
David Drysdalee60248c2021-10-04 12:54:13 +01004097 uint32_t key_size = 2048;
4098 string key = rsa_2048_key;
4099
4100 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4101 ImportKey(AuthorizationSetBuilder()
4102 .Authorization(TAG_NO_AUTH_REQUIRED)
4103 .RsaSigningKey(key_size, 65537)
4104 .AttestKey()
4105 .Digest(Digest::SHA_2_256)
4106 .Padding(PaddingMode::RSA_PSS)
4107 .SetDefaultValidity(),
4108 KeyFormat::PKCS8, key));
4109}
4110
4111/*
Selene Huang31ab4042020-04-29 04:22:39 -07004112 * ImportKeyTest.EcdsaSuccess
4113 *
4114 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4115 */
4116TEST_P(ImportKeyTest, EcdsaSuccess) {
4117 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4118 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004119 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004120 .Digest(Digest::SHA_2_256)
4121 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004122 KeyFormat::PKCS8, ec_256_key));
4123
4124 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004125 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4126 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4127
4128 CheckOrigin();
4129
4130 string message(32, 'a');
4131 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4132 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004133 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004134}
4135
4136/*
4137 * ImportKeyTest.EcdsaP256RFC5915Success
4138 *
4139 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4140 * correctly.
4141 */
4142TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4143 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4144 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004145 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004146 .Digest(Digest::SHA_2_256)
4147 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004148 KeyFormat::PKCS8, ec_256_key_rfc5915));
4149
4150 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004151 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4152 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4153
4154 CheckOrigin();
4155
4156 string message(32, 'a');
4157 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4158 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004159 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004160}
4161
4162/*
4163 * ImportKeyTest.EcdsaP256SEC1Success
4164 *
4165 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4166 */
4167TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4168 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4169 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004170 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004171 .Digest(Digest::SHA_2_256)
4172 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004173 KeyFormat::PKCS8, ec_256_key_sec1));
4174
4175 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004176 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4177 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4178
4179 CheckOrigin();
4180
4181 string message(32, 'a');
4182 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4183 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004184 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004185}
4186
4187/*
4188 * ImportKeyTest.Ecdsa521Success
4189 *
4190 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4191 */
4192TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004193 if (SecLevel() == SecurityLevel::STRONGBOX) {
4194 GTEST_SKIP() << "Test not applicable to StrongBox device";
4195 }
Selene Huang31ab4042020-04-29 04:22:39 -07004196 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4197 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004198 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004199 .Digest(Digest::SHA_2_256)
4200 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004201 KeyFormat::PKCS8, ec_521_key));
4202
4203 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004204 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4205 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4206 CheckOrigin();
4207
4208 string message(32, 'a');
4209 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4210 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004211 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004212}
4213
4214/*
Selene Huang31ab4042020-04-29 04:22:39 -07004215 * ImportKeyTest.EcdsaCurveMismatch
4216 *
4217 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4218 * the correct way.
4219 */
4220TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4221 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4222 ImportKey(AuthorizationSetBuilder()
4223 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004224 .Digest(Digest::NONE)
4225 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004226 KeyFormat::PKCS8, ec_256_key));
4227}
4228
4229/*
David Drysdalee60248c2021-10-04 12:54:13 +01004230 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4231 *
4232 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4233 */
4234TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004235 if (AidlVersion() < 2) {
4236 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4237 // with other key purposes. However, this was not checked at the time
4238 // so we can only be strict about checking this for implementations of KeyMint
4239 // version 2 and above.
4240 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4241 }
David Drysdalee60248c2021-10-04 12:54:13 +01004242 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4243 ImportKey(AuthorizationSetBuilder()
4244 .Authorization(TAG_NO_AUTH_REQUIRED)
4245 .EcdsaSigningKey(EcCurve::P_256)
4246 .AttestKey()
4247 .Digest(Digest::SHA_2_256)
4248 .SetDefaultValidity(),
4249 KeyFormat::PKCS8, ec_256_key));
4250}
4251
4252/*
David Drysdale42fe1892021-10-14 14:43:46 +01004253 * ImportKeyTest.Ed25519RawSuccess
4254 *
4255 * Verifies that importing and using a raw Ed25519 private key works correctly.
4256 */
4257TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4258 if (!Curve25519Supported()) {
4259 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4260 }
4261
4262 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4263 .Authorization(TAG_NO_AUTH_REQUIRED)
4264 .EcdsaSigningKey(EcCurve::CURVE_25519)
4265 .Digest(Digest::NONE)
4266 .SetDefaultValidity(),
4267 KeyFormat::RAW, ed25519_key));
4268 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4269 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4270 CheckOrigin();
4271
4272 // The returned cert should hold the correct public key.
4273 ASSERT_GT(cert_chain_.size(), 0);
4274 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4275 ASSERT_NE(kmKeyCert, nullptr);
4276 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4277 ASSERT_NE(kmPubKey.get(), nullptr);
4278 size_t kmPubKeySize = 32;
4279 uint8_t kmPubKeyData[32];
4280 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4281 ASSERT_EQ(kmPubKeySize, 32);
4282 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4283
4284 string message(32, 'a');
4285 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4286 string signature = SignMessage(message, params);
4287 LocalVerifyMessage(message, signature, params);
4288}
4289
4290/*
4291 * ImportKeyTest.Ed25519Pkcs8Success
4292 *
4293 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4294 */
4295TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4296 if (!Curve25519Supported()) {
4297 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4298 }
4299
4300 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4301 .Authorization(TAG_NO_AUTH_REQUIRED)
4302 .EcdsaSigningKey(EcCurve::CURVE_25519)
4303 .Digest(Digest::NONE)
4304 .SetDefaultValidity(),
4305 KeyFormat::PKCS8, ed25519_pkcs8_key));
4306 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4307 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4308 CheckOrigin();
4309
4310 // The returned cert should hold the correct public key.
4311 ASSERT_GT(cert_chain_.size(), 0);
4312 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4313 ASSERT_NE(kmKeyCert, nullptr);
4314 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4315 ASSERT_NE(kmPubKey.get(), nullptr);
4316 size_t kmPubKeySize = 32;
4317 uint8_t kmPubKeyData[32];
4318 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4319 ASSERT_EQ(kmPubKeySize, 32);
4320 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4321
4322 string message(32, 'a');
4323 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4324 string signature = SignMessage(message, params);
4325 LocalVerifyMessage(message, signature, params);
4326}
4327
4328/*
4329 * ImportKeyTest.Ed25519CurveMismatch
4330 *
4331 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4332 * the correct way.
4333 */
4334TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4335 if (!Curve25519Supported()) {
4336 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4337 }
4338
4339 ASSERT_NE(ErrorCode::OK,
4340 ImportKey(AuthorizationSetBuilder()
4341 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4342 .Digest(Digest::NONE)
4343 .SetDefaultValidity(),
4344 KeyFormat::RAW, ed25519_key));
4345}
4346
4347/*
4348 * ImportKeyTest.Ed25519FormatMismatch
4349 *
4350 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4351 */
4352TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4353 if (!Curve25519Supported()) {
4354 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4355 }
4356
4357 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4358 .EcdsaSigningKey(EcCurve::CURVE_25519)
4359 .Digest(Digest::NONE)
4360 .SetDefaultValidity(),
4361 KeyFormat::PKCS8, ed25519_key));
4362 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4363 .EcdsaSigningKey(EcCurve::CURVE_25519)
4364 .Digest(Digest::NONE)
4365 .SetDefaultValidity(),
4366 KeyFormat::RAW, ed25519_pkcs8_key));
4367}
4368
4369/*
4370 * ImportKeyTest.Ed25519PurposeMismatch
4371 *
4372 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4373 */
4374TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4375 if (!Curve25519Supported()) {
4376 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4377 }
4378
4379 // Can't have both SIGN and ATTEST_KEY
4380 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4381 .EcdsaSigningKey(EcCurve::CURVE_25519)
4382 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4383 .Digest(Digest::NONE)
4384 .SetDefaultValidity(),
4385 KeyFormat::RAW, ed25519_key));
4386 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4387 // PKCS#8 format and so includes an OID).
4388 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4389 .EcdsaKey(EcCurve::CURVE_25519)
4390 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4391 .Digest(Digest::NONE)
4392 .SetDefaultValidity(),
4393 KeyFormat::PKCS8, ed25519_pkcs8_key));
4394}
4395
4396/*
4397 * ImportKeyTest.X25519RawSuccess
4398 *
4399 * Verifies that importing and using a raw X25519 private key works correctly.
4400 */
4401TEST_P(ImportKeyTest, X25519RawSuccess) {
4402 if (!Curve25519Supported()) {
4403 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4404 }
4405
4406 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4407 .Authorization(TAG_NO_AUTH_REQUIRED)
4408 .EcdsaKey(EcCurve::CURVE_25519)
4409 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4410 .SetDefaultValidity(),
4411 KeyFormat::RAW, x25519_key));
4412
4413 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4414 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4415 CheckOrigin();
4416}
4417
4418/*
4419 * ImportKeyTest.X25519Pkcs8Success
4420 *
4421 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4422 */
4423TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4424 if (!Curve25519Supported()) {
4425 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4426 }
4427
4428 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4429 .Authorization(TAG_NO_AUTH_REQUIRED)
4430 .EcdsaKey(EcCurve::CURVE_25519)
4431 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4432 .SetDefaultValidity(),
4433 KeyFormat::PKCS8, x25519_pkcs8_key));
4434
4435 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4436 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4437 CheckOrigin();
4438}
4439
4440/*
4441 * ImportKeyTest.X25519CurveMismatch
4442 *
4443 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4444 * the correct way.
4445 */
4446TEST_P(ImportKeyTest, X25519CurveMismatch) {
4447 if (!Curve25519Supported()) {
4448 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4449 }
4450
4451 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4452 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4453 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4454 .SetDefaultValidity(),
4455 KeyFormat::RAW, x25519_key));
4456}
4457
4458/*
4459 * ImportKeyTest.X25519FormatMismatch
4460 *
4461 * Verifies that importing an X25519 key with an invalid format fails.
4462 */
4463TEST_P(ImportKeyTest, X25519FormatMismatch) {
4464 if (!Curve25519Supported()) {
4465 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4466 }
4467
4468 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4469 .EcdsaKey(EcCurve::CURVE_25519)
4470 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4471 .SetDefaultValidity(),
4472 KeyFormat::PKCS8, x25519_key));
4473 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4474 .EcdsaKey(EcCurve::CURVE_25519)
4475 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4476 .SetDefaultValidity(),
4477 KeyFormat::RAW, x25519_pkcs8_key));
4478}
4479
4480/*
4481 * ImportKeyTest.X25519PurposeMismatch
4482 *
4483 * Verifies that importing an X25519 key pair with an invalid format fails.
4484 */
4485TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4486 if (!Curve25519Supported()) {
4487 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4488 }
4489
4490 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4491 .EcdsaKey(EcCurve::CURVE_25519)
4492 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4493 .SetDefaultValidity(),
4494 KeyFormat::PKCS8, x25519_pkcs8_key));
4495 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4496 .EcdsaSigningKey(EcCurve::CURVE_25519)
4497 .SetDefaultValidity(),
4498 KeyFormat::PKCS8, x25519_pkcs8_key));
4499}
4500
4501/*
Selene Huang31ab4042020-04-29 04:22:39 -07004502 * ImportKeyTest.AesSuccess
4503 *
4504 * Verifies that importing and using an AES key works.
4505 */
4506TEST_P(ImportKeyTest, AesSuccess) {
4507 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4508 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4509 .Authorization(TAG_NO_AUTH_REQUIRED)
4510 .AesEncryptionKey(key.size() * 8)
4511 .EcbMode()
4512 .Padding(PaddingMode::PKCS7),
4513 KeyFormat::RAW, key));
4514
4515 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4516 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4517 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4518 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4519 CheckOrigin();
4520
4521 string message = "Hello World!";
4522 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4523 string ciphertext = EncryptMessage(message, params);
4524 string plaintext = DecryptMessage(ciphertext, params);
4525 EXPECT_EQ(message, plaintext);
4526}
4527
4528/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004529 * ImportKeyTest.AesFailure
4530 *
4531 * Verifies that importing an invalid AES key fails.
4532 */
4533TEST_P(ImportKeyTest, AesFailure) {
4534 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4535 uint32_t bitlen = key.size() * 8;
4536 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004537 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004538 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004539 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004540 .Authorization(TAG_NO_AUTH_REQUIRED)
4541 .AesEncryptionKey(key_size)
4542 .EcbMode()
4543 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004544 KeyFormat::RAW, key);
4545 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004546 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4547 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004548 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004549
4550 // Explicit key size matches that of the provided key, but it's not a valid size.
4551 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4552 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4553 ImportKey(AuthorizationSetBuilder()
4554 .Authorization(TAG_NO_AUTH_REQUIRED)
4555 .AesEncryptionKey(long_key.size() * 8)
4556 .EcbMode()
4557 .Padding(PaddingMode::PKCS7),
4558 KeyFormat::RAW, long_key));
4559 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4560 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4561 ImportKey(AuthorizationSetBuilder()
4562 .Authorization(TAG_NO_AUTH_REQUIRED)
4563 .AesEncryptionKey(short_key.size() * 8)
4564 .EcbMode()
4565 .Padding(PaddingMode::PKCS7),
4566 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004567}
4568
4569/*
4570 * ImportKeyTest.TripleDesSuccess
4571 *
4572 * Verifies that importing and using a 3DES key works.
4573 */
4574TEST_P(ImportKeyTest, TripleDesSuccess) {
4575 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4576 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4577 .Authorization(TAG_NO_AUTH_REQUIRED)
4578 .TripleDesEncryptionKey(168)
4579 .EcbMode()
4580 .Padding(PaddingMode::PKCS7),
4581 KeyFormat::RAW, key));
4582
4583 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4584 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4585 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4586 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4587 CheckOrigin();
4588
4589 string message = "Hello World!";
4590 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4591 string ciphertext = EncryptMessage(message, params);
4592 string plaintext = DecryptMessage(ciphertext, params);
4593 EXPECT_EQ(message, plaintext);
4594}
4595
4596/*
4597 * ImportKeyTest.TripleDesFailure
4598 *
4599 * Verifies that importing an invalid 3DES key fails.
4600 */
4601TEST_P(ImportKeyTest, TripleDesFailure) {
4602 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004603 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004604 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004605 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004606 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004607 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004608 .Authorization(TAG_NO_AUTH_REQUIRED)
4609 .TripleDesEncryptionKey(key_size)
4610 .EcbMode()
4611 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004612 KeyFormat::RAW, key);
4613 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004614 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4615 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004616 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004617 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004618 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004619 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4620 ImportKey(AuthorizationSetBuilder()
4621 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004622 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004623 .EcbMode()
4624 .Padding(PaddingMode::PKCS7),
4625 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004626 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004627 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4628 ImportKey(AuthorizationSetBuilder()
4629 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004630 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004631 .EcbMode()
4632 .Padding(PaddingMode::PKCS7),
4633 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004634}
4635
4636/*
4637 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004638 *
4639 * Verifies that importing and using an HMAC key works.
4640 */
4641TEST_P(ImportKeyTest, HmacKeySuccess) {
4642 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4643 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4644 .Authorization(TAG_NO_AUTH_REQUIRED)
4645 .HmacKey(key.size() * 8)
4646 .Digest(Digest::SHA_2_256)
4647 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4648 KeyFormat::RAW, key));
4649
4650 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4651 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4652 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4653 CheckOrigin();
4654
4655 string message = "Hello World!";
4656 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4657 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4658}
4659
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004660/*
4661 * ImportKeyTest.GetKeyCharacteristics
4662 *
4663 * Verifies that imported keys have the correct characteristics.
4664 */
4665TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4666 vector<uint8_t> key_blob;
4667 vector<KeyCharacteristics> key_characteristics;
4668 auto base_builder = AuthorizationSetBuilder()
4669 .Padding(PaddingMode::NONE)
4670 .Authorization(TAG_NO_AUTH_REQUIRED)
4671 .SetDefaultValidity();
4672 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4673 Algorithm::TRIPLE_DES};
4674 ErrorCode result;
4675 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4676 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4677 for (auto alg : algorithms) {
4678 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4679 AuthorizationSetBuilder builder(base_builder);
4680 switch (alg) {
4681 case Algorithm::RSA:
4682 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4683
4684 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4685 &key_characteristics);
4686 break;
4687 case Algorithm::EC:
4688 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4689 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4690 &key_characteristics);
4691 break;
4692 case Algorithm::HMAC:
4693 builder.HmacKey(128)
4694 .Digest(Digest::SHA_2_256)
4695 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4696 result =
4697 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4698 break;
4699 case Algorithm::AES:
4700 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4701 result =
4702 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4703 break;
4704 case Algorithm::TRIPLE_DES:
4705 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4706 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4707 &key_characteristics);
4708 break;
4709 default:
4710 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4711 continue;
4712 }
4713 ASSERT_EQ(ErrorCode::OK, result);
4714 CheckCharacteristics(key_blob, key_characteristics);
4715 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4716 }
4717}
4718
Selene Huang31ab4042020-04-29 04:22:39 -07004719INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4720
4721auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004722 // IKeyMintDevice.aidl
4723 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4724 "020100" // INTEGER length 1 value 0x00 (version)
4725 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4726 "934bf94e2aa28a3f83c9f79297250262"
4727 "fbe3276b5a1c91159bbfa3ef8957aac8"
4728 "4b59b30b455a79c2973480823d8b3863"
4729 "c3deef4a8e243590268d80e18751a0e1"
4730 "30f67ce6a1ace9f79b95e097474febc9"
4731 "81195b1d13a69086c0863f66a7b7fdb4"
4732 "8792227b1ac5e2489febdf087ab54864"
4733 "83033a6f001ca5d1ec1e27f5c30f4cec"
4734 "2642074a39ae68aee552e196627a8e3d"
4735 "867e67a8c01b11e75f13cca0a97ab668"
4736 "b50cda07a8ecb7cd8e3dd7009c963653"
4737 "4f6f239cffe1fc8daa466f78b676c711"
4738 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4739 "99b801597d5220e307eaa5bee507fb94"
4740 "d1fa69f9e519b2de315bac92c36f2ea1"
4741 "fa1df4478c0ddedeae8c70e0233cd098"
4742 "040c" // OCTET STRING length 0x0c (initializationVector)
4743 "d796b02c370f1fa4cc0124f1"
4744 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4745 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4746 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4747 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4748 "3106" // SET length 0x06
4749 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4750 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4751 // } end SET
4752 // } end [1]
4753 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4754 "020120" // INTEGER length 1 value 0x20 (AES)
4755 // } end [2]
4756 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4757 "02020100" // INTEGER length 2 value 0x100
4758 // } end [3]
4759 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4760 "3103" // SET length 0x03 {
4761 "020101" // INTEGER length 1 value 0x01 (ECB)
4762 // } end SET
4763 // } end [4]
4764 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4765 "3103" // SET length 0x03 {
4766 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4767 // } end SET
4768 // } end [5]
4769 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4770 // (noAuthRequired)
4771 "0500" // NULL
4772 // } end [503]
4773 // } end SEQUENCE (AuthorizationList)
4774 // } end SEQUENCE (KeyDescription)
4775 "0420" // OCTET STRING length 0x20 (encryptedKey)
4776 "ccd540855f833a5e1480bfd2d36faf3a"
4777 "eee15df5beabe2691bc82dde2a7aa910"
4778 "0410" // OCTET STRING length 0x10 (tag)
4779 "64c9f689c60ff6223ab6e6999e0eb6e5"
4780 // } SEQUENCE (SecureKeyWrapper)
4781);
Selene Huang31ab4042020-04-29 04:22:39 -07004782
4783auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004784 // IKeyMintDevice.aidl
4785 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4786 "020100" // INTEGER length 1 value 0x00 (version)
4787 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4788 "aad93ed5924f283b4bb5526fbe7a1412"
4789 "f9d9749ec30db9062b29e574a8546f33"
4790 "c88732452f5b8e6a391ee76c39ed1712"
4791 "c61d8df6213dec1cffbc17a8c6d04c7b"
4792 "30893d8daa9b2015213e219468215532"
4793 "07f8f9931c4caba23ed3bee28b36947e"
4794 "47f10e0a5c3dc51c988a628daad3e5e1"
4795 "f4005e79c2d5a96c284b4b8d7e4948f3"
4796 "31e5b85dd5a236f85579f3ea1d1b8484"
4797 "87470bdb0ab4f81a12bee42c99fe0df4"
4798 "bee3759453e69ad1d68a809ce06b949f"
4799 "7694a990429b2fe81e066ff43e56a216"
4800 "02db70757922a4bcc23ab89f1e35da77"
4801 "586775f423e519c2ea394caf48a28d0c"
4802 "8020f1dcf6b3a68ec246f615ae96dae9"
4803 "a079b1f6eb959033c1af5c125fd94168"
4804 "040c" // OCTET STRING length 0x0c (initializationVector)
4805 "6d9721d08589581ab49204a3"
4806 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4807 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4808 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4809 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4810 "3106" // SET length 0x06
4811 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4812 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4813 // } end SET
4814 // } end [1]
4815 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4816 "020120" // INTEGER length 1 value 0x20 (AES)
4817 // } end [2]
4818 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4819 "02020100" // INTEGER length 2 value 0x100
4820 // } end [3]
4821 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4822 "3103" // SET length 0x03 {
4823 "020101" // INTEGER length 1 value 0x01 (ECB)
4824 // } end SET
4825 // } end [4]
4826 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4827 "3103" // SET length 0x03 {
4828 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4829 // } end SET
4830 // } end [5]
4831 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4832 // (noAuthRequired)
4833 "0500" // NULL
4834 // } end [503]
4835 // } end SEQUENCE (AuthorizationList)
4836 // } end SEQUENCE (KeyDescription)
4837 "0420" // OCTET STRING length 0x20 (encryptedKey)
4838 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4839 "c20d1f99a9a024a76f35c8e2cab9b68d"
4840 "0410" // OCTET STRING length 0x10 (tag)
4841 "2560c70109ae67c030f00b98b512a670"
4842 // } SEQUENCE (SecureKeyWrapper)
4843);
Selene Huang31ab4042020-04-29 04:22:39 -07004844
4845auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004846 // RFC 5208 s5
4847 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4848 "020100" // INTEGER length 1 value 0x00 (version)
4849 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4850 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4851 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4852 "0500" // NULL (parameters)
4853 // } SEQUENCE (AlgorithmIdentifier)
4854 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4855 // RFC 8017 A.1.2
4856 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4857 "020100" // INTEGER length 1 value 0x00 (version)
4858 "02820101" // INTEGER length 0x0101 (modulus) value...
4859 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4860 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4861 "7b06e673a837313d56b1c725150a3fef" // 0x30
4862 "86acbddc41bb759c2854eae32d35841e" // 0x40
4863 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4864 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4865 "312d7bd5921ffaea1347c157406fef71" // 0x70
4866 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4867 "f4645c11f5c1374c3886427411c44979" // 0x90
4868 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4869 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4870 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4871 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4872 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4873 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4874 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4875 "55" // 0x101
4876 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4877 "02820100" // INTEGER length 0x100 (privateExponent) value...
4878 "431447b6251908112b1ee76f99f3711a" // 0x10
4879 "52b6630960046c2de70de188d833f8b8" // 0x20
4880 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4881 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4882 "e710b630a03adc683b5d2c43080e52be" // 0x50
4883 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4884 "822bccff087d63c940ba8a45f670feb2" // 0x70
4885 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4886 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4887 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4888 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4889 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4890 "52659d5a5ba05b663737a8696281865b" // 0xd0
4891 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4892 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4893 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4894 "028181" // INTEGER length 0x81 (prime1) value...
4895 "00de392e18d682c829266cc3454e1d61" // 0x10
4896 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4897 "ff841be5bac82a164c5970007047b8c5" // 0x30
4898 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4899 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4900 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4901 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4902 "9e91346130748a6e3c124f9149d71c74" // 0x80
4903 "35"
4904 "028181" // INTEGER length 0x81 (prime2) value...
4905 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4906 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4907 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4908 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4909 "9ed39a2d934c880440aed8832f984316" // 0x50
4910 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4911 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4912 "b880677c068e1be936e81288815252a8" // 0x80
4913 "a1"
4914 "028180" // INTEGER length 0x80 (exponent1) value...
4915 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4916 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4917 "5a063212a4f105a3764743e53281988a" // 0x30
4918 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4919 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4920 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4921 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4922 "4719d6e2b9439823719cd08bcd031781" // 0x80
4923 "028181" // INTEGER length 0x81 (exponent2) value...
4924 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4925 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4926 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4927 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4928 "1254186af30b22c10582a8a43e34fe94" // 0x50
4929 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4930 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4931 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4932 "61"
4933 "028181" // INTEGER length 0x81 (coefficient) value...
4934 "00c931617c77829dfb1270502be9195c" // 0x10
4935 "8f2830885f57dba869536811e6864236" // 0x20
4936 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4937 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4938 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4939 "959356210723287b0affcc9f727044d4" // 0x60
4940 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4941 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4942 "22"
4943 // } SEQUENCE
4944 // } SEQUENCE ()
4945);
Selene Huang31ab4042020-04-29 04:22:39 -07004946
4947string zero_masking_key =
4948 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4949string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4950
4951class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4952
4953TEST_P(ImportWrappedKeyTest, Success) {
4954 auto wrapping_key_desc = AuthorizationSetBuilder()
4955 .RsaEncryptionKey(2048, 65537)
4956 .Digest(Digest::SHA_2_256)
4957 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004958 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4959 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004960
4961 ASSERT_EQ(ErrorCode::OK,
4962 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4963 AuthorizationSetBuilder()
4964 .Digest(Digest::SHA_2_256)
4965 .Padding(PaddingMode::RSA_OAEP)));
4966
4967 string message = "Hello World!";
4968 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4969 string ciphertext = EncryptMessage(message, params);
4970 string plaintext = DecryptMessage(ciphertext, params);
4971 EXPECT_EQ(message, plaintext);
4972}
4973
David Drysdaled2cc8c22021-04-15 13:29:45 +01004974/*
4975 * ImportWrappedKeyTest.SuccessSidsIgnored
4976 *
4977 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4978 * include Tag:USER_SECURE_ID.
4979 */
4980TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4981 auto wrapping_key_desc = AuthorizationSetBuilder()
4982 .RsaEncryptionKey(2048, 65537)
4983 .Digest(Digest::SHA_2_256)
4984 .Padding(PaddingMode::RSA_OAEP)
4985 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4986 .SetDefaultValidity();
4987
4988 int64_t password_sid = 42;
4989 int64_t biometric_sid = 24;
4990 ASSERT_EQ(ErrorCode::OK,
4991 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4992 AuthorizationSetBuilder()
4993 .Digest(Digest::SHA_2_256)
4994 .Padding(PaddingMode::RSA_OAEP),
4995 password_sid, biometric_sid));
4996
4997 string message = "Hello World!";
4998 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4999 string ciphertext = EncryptMessage(message, params);
5000 string plaintext = DecryptMessage(ciphertext, params);
5001 EXPECT_EQ(message, plaintext);
5002}
5003
Selene Huang31ab4042020-04-29 04:22:39 -07005004TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5005 auto wrapping_key_desc = AuthorizationSetBuilder()
5006 .RsaEncryptionKey(2048, 65537)
5007 .Digest(Digest::SHA_2_256)
5008 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005009 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5010 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005011
5012 ASSERT_EQ(ErrorCode::OK,
5013 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5014 AuthorizationSetBuilder()
5015 .Digest(Digest::SHA_2_256)
5016 .Padding(PaddingMode::RSA_OAEP)));
5017}
5018
5019TEST_P(ImportWrappedKeyTest, WrongMask) {
5020 auto wrapping_key_desc = AuthorizationSetBuilder()
5021 .RsaEncryptionKey(2048, 65537)
5022 .Digest(Digest::SHA_2_256)
5023 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005024 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5025 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005026
5027 ASSERT_EQ(
5028 ErrorCode::VERIFICATION_FAILED,
5029 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5030 AuthorizationSetBuilder()
5031 .Digest(Digest::SHA_2_256)
5032 .Padding(PaddingMode::RSA_OAEP)));
5033}
5034
5035TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5036 auto wrapping_key_desc = AuthorizationSetBuilder()
5037 .RsaEncryptionKey(2048, 65537)
5038 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005039 .Padding(PaddingMode::RSA_OAEP)
5040 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07005041
5042 ASSERT_EQ(
5043 ErrorCode::INCOMPATIBLE_PURPOSE,
5044 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5045 AuthorizationSetBuilder()
5046 .Digest(Digest::SHA_2_256)
5047 .Padding(PaddingMode::RSA_OAEP)));
5048}
5049
David Drysdaled2cc8c22021-04-15 13:29:45 +01005050TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5051 auto wrapping_key_desc = AuthorizationSetBuilder()
5052 .RsaEncryptionKey(2048, 65537)
5053 .Digest(Digest::SHA_2_256)
5054 .Padding(PaddingMode::RSA_PSS)
5055 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5056 .SetDefaultValidity();
5057
5058 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5059 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5060 AuthorizationSetBuilder()
5061 .Digest(Digest::SHA_2_256)
5062 .Padding(PaddingMode::RSA_OAEP)));
5063}
5064
5065TEST_P(ImportWrappedKeyTest, WrongDigest) {
5066 auto wrapping_key_desc = AuthorizationSetBuilder()
5067 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005068 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005069 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005070 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5071 .SetDefaultValidity();
5072
5073 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5074 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5075 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08005076 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01005077 .Padding(PaddingMode::RSA_OAEP)));
5078}
5079
Selene Huang31ab4042020-04-29 04:22:39 -07005080INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5081
5082typedef KeyMintAidlTestBase EncryptionOperationsTest;
5083
5084/*
5085 * EncryptionOperationsTest.RsaNoPaddingSuccess
5086 *
David Drysdale59cae642021-05-12 13:52:03 +01005087 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07005088 */
5089TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00005090 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005091 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005092 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5093 .Authorization(TAG_NO_AUTH_REQUIRED)
5094 .RsaEncryptionKey(2048, exponent)
5095 .Padding(PaddingMode::NONE)
5096 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005097
David Drysdaled2cc8c22021-04-15 13:29:45 +01005098 string message = string(2048 / 8, 'a');
5099 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005100 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005101 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005102
David Drysdale59cae642021-05-12 13:52:03 +01005103 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005104 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005105
David Drysdaled2cc8c22021-04-15 13:29:45 +01005106 // Unpadded RSA is deterministic
5107 EXPECT_EQ(ciphertext1, ciphertext2);
5108
5109 CheckedDeleteKey();
5110 }
Selene Huang31ab4042020-04-29 04:22:39 -07005111}
5112
5113/*
5114 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5115 *
David Drysdale59cae642021-05-12 13:52:03 +01005116 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005117 */
5118TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5119 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5120 .Authorization(TAG_NO_AUTH_REQUIRED)
5121 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005122 .Padding(PaddingMode::NONE)
5123 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005124
5125 string message = "1";
5126 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5127
David Drysdale59cae642021-05-12 13:52:03 +01005128 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005129 EXPECT_EQ(2048U / 8, ciphertext.size());
5130
5131 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5132 string plaintext = DecryptMessage(ciphertext, params);
5133
5134 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005135}
5136
5137/*
Selene Huang31ab4042020-04-29 04:22:39 -07005138 * EncryptionOperationsTest.RsaOaepSuccess
5139 *
David Drysdale59cae642021-05-12 13:52:03 +01005140 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005141 */
5142TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5143 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5144
5145 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01005146 ASSERT_EQ(ErrorCode::OK,
5147 GenerateKey(AuthorizationSetBuilder()
5148 .Authorization(TAG_NO_AUTH_REQUIRED)
5149 .RsaEncryptionKey(key_size, 65537)
5150 .Padding(PaddingMode::RSA_OAEP)
5151 .Digest(digests)
5152 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
5153 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005154
5155 string message = "Hello";
5156
5157 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005158 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5159
5160 auto params = AuthorizationSetBuilder()
5161 .Digest(digest)
5162 .Padding(PaddingMode::RSA_OAEP)
5163 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5164 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005165 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5166 EXPECT_EQ(key_size / 8, ciphertext1.size());
5167
David Drysdale59cae642021-05-12 13:52:03 +01005168 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005169 EXPECT_EQ(key_size / 8, ciphertext2.size());
5170
5171 // OAEP randomizes padding so every result should be different (with astronomically high
5172 // probability).
5173 EXPECT_NE(ciphertext1, ciphertext2);
5174
5175 string plaintext1 = DecryptMessage(ciphertext1, params);
5176 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5177 string plaintext2 = DecryptMessage(ciphertext2, params);
5178 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5179
5180 // Decrypting corrupted ciphertext should fail.
5181 size_t offset_to_corrupt = random() % ciphertext1.size();
5182 char corrupt_byte;
5183 do {
5184 corrupt_byte = static_cast<char>(random() % 256);
5185 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5186 ciphertext1[offset_to_corrupt] = corrupt_byte;
5187
5188 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5189 string result;
5190 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5191 EXPECT_EQ(0U, result.size());
5192 }
5193}
5194
5195/*
5196 * EncryptionOperationsTest.RsaOaepInvalidDigest
5197 *
David Drysdale59cae642021-05-12 13:52:03 +01005198 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005199 * without a digest.
5200 */
5201TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5202 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5203 .Authorization(TAG_NO_AUTH_REQUIRED)
5204 .RsaEncryptionKey(2048, 65537)
5205 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005206 .Digest(Digest::NONE)
5207 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005208
5209 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005210 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005211}
5212
5213/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005214 * EncryptionOperationsTest.RsaOaepInvalidPadding
5215 *
David Drysdale59cae642021-05-12 13:52:03 +01005216 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005217 * with a padding value that is only suitable for signing/verifying.
5218 */
5219TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5220 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5221 .Authorization(TAG_NO_AUTH_REQUIRED)
5222 .RsaEncryptionKey(2048, 65537)
5223 .Padding(PaddingMode::RSA_PSS)
5224 .Digest(Digest::NONE)
5225 .SetDefaultValidity()));
5226
5227 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005228 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005229}
5230
5231/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005232 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005233 *
David Drysdale59cae642021-05-12 13:52:03 +01005234 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005235 * with a different digest than was used to encrypt.
5236 */
5237TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005238 if (SecLevel() == SecurityLevel::STRONGBOX) {
5239 GTEST_SKIP() << "Test not applicable to StrongBox device";
5240 }
Selene Huang31ab4042020-04-29 04:22:39 -07005241
5242 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5243 .Authorization(TAG_NO_AUTH_REQUIRED)
5244 .RsaEncryptionKey(1024, 65537)
5245 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005246 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5247 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005248 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005249 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005250 message,
5251 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5252
5253 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5254 .Digest(Digest::SHA_2_256)
5255 .Padding(PaddingMode::RSA_OAEP)));
5256 string result;
5257 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5258 EXPECT_EQ(0U, result.size());
5259}
5260
5261/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005262 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5263 *
David Drysdale59cae642021-05-12 13:52:03 +01005264 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005265 * digests.
5266 */
5267TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5268 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5269
5270 size_t key_size = 2048; // Need largish key for SHA-512 test.
5271 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5272 .OaepMGFDigest(digests)
5273 .Authorization(TAG_NO_AUTH_REQUIRED)
5274 .RsaEncryptionKey(key_size, 65537)
5275 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005276 .Digest(Digest::SHA_2_256)
5277 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005278
5279 string message = "Hello";
5280
5281 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005282 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005283 auto params = AuthorizationSetBuilder()
5284 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5285 .Digest(Digest::SHA_2_256)
5286 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005287 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005288 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5289 EXPECT_EQ(key_size / 8, ciphertext1.size());
5290
David Drysdale59cae642021-05-12 13:52:03 +01005291 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005292 EXPECT_EQ(key_size / 8, ciphertext2.size());
5293
5294 // OAEP randomizes padding so every result should be different (with astronomically high
5295 // probability).
5296 EXPECT_NE(ciphertext1, ciphertext2);
5297
5298 string plaintext1 = DecryptMessage(ciphertext1, params);
5299 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5300 string plaintext2 = DecryptMessage(ciphertext2, params);
5301 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5302
5303 // Decrypting corrupted ciphertext should fail.
5304 size_t offset_to_corrupt = random() % ciphertext1.size();
5305 char corrupt_byte;
5306 do {
5307 corrupt_byte = static_cast<char>(random() % 256);
5308 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5309 ciphertext1[offset_to_corrupt] = corrupt_byte;
5310
5311 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5312 string result;
5313 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5314 EXPECT_EQ(0U, result.size());
5315 }
5316}
5317
5318/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005319 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5320 *
5321 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5322 * specified, defaulting to SHA-1.
5323 */
5324TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5325 size_t key_size = 2048;
5326 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5327 .Authorization(TAG_NO_AUTH_REQUIRED)
5328 .RsaEncryptionKey(key_size, 65537)
5329 .Padding(PaddingMode::RSA_OAEP)
5330 .Digest(Digest::SHA_2_256)
5331 .SetDefaultValidity()));
5332
5333 // Do local RSA encryption using the default MGF digest of SHA-1.
5334 string message = "Hello";
5335 auto params =
5336 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5337 string ciphertext = LocalRsaEncryptMessage(message, params);
5338 EXPECT_EQ(key_size / 8, ciphertext.size());
5339
5340 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5341 string plaintext = DecryptMessage(ciphertext, params);
5342 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5343
5344 // Decrypting corrupted ciphertext should fail.
5345 size_t offset_to_corrupt = random() % ciphertext.size();
5346 char corrupt_byte;
5347 do {
5348 corrupt_byte = static_cast<char>(random() % 256);
5349 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5350 ciphertext[offset_to_corrupt] = corrupt_byte;
5351
5352 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5353 string result;
5354 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5355 EXPECT_EQ(0U, result.size());
5356}
5357
5358/*
5359 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5360 *
5361 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5362 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5363 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5364 */
5365TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5366 size_t key_size = 2048;
5367 ASSERT_EQ(ErrorCode::OK,
5368 GenerateKey(AuthorizationSetBuilder()
5369 .Authorization(TAG_NO_AUTH_REQUIRED)
5370 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5371 .RsaEncryptionKey(key_size, 65537)
5372 .Padding(PaddingMode::RSA_OAEP)
5373 .Digest(Digest::SHA_2_256)
5374 .SetDefaultValidity()));
5375
5376 // Do local RSA encryption using the default MGF digest of SHA-1.
5377 string message = "Hello";
5378 auto params =
5379 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5380 string ciphertext = LocalRsaEncryptMessage(message, params);
5381 EXPECT_EQ(key_size / 8, ciphertext.size());
5382
5383 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5384 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5385 // is checked against those values, and found absent.
5386 auto result = Begin(KeyPurpose::DECRYPT, params);
5387 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5388 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5389}
5390
5391/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005392 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5393 *
David Drysdale59cae642021-05-12 13:52:03 +01005394 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005395 * with incompatible MGF digest.
5396 */
5397TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5398 ASSERT_EQ(ErrorCode::OK,
5399 GenerateKey(AuthorizationSetBuilder()
5400 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5401 .Authorization(TAG_NO_AUTH_REQUIRED)
5402 .RsaEncryptionKey(2048, 65537)
5403 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005404 .Digest(Digest::SHA_2_256)
5405 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005406 string message = "Hello World!";
5407
5408 auto params = AuthorizationSetBuilder()
5409 .Padding(PaddingMode::RSA_OAEP)
5410 .Digest(Digest::SHA_2_256)
5411 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005412 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005413}
5414
5415/*
5416 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5417 *
5418 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5419 * with unsupported MGF digest.
5420 */
5421TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5422 ASSERT_EQ(ErrorCode::OK,
5423 GenerateKey(AuthorizationSetBuilder()
5424 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5425 .Authorization(TAG_NO_AUTH_REQUIRED)
5426 .RsaEncryptionKey(2048, 65537)
5427 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005428 .Digest(Digest::SHA_2_256)
5429 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005430 string message = "Hello World!";
5431
5432 auto params = AuthorizationSetBuilder()
5433 .Padding(PaddingMode::RSA_OAEP)
5434 .Digest(Digest::SHA_2_256)
5435 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005436 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005437}
5438
5439/*
Selene Huang31ab4042020-04-29 04:22:39 -07005440 * EncryptionOperationsTest.RsaPkcs1Success
5441 *
5442 * Verifies that RSA PKCS encryption/decrypts works.
5443 */
5444TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5445 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5446 .Authorization(TAG_NO_AUTH_REQUIRED)
5447 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005448 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5449 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005450
5451 string message = "Hello World!";
5452 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005453 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005454 EXPECT_EQ(2048U / 8, ciphertext1.size());
5455
David Drysdale59cae642021-05-12 13:52:03 +01005456 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005457 EXPECT_EQ(2048U / 8, ciphertext2.size());
5458
5459 // PKCS1 v1.5 randomizes padding so every result should be different.
5460 EXPECT_NE(ciphertext1, ciphertext2);
5461
5462 string plaintext = DecryptMessage(ciphertext1, params);
5463 EXPECT_EQ(message, plaintext);
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;
5475 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5476 EXPECT_EQ(0U, result.size());
5477}
5478
5479/*
Selene Huang31ab4042020-04-29 04:22:39 -07005480 * EncryptionOperationsTest.EcdsaEncrypt
5481 *
5482 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5483 */
5484TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5485 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5486 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005487 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005488 .Digest(Digest::NONE)
5489 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005490 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5491 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5492 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5493}
5494
5495/*
5496 * EncryptionOperationsTest.HmacEncrypt
5497 *
5498 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5499 */
5500TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5501 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5502 .Authorization(TAG_NO_AUTH_REQUIRED)
5503 .HmacKey(128)
5504 .Digest(Digest::SHA_2_256)
5505 .Padding(PaddingMode::NONE)
5506 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5507 auto params = AuthorizationSetBuilder()
5508 .Digest(Digest::SHA_2_256)
5509 .Padding(PaddingMode::NONE)
5510 .Authorization(TAG_MAC_LENGTH, 128);
5511 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5512 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5513}
5514
5515/*
5516 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5517 *
5518 * Verifies that AES ECB mode works.
5519 */
5520TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5521 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5522 .Authorization(TAG_NO_AUTH_REQUIRED)
5523 .AesEncryptionKey(128)
5524 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5525 .Padding(PaddingMode::NONE)));
5526
5527 ASSERT_GT(key_blob_.size(), 0U);
5528 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5529
5530 // Two-block message.
5531 string message = "12345678901234567890123456789012";
5532 string ciphertext1 = EncryptMessage(message, params);
5533 EXPECT_EQ(message.size(), ciphertext1.size());
5534
5535 string ciphertext2 = EncryptMessage(string(message), params);
5536 EXPECT_EQ(message.size(), ciphertext2.size());
5537
5538 // ECB is deterministic.
5539 EXPECT_EQ(ciphertext1, ciphertext2);
5540
5541 string plaintext = DecryptMessage(ciphertext1, params);
5542 EXPECT_EQ(message, plaintext);
5543}
5544
5545/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005546 * EncryptionOperationsTest.AesEcbUnknownTag
5547 *
5548 * Verifies that AES ECB operations ignore unknown tags.
5549 */
5550TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5551 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5552 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5553 KeyParameter unknown_param;
5554 unknown_param.tag = unknown_tag;
5555
5556 vector<KeyCharacteristics> key_characteristics;
5557 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5558 .Authorization(TAG_NO_AUTH_REQUIRED)
5559 .AesEncryptionKey(128)
5560 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5561 .Padding(PaddingMode::NONE)
5562 .Authorization(unknown_param),
5563 &key_blob_, &key_characteristics));
5564 ASSERT_GT(key_blob_.size(), 0U);
5565
5566 // Unknown tags should not be returned in key characteristics.
5567 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5568 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5569 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5570 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5571
5572 // Encrypt without mentioning the unknown parameter.
5573 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5574 string message = "12345678901234567890123456789012";
5575 string ciphertext = EncryptMessage(message, params);
5576 EXPECT_EQ(message.size(), ciphertext.size());
5577
5578 // Decrypt including the unknown parameter.
5579 auto decrypt_params = AuthorizationSetBuilder()
5580 .BlockMode(BlockMode::ECB)
5581 .Padding(PaddingMode::NONE)
5582 .Authorization(unknown_param);
5583 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5584 EXPECT_EQ(message, plaintext);
5585}
5586
5587/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005588 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005589 *
5590 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5591 */
5592TEST_P(EncryptionOperationsTest, AesWrongMode) {
5593 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5594 .Authorization(TAG_NO_AUTH_REQUIRED)
5595 .AesEncryptionKey(128)
5596 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5597 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005598 ASSERT_GT(key_blob_.size(), 0U);
5599
Selene Huang31ab4042020-04-29 04:22:39 -07005600 EXPECT_EQ(
5601 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5602 Begin(KeyPurpose::ENCRYPT,
5603 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5604}
5605
5606/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005607 * EncryptionOperationsTest.AesWrongPadding
5608 *
5609 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5610 */
5611TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5612 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5613 .Authorization(TAG_NO_AUTH_REQUIRED)
5614 .AesEncryptionKey(128)
5615 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5616 .Padding(PaddingMode::NONE)));
5617 ASSERT_GT(key_blob_.size(), 0U);
5618
5619 EXPECT_EQ(
5620 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5621 Begin(KeyPurpose::ENCRYPT,
5622 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5623}
5624
5625/*
5626 * EncryptionOperationsTest.AesInvalidParams
5627 *
5628 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5629 */
5630TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5631 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5632 .Authorization(TAG_NO_AUTH_REQUIRED)
5633 .AesEncryptionKey(128)
5634 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5635 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5636 .Padding(PaddingMode::NONE)
5637 .Padding(PaddingMode::PKCS7)));
5638 ASSERT_GT(key_blob_.size(), 0U);
5639
5640 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5641 .BlockMode(BlockMode::CBC)
5642 .BlockMode(BlockMode::ECB)
5643 .Padding(PaddingMode::NONE));
5644 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5645 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5646
5647 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5648 .BlockMode(BlockMode::ECB)
5649 .Padding(PaddingMode::NONE)
5650 .Padding(PaddingMode::PKCS7));
5651 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5652 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5653}
5654
5655/*
Selene Huang31ab4042020-04-29 04:22:39 -07005656 * EncryptionOperationsTest.AesWrongPurpose
5657 *
5658 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5659 * specified.
5660 */
5661TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5662 auto err = GenerateKey(AuthorizationSetBuilder()
5663 .Authorization(TAG_NO_AUTH_REQUIRED)
5664 .AesKey(128)
5665 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5666 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5667 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5668 .Padding(PaddingMode::NONE));
5669 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5670 ASSERT_GT(key_blob_.size(), 0U);
5671
5672 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5673 .BlockMode(BlockMode::GCM)
5674 .Padding(PaddingMode::NONE)
5675 .Authorization(TAG_MAC_LENGTH, 128));
5676 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5677
5678 CheckedDeleteKey();
5679
5680 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5681 .Authorization(TAG_NO_AUTH_REQUIRED)
5682 .AesKey(128)
5683 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5684 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5685 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5686 .Padding(PaddingMode::NONE)));
5687
5688 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5689 .BlockMode(BlockMode::GCM)
5690 .Padding(PaddingMode::NONE)
5691 .Authorization(TAG_MAC_LENGTH, 128));
5692 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5693}
5694
5695/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005696 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005697 *
5698 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5699 * multiple of the block size and no padding is specified.
5700 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005701TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5702 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005703 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005704 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5705 .Authorization(TAG_NO_AUTH_REQUIRED)
5706 .AesEncryptionKey(128)
5707 .Authorization(TAG_BLOCK_MODE, blockMode)
5708 .Padding(PaddingMode::NONE)));
5709 // Message is slightly shorter than two blocks.
5710 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005711
David Drysdaled2cc8c22021-04-15 13:29:45 +01005712 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5713 AuthorizationSet out_params;
5714 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5715 string ciphertext;
5716 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5717 EXPECT_EQ(0U, ciphertext.size());
5718
5719 CheckedDeleteKey();
5720 }
Selene Huang31ab4042020-04-29 04:22:39 -07005721}
5722
5723/*
5724 * EncryptionOperationsTest.AesEcbPkcs7Padding
5725 *
5726 * Verifies that AES PKCS7 padding works for any message length.
5727 */
5728TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5729 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5730 .Authorization(TAG_NO_AUTH_REQUIRED)
5731 .AesEncryptionKey(128)
5732 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5733 .Padding(PaddingMode::PKCS7)));
5734
5735 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5736
5737 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005738 for (size_t i = 0; i <= 48; i++) {
5739 SCOPED_TRACE(testing::Message() << "i = " << i);
5740 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5741 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005742 string ciphertext = EncryptMessage(message, params);
5743 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5744 string plaintext = DecryptMessage(ciphertext, params);
5745 EXPECT_EQ(message, plaintext);
5746 }
5747}
5748
5749/*
5750 * EncryptionOperationsTest.AesEcbWrongPadding
5751 *
5752 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5753 * specified.
5754 */
5755TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5756 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5757 .Authorization(TAG_NO_AUTH_REQUIRED)
5758 .AesEncryptionKey(128)
5759 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5760 .Padding(PaddingMode::NONE)));
5761
5762 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5763
5764 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005765 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005766 string message(i, 'a');
5767 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5768 }
5769}
5770
5771/*
5772 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5773 *
5774 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5775 */
5776TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5777 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5778 .Authorization(TAG_NO_AUTH_REQUIRED)
5779 .AesEncryptionKey(128)
5780 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5781 .Padding(PaddingMode::PKCS7)));
5782
5783 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5784
5785 string message = "a";
5786 string ciphertext = EncryptMessage(message, params);
5787 EXPECT_EQ(16U, ciphertext.size());
5788 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005789
Seth Moore7a55ae32021-06-23 14:28:11 -07005790 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5791 ++ciphertext[ciphertext.size() / 2];
5792
5793 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5794 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005795 ErrorCode error = Finish(ciphertext, &plaintext);
5796 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005797 // This is the expected error, we can exit the test now.
5798 return;
5799 } else {
5800 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005801 ASSERT_EQ(error, ErrorCode::OK)
5802 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005803 }
5804 }
5805 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005806}
5807
David Drysdaleb8093292022-04-08 12:22:35 +01005808/*
5809 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5810 *
5811 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5812 */
5813TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5814 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5815 .Authorization(TAG_NO_AUTH_REQUIRED)
5816 .AesEncryptionKey(128)
5817 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5818 .Padding(PaddingMode::PKCS7)));
5819
5820 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5821
5822 string message = "a";
5823 string ciphertext = EncryptMessage(message, params);
5824 EXPECT_EQ(16U, ciphertext.size());
5825 EXPECT_NE(ciphertext, message);
5826
5827 // Shorten the ciphertext.
5828 ciphertext.resize(ciphertext.size() - 1);
5829 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5830 string plaintext;
5831 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5832}
5833
Selene Huang31ab4042020-04-29 04:22:39 -07005834vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5835 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005836 EXPECT_TRUE(iv);
5837 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005838}
5839
5840/*
5841 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5842 *
5843 * Verifies that AES CTR mode works.
5844 */
5845TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5846 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5847 .Authorization(TAG_NO_AUTH_REQUIRED)
5848 .AesEncryptionKey(128)
5849 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5850 .Padding(PaddingMode::NONE)));
5851
5852 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5853
5854 string message = "123";
5855 AuthorizationSet out_params;
5856 string ciphertext1 = EncryptMessage(message, params, &out_params);
5857 vector<uint8_t> iv1 = CopyIv(out_params);
5858 EXPECT_EQ(16U, iv1.size());
5859
5860 EXPECT_EQ(message.size(), ciphertext1.size());
5861
5862 out_params.Clear();
5863 string ciphertext2 = EncryptMessage(message, params, &out_params);
5864 vector<uint8_t> iv2 = CopyIv(out_params);
5865 EXPECT_EQ(16U, iv2.size());
5866
5867 // IVs should be random, so ciphertexts should differ.
5868 EXPECT_NE(ciphertext1, ciphertext2);
5869
5870 auto params_iv1 =
5871 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5872 auto params_iv2 =
5873 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5874
5875 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5876 EXPECT_EQ(message, plaintext);
5877 plaintext = DecryptMessage(ciphertext2, params_iv2);
5878 EXPECT_EQ(message, plaintext);
5879
5880 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5881 plaintext = DecryptMessage(ciphertext1, params_iv2);
5882 EXPECT_NE(message, plaintext);
5883 plaintext = DecryptMessage(ciphertext2, params_iv1);
5884 EXPECT_NE(message, plaintext);
5885}
5886
5887/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305888 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005889 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305890 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005891 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305892TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5893 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5894}
Selene Huang31ab4042020-04-29 04:22:39 -07005895
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305896/*
5897 * EncryptionOperationsTest.AesCbcIncremental
5898 *
5899 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5900 */
5901TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5902 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5903}
Selene Huang31ab4042020-04-29 04:22:39 -07005904
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305905/*
5906 * EncryptionOperationsTest.AesCtrIncremental
5907 *
5908 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5909 */
5910TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5911 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5912}
Selene Huang31ab4042020-04-29 04:22:39 -07005913
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305914/*
5915 * EncryptionOperationsTest.AesGcmIncremental
5916 *
5917 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5918 */
5919TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5920 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005921}
5922
Prashant Patildd5f7f02022-07-06 18:58:07 +00005923/*
5924 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
5925 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5926 */
5927TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
5928 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
5929 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
5930 string kat_plaintext =
5931 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
5932 "809FFF37081C22EF278F896AB213A2A631");
5933 string kat_ciphertext =
5934 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
5935 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
5936 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5937 kat_ciphertext);
5938}
5939
5940/*
5941 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
5942 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5943 */
5944TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
5945 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
5946 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
5947 string kat_plaintext =
5948 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
5949 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
5950 string kat_ciphertext =
5951 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
5952 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
5953 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5954 kat_plaintext, kat_ciphertext);
5955}
5956
5957/*
5958 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
5959 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5960 */
5961TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
5962 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
5963 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
5964 string kat_plaintext =
5965 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
5966 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
5967 string kat_ciphertext =
5968 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
5969 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
5970 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
5971 kat_ciphertext);
5972}
5973
5974/*
5975 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
5976 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
5977 */
5978TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
5979 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
5980 string kat_plaintext =
5981 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
5982 "7B6168A9A27BCE554BEA94EF26E6C742A0");
5983 string kat_ciphertext =
5984 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
5985 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
5986 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
5987 kat_ciphertext);
5988}
5989
5990/*
5991 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
5992 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
5993 */
5994TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
5995 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
5996 string kat_plaintext =
5997 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
5998 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
5999 string kat_ciphertext =
6000 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6001 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6002 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6003 kat_ciphertext);
6004}
6005
6006/*
6007 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6008 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6009 */
6010TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6011 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6012 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6013 string kat_plaintext =
6014 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6015 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6016 string kat_ciphertext =
6017 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6018 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6019 "bdfcc0cba0");
6020
6021 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6022 kat_ciphertext);
6023}
6024
6025/*
6026 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6027 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6028 */
6029TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6030 if (SecLevel() == SecurityLevel::STRONGBOX) {
6031 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6032 }
6033 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6034 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6035 string kat_plaintext =
6036 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6037 "167f2497c994bd496eb80bfb2ba2c9d5af");
6038 string kat_ciphertext =
6039 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6040 "72c134552f3a138e726fbe493b3a839598");
6041 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6042 kat_ciphertext);
6043}
6044
6045/*
6046 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6047 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6048 */
6049TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6050 if (SecLevel() == SecurityLevel::STRONGBOX) {
6051 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6052 }
6053 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6054 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6055 string kat_plaintext =
6056 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6057 "b170");
6058 string kat_ciphertext =
6059 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6060 "4e3884138ff403a41fd99818708ada301c");
6061 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6062 kat_plaintext, kat_ciphertext);
6063}
6064
6065/*
6066 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6067 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6068 */
6069TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6070 if (SecLevel() == SecurityLevel::STRONGBOX) {
6071 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6072 }
6073 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6074 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6075 string kat_plaintext =
6076 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6077 "28091e09cdbbd3b42b");
6078 string kat_ciphertext =
6079 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6080 "2ae0f90f0c19f42b4a");
6081 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6082 kat_ciphertext);
6083}
6084
6085/*
6086 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6087 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6088 */
6089TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6090 if (SecLevel() == SecurityLevel::STRONGBOX) {
6091 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6092 }
6093 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6094 string kat_plaintext =
6095 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6096 "44ab");
6097 string kat_ciphertext =
6098 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6099 "2453");
6100 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6101 kat_ciphertext);
6102}
6103
6104/*
6105 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6106 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6107 */
6108TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6109 if (SecLevel() == SecurityLevel::STRONGBOX) {
6110 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6111 }
6112 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6113 string kat_plaintext =
6114 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6115 "e2c7");
6116 string kat_ciphertext =
6117 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6118 "bb7e3a889dd4a9589098b44acf1056e7aa");
6119 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6120 kat_ciphertext);
6121}
6122
6123/*
6124 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6125 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6126 */
6127TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6128 if (SecLevel() == SecurityLevel::STRONGBOX) {
6129 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6130 }
6131 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6132 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6133 string kat_plaintext =
6134 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6135 "ff52");
6136 string kat_ciphertext =
6137 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6138 "1413ad70fb0e1970669095ad77ebb5974ae8");
6139
6140 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6141 kat_ciphertext);
6142}
6143
6144/*
6145 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6146 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6147 */
6148TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6149 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6150 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6151 string kat_plaintext =
6152 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6153 "494cb53caca353e4b637ba05687be20f8d");
6154 string kat_ciphertext =
6155 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6156 "6047da1e4fd7c4e1cf2656097f75ae8685");
6157 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6158 kat_ciphertext);
6159}
6160
6161/*
6162 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6163 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6164 */
6165TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6166 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6167 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6168 string kat_plaintext =
6169 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6170 "2545a82b73c48078b9dae62261c65909");
6171 string kat_ciphertext =
6172 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6173 "9403a71987b95124073d69f2a3cb95b0ab");
6174 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6175 kat_plaintext, kat_ciphertext);
6176}
6177
6178/*
6179 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6180 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6181 */
6182TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6183 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6184 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6185 string kat_plaintext =
6186 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6187 "1f6db3c884");
6188 string kat_ciphertext =
6189 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6190 "a7be30d4c3");
6191 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6192 kat_ciphertext);
6193}
6194
6195/*
6196 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6197 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6198 */
6199TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6200 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6201 string kat_plaintext =
6202 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6203 "31a476d6806b8116089c6ec50bb543200f");
6204 string kat_ciphertext =
6205 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6206 "c83e377faf246288931136bef2a07c0be4");
6207 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6208 kat_ciphertext);
6209}
6210
6211/*
6212 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6213 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6214 */
6215TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6216 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6217 string kat_plaintext =
6218 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6219 "6f");
6220 string kat_ciphertext =
6221 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6222 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6223 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6224 kat_ciphertext);
6225}
6226
6227/*
6228 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6229 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6230 */
6231TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6232 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6233 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6234 string kat_plaintext =
6235 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6236 "f0");
6237 string kat_ciphertext =
6238 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6239 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6240
6241 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6242 kat_ciphertext);
6243}
6244
Selene Huang31ab4042020-04-29 04:22:39 -07006245struct AesCtrSp80038aTestVector {
6246 const char* key;
6247 const char* nonce;
6248 const char* plaintext;
6249 const char* ciphertext;
6250};
6251
6252// These test vectors are taken from
6253// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6254static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6255 // AES-128
6256 {
6257 "2b7e151628aed2a6abf7158809cf4f3c",
6258 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6259 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6260 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6261 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6262 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6263 },
6264 // AES-192
6265 {
6266 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6267 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6268 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6269 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6270 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6271 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6272 },
6273 // AES-256
6274 {
6275 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6276 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6277 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6278 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6279 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6280 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6281 },
6282};
6283
6284/*
6285 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6286 *
6287 * Verifies AES CTR implementation against SP800-38A test vectors.
6288 */
6289TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6290 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6291 for (size_t i = 0; i < 3; i++) {
6292 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6293 const string key = hex2str(test.key);
6294 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6295 InvalidSizes.end())
6296 continue;
6297 const string nonce = hex2str(test.nonce);
6298 const string plaintext = hex2str(test.plaintext);
6299 const string ciphertext = hex2str(test.ciphertext);
6300 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6301 }
6302}
6303
6304/*
6305 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6306 *
6307 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6308 */
6309TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6310 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6311 .Authorization(TAG_NO_AUTH_REQUIRED)
6312 .AesEncryptionKey(128)
6313 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6314 .Padding(PaddingMode::PKCS7)));
6315 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6316 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6317}
6318
6319/*
6320 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6321 *
6322 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6323 */
6324TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6325 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6326 .Authorization(TAG_NO_AUTH_REQUIRED)
6327 .AesEncryptionKey(128)
6328 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6329 .Authorization(TAG_CALLER_NONCE)
6330 .Padding(PaddingMode::NONE)));
6331
6332 auto params = AuthorizationSetBuilder()
6333 .BlockMode(BlockMode::CTR)
6334 .Padding(PaddingMode::NONE)
6335 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6336 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6337
6338 params = AuthorizationSetBuilder()
6339 .BlockMode(BlockMode::CTR)
6340 .Padding(PaddingMode::NONE)
6341 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6342 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6343
6344 params = AuthorizationSetBuilder()
6345 .BlockMode(BlockMode::CTR)
6346 .Padding(PaddingMode::NONE)
6347 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6348 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6349}
6350
6351/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006352 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006353 *
6354 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6355 */
6356TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6357 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6358 .Authorization(TAG_NO_AUTH_REQUIRED)
6359 .AesEncryptionKey(128)
6360 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6361 .Padding(PaddingMode::NONE)));
6362 // Two-block message.
6363 string message = "12345678901234567890123456789012";
6364 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6365 AuthorizationSet out_params;
6366 string ciphertext1 = EncryptMessage(message, params, &out_params);
6367 vector<uint8_t> iv1 = CopyIv(out_params);
6368 EXPECT_EQ(message.size(), ciphertext1.size());
6369
6370 out_params.Clear();
6371
6372 string ciphertext2 = EncryptMessage(message, params, &out_params);
6373 vector<uint8_t> iv2 = CopyIv(out_params);
6374 EXPECT_EQ(message.size(), ciphertext2.size());
6375
6376 // IVs should be random, so ciphertexts should differ.
6377 EXPECT_NE(ciphertext1, ciphertext2);
6378
6379 params.push_back(TAG_NONCE, iv1);
6380 string plaintext = DecryptMessage(ciphertext1, params);
6381 EXPECT_EQ(message, plaintext);
6382}
6383
6384/*
Tommy Chiuee705692021-09-23 20:09:13 +08006385 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6386 *
6387 * Verifies that keymaster generates correct output on zero-input with
6388 * NonePadding mode
6389 */
6390TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6391 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6392 .Authorization(TAG_NO_AUTH_REQUIRED)
6393 .AesEncryptionKey(128)
6394 .BlockMode(BlockMode::CBC)
6395 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6396
6397 // Zero input message
6398 string message = "";
6399 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006400 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006401 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6402 AuthorizationSet out_params;
6403 string ciphertext1 = EncryptMessage(message, params, &out_params);
6404 vector<uint8_t> iv1 = CopyIv(out_params);
6405 if (padding == PaddingMode::NONE)
6406 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6407 else
6408 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6409
6410 out_params.Clear();
6411
6412 string ciphertext2 = EncryptMessage(message, params, &out_params);
6413 vector<uint8_t> iv2 = CopyIv(out_params);
6414 if (padding == PaddingMode::NONE)
6415 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6416 else
6417 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6418
6419 // IVs should be random
6420 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6421
6422 params.push_back(TAG_NONCE, iv1);
6423 string plaintext = DecryptMessage(ciphertext1, params);
6424 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6425 }
6426}
6427
6428/*
Selene Huang31ab4042020-04-29 04:22:39 -07006429 * EncryptionOperationsTest.AesCallerNonce
6430 *
6431 * Verifies that AES caller-provided nonces work correctly.
6432 */
6433TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6434 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6435 .Authorization(TAG_NO_AUTH_REQUIRED)
6436 .AesEncryptionKey(128)
6437 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6438 .Authorization(TAG_CALLER_NONCE)
6439 .Padding(PaddingMode::NONE)));
6440
6441 string message = "12345678901234567890123456789012";
6442
6443 // Don't specify nonce, should get a random one.
6444 AuthorizationSetBuilder params =
6445 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6446 AuthorizationSet out_params;
6447 string ciphertext = EncryptMessage(message, params, &out_params);
6448 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006449 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006450
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006451 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006452 string plaintext = DecryptMessage(ciphertext, params);
6453 EXPECT_EQ(message, plaintext);
6454
6455 // Now specify a nonce, should also work.
6456 params = AuthorizationSetBuilder()
6457 .BlockMode(BlockMode::CBC)
6458 .Padding(PaddingMode::NONE)
6459 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6460 out_params.Clear();
6461 ciphertext = EncryptMessage(message, params, &out_params);
6462
6463 // Decrypt with correct nonce.
6464 plaintext = DecryptMessage(ciphertext, params);
6465 EXPECT_EQ(message, plaintext);
6466
6467 // Try with wrong nonce.
6468 params = AuthorizationSetBuilder()
6469 .BlockMode(BlockMode::CBC)
6470 .Padding(PaddingMode::NONE)
6471 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6472 plaintext = DecryptMessage(ciphertext, params);
6473 EXPECT_NE(message, plaintext);
6474}
6475
6476/*
6477 * EncryptionOperationsTest.AesCallerNonceProhibited
6478 *
6479 * Verifies that caller-provided nonces are not permitted when not specified in the key
6480 * authorizations.
6481 */
6482TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6483 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6484 .Authorization(TAG_NO_AUTH_REQUIRED)
6485 .AesEncryptionKey(128)
6486 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6487 .Padding(PaddingMode::NONE)));
6488
6489 string message = "12345678901234567890123456789012";
6490
6491 // Don't specify nonce, should get a random one.
6492 AuthorizationSetBuilder params =
6493 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6494 AuthorizationSet out_params;
6495 string ciphertext = EncryptMessage(message, params, &out_params);
6496 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006497 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006498
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006499 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006500 string plaintext = DecryptMessage(ciphertext, params);
6501 EXPECT_EQ(message, plaintext);
6502
6503 // Now specify a nonce, should fail
6504 params = AuthorizationSetBuilder()
6505 .BlockMode(BlockMode::CBC)
6506 .Padding(PaddingMode::NONE)
6507 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6508 out_params.Clear();
6509 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6510}
6511
6512/*
6513 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6514 *
6515 * Verifies that AES GCM mode works.
6516 */
6517TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6518 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6519 .Authorization(TAG_NO_AUTH_REQUIRED)
6520 .AesEncryptionKey(128)
6521 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6522 .Padding(PaddingMode::NONE)
6523 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6524
6525 string aad = "foobar";
6526 string message = "123456789012345678901234567890123456";
6527
6528 auto begin_params = AuthorizationSetBuilder()
6529 .BlockMode(BlockMode::GCM)
6530 .Padding(PaddingMode::NONE)
6531 .Authorization(TAG_MAC_LENGTH, 128);
6532
Selene Huang31ab4042020-04-29 04:22:39 -07006533 // Encrypt
6534 AuthorizationSet begin_out_params;
6535 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6536 << "Begin encrypt";
6537 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006538 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6539 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006540 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6541
6542 // Grab nonce
6543 begin_params.push_back(begin_out_params);
6544
6545 // Decrypt.
6546 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006547 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006548 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006549 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006550 EXPECT_EQ(message.length(), plaintext.length());
6551 EXPECT_EQ(message, plaintext);
6552}
6553
6554/*
6555 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6556 *
6557 * Verifies that AES GCM mode works, even when there's a long delay
6558 * between operations.
6559 */
6560TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6561 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6562 .Authorization(TAG_NO_AUTH_REQUIRED)
6563 .AesEncryptionKey(128)
6564 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6565 .Padding(PaddingMode::NONE)
6566 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6567
6568 string aad = "foobar";
6569 string message = "123456789012345678901234567890123456";
6570
6571 auto begin_params = AuthorizationSetBuilder()
6572 .BlockMode(BlockMode::GCM)
6573 .Padding(PaddingMode::NONE)
6574 .Authorization(TAG_MAC_LENGTH, 128);
6575
Selene Huang31ab4042020-04-29 04:22:39 -07006576 // Encrypt
6577 AuthorizationSet begin_out_params;
6578 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6579 << "Begin encrypt";
6580 string ciphertext;
6581 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006582 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006583 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006584 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006585
6586 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6587
6588 // Grab nonce
6589 begin_params.push_back(begin_out_params);
6590
6591 // Decrypt.
6592 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6593 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006594 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006595 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006596 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006597 sleep(5);
6598 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6599 EXPECT_EQ(message.length(), plaintext.length());
6600 EXPECT_EQ(message, plaintext);
6601}
6602
6603/*
6604 * EncryptionOperationsTest.AesGcmDifferentNonces
6605 *
6606 * Verifies that encrypting the same data with different nonces produces different outputs.
6607 */
6608TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6609 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6610 .Authorization(TAG_NO_AUTH_REQUIRED)
6611 .AesEncryptionKey(128)
6612 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6613 .Padding(PaddingMode::NONE)
6614 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6615 .Authorization(TAG_CALLER_NONCE)));
6616
6617 string aad = "foobar";
6618 string message = "123456789012345678901234567890123456";
6619 string nonce1 = "000000000000";
6620 string nonce2 = "111111111111";
6621 string nonce3 = "222222222222";
6622
6623 string ciphertext1 =
6624 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6625 string ciphertext2 =
6626 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6627 string ciphertext3 =
6628 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6629
6630 ASSERT_NE(ciphertext1, ciphertext2);
6631 ASSERT_NE(ciphertext1, ciphertext3);
6632 ASSERT_NE(ciphertext2, ciphertext3);
6633}
6634
6635/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006636 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6637 *
6638 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6639 */
6640TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6641 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6642 .Authorization(TAG_NO_AUTH_REQUIRED)
6643 .AesEncryptionKey(128)
6644 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6645 .Padding(PaddingMode::NONE)
6646 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6647
6648 string aad = "foobar";
6649 string message = "123456789012345678901234567890123456";
6650
6651 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6652 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6653 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6654
6655 ASSERT_NE(ciphertext1, ciphertext2);
6656 ASSERT_NE(ciphertext1, ciphertext3);
6657 ASSERT_NE(ciphertext2, ciphertext3);
6658}
6659
6660/*
Selene Huang31ab4042020-04-29 04:22:39 -07006661 * EncryptionOperationsTest.AesGcmTooShortTag
6662 *
6663 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6664 */
6665TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6666 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6667 .Authorization(TAG_NO_AUTH_REQUIRED)
6668 .AesEncryptionKey(128)
6669 .BlockMode(BlockMode::GCM)
6670 .Padding(PaddingMode::NONE)
6671 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6672 string message = "123456789012345678901234567890123456";
6673 auto params = AuthorizationSetBuilder()
6674 .BlockMode(BlockMode::GCM)
6675 .Padding(PaddingMode::NONE)
6676 .Authorization(TAG_MAC_LENGTH, 96);
6677
6678 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6679}
6680
6681/*
6682 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6683 *
6684 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6685 */
6686TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6687 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6688 .Authorization(TAG_NO_AUTH_REQUIRED)
6689 .AesEncryptionKey(128)
6690 .BlockMode(BlockMode::GCM)
6691 .Padding(PaddingMode::NONE)
6692 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6693 string aad = "foobar";
6694 string message = "123456789012345678901234567890123456";
6695 auto params = AuthorizationSetBuilder()
6696 .BlockMode(BlockMode::GCM)
6697 .Padding(PaddingMode::NONE)
6698 .Authorization(TAG_MAC_LENGTH, 128);
6699
Selene Huang31ab4042020-04-29 04:22:39 -07006700 // Encrypt
6701 AuthorizationSet begin_out_params;
6702 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6703 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006704 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006705
6706 AuthorizationSet finish_out_params;
6707 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006708 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6709 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006710
6711 params = AuthorizationSetBuilder()
6712 .Authorizations(begin_out_params)
6713 .BlockMode(BlockMode::GCM)
6714 .Padding(PaddingMode::NONE)
6715 .Authorization(TAG_MAC_LENGTH, 96);
6716
6717 // Decrypt.
6718 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6719}
6720
6721/*
6722 * EncryptionOperationsTest.AesGcmCorruptKey
6723 *
6724 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6725 */
6726TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6727 const uint8_t nonce_bytes[] = {
6728 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6729 };
6730 string nonce = make_string(nonce_bytes);
6731 const uint8_t ciphertext_bytes[] = {
6732 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6733 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6734 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6735 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6736 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6737 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6738 };
6739 string ciphertext = make_string(ciphertext_bytes);
6740
6741 auto params = AuthorizationSetBuilder()
6742 .BlockMode(BlockMode::GCM)
6743 .Padding(PaddingMode::NONE)
6744 .Authorization(TAG_MAC_LENGTH, 128)
6745 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6746
6747 auto import_params = AuthorizationSetBuilder()
6748 .Authorization(TAG_NO_AUTH_REQUIRED)
6749 .AesEncryptionKey(128)
6750 .BlockMode(BlockMode::GCM)
6751 .Padding(PaddingMode::NONE)
6752 .Authorization(TAG_CALLER_NONCE)
6753 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6754
6755 // Import correct key and decrypt
6756 const uint8_t key_bytes[] = {
6757 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6758 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6759 };
6760 string key = make_string(key_bytes);
6761 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6762 string plaintext = DecryptMessage(ciphertext, params);
6763 CheckedDeleteKey();
6764
6765 // Corrupt key and attempt to decrypt
6766 key[0] = 0;
6767 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6768 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6769 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6770 CheckedDeleteKey();
6771}
6772
6773/*
6774 * EncryptionOperationsTest.AesGcmAadNoData
6775 *
6776 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6777 * encrypt.
6778 */
6779TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6780 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6781 .Authorization(TAG_NO_AUTH_REQUIRED)
6782 .AesEncryptionKey(128)
6783 .BlockMode(BlockMode::GCM)
6784 .Padding(PaddingMode::NONE)
6785 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6786
6787 string aad = "1234567890123456";
6788 auto params = AuthorizationSetBuilder()
6789 .BlockMode(BlockMode::GCM)
6790 .Padding(PaddingMode::NONE)
6791 .Authorization(TAG_MAC_LENGTH, 128);
6792
Selene Huang31ab4042020-04-29 04:22:39 -07006793 // Encrypt
6794 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006795 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006796 string ciphertext;
6797 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006798 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6799 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006800 EXPECT_TRUE(finish_out_params.empty());
6801
6802 // Grab nonce
6803 params.push_back(begin_out_params);
6804
6805 // Decrypt.
6806 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006807 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006808 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006809 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006810
6811 EXPECT_TRUE(finish_out_params.empty());
6812
6813 EXPECT_EQ("", plaintext);
6814}
6815
6816/*
6817 * EncryptionOperationsTest.AesGcmMultiPartAad
6818 *
6819 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6820 * chunks.
6821 */
6822TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6823 const size_t tag_bits = 128;
6824 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6825 .Authorization(TAG_NO_AUTH_REQUIRED)
6826 .AesEncryptionKey(128)
6827 .BlockMode(BlockMode::GCM)
6828 .Padding(PaddingMode::NONE)
6829 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6830
6831 string message = "123456789012345678901234567890123456";
6832 auto begin_params = AuthorizationSetBuilder()
6833 .BlockMode(BlockMode::GCM)
6834 .Padding(PaddingMode::NONE)
6835 .Authorization(TAG_MAC_LENGTH, tag_bits);
6836 AuthorizationSet begin_out_params;
6837
David Drysdale7fc26b92022-05-13 09:54:24 +01006838 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006839
6840 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006841 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6842 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006843 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006844 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6845 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006846
Selene Huang31ab4042020-04-29 04:22:39 -07006847 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006848 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006849
6850 // Grab nonce.
6851 begin_params.push_back(begin_out_params);
6852
6853 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006854 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006855 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006856 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006857 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006858 EXPECT_EQ(message, plaintext);
6859}
6860
6861/*
6862 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6863 *
6864 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6865 */
6866TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
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
6874 string message = "123456789012345678901234567890123456";
6875 auto begin_params = AuthorizationSetBuilder()
6876 .BlockMode(BlockMode::GCM)
6877 .Padding(PaddingMode::NONE)
6878 .Authorization(TAG_MAC_LENGTH, 128);
6879 AuthorizationSet begin_out_params;
6880
David Drysdale7fc26b92022-05-13 09:54:24 +01006881 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006882
Shawn Willden92d79c02021-02-19 07:31:55 -07006883 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006884 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006885 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6886 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006887
David Drysdaled2cc8c22021-04-15 13:29:45 +01006888 // The failure should have already cancelled the operation.
6889 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6890
Shawn Willden92d79c02021-02-19 07:31:55 -07006891 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006892}
6893
6894/*
6895 * EncryptionOperationsTest.AesGcmBadAad
6896 *
6897 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6898 */
6899TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6900 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6901 .Authorization(TAG_NO_AUTH_REQUIRED)
6902 .AesEncryptionKey(128)
6903 .BlockMode(BlockMode::GCM)
6904 .Padding(PaddingMode::NONE)
6905 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6906
6907 string message = "12345678901234567890123456789012";
6908 auto begin_params = AuthorizationSetBuilder()
6909 .BlockMode(BlockMode::GCM)
6910 .Padding(PaddingMode::NONE)
6911 .Authorization(TAG_MAC_LENGTH, 128);
6912
Selene Huang31ab4042020-04-29 04:22:39 -07006913 // Encrypt
6914 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006915 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006916 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006917 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006918 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006919
6920 // Grab nonce
6921 begin_params.push_back(begin_out_params);
6922
Selene Huang31ab4042020-04-29 04:22:39 -07006923 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006924 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006925 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006926 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006927 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006928}
6929
6930/*
6931 * EncryptionOperationsTest.AesGcmWrongNonce
6932 *
6933 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6934 */
6935TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6936 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6937 .Authorization(TAG_NO_AUTH_REQUIRED)
6938 .AesEncryptionKey(128)
6939 .BlockMode(BlockMode::GCM)
6940 .Padding(PaddingMode::NONE)
6941 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6942
6943 string message = "12345678901234567890123456789012";
6944 auto begin_params = AuthorizationSetBuilder()
6945 .BlockMode(BlockMode::GCM)
6946 .Padding(PaddingMode::NONE)
6947 .Authorization(TAG_MAC_LENGTH, 128);
6948
Selene Huang31ab4042020-04-29 04:22:39 -07006949 // Encrypt
6950 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006951 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006952 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006953 string ciphertext;
6954 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006955 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006956
6957 // Wrong nonce
6958 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6959
6960 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006961 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006962 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006963 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006964 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006965
6966 // With wrong nonce, should have gotten garbage plaintext (or none).
6967 EXPECT_NE(message, plaintext);
6968}
6969
6970/*
6971 * EncryptionOperationsTest.AesGcmCorruptTag
6972 *
6973 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6974 */
6975TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6976 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6977 .Authorization(TAG_NO_AUTH_REQUIRED)
6978 .AesEncryptionKey(128)
6979 .BlockMode(BlockMode::GCM)
6980 .Padding(PaddingMode::NONE)
6981 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6982
6983 string aad = "1234567890123456";
6984 string message = "123456789012345678901234567890123456";
6985
6986 auto params = AuthorizationSetBuilder()
6987 .BlockMode(BlockMode::GCM)
6988 .Padding(PaddingMode::NONE)
6989 .Authorization(TAG_MAC_LENGTH, 128);
6990
Selene Huang31ab4042020-04-29 04:22:39 -07006991 // Encrypt
6992 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006993 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006994 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006995 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006996 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006997
6998 // Corrupt tag
6999 ++(*ciphertext.rbegin());
7000
7001 // Grab nonce
7002 params.push_back(begin_out_params);
7003
7004 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01007005 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07007006 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07007007 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07007008 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007009}
7010
7011/*
7012 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7013 *
7014 * Verifies that 3DES is basically functional.
7015 */
7016TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7017 auto auths = AuthorizationSetBuilder()
7018 .TripleDesEncryptionKey(168)
7019 .BlockMode(BlockMode::ECB)
7020 .Authorization(TAG_NO_AUTH_REQUIRED)
7021 .Padding(PaddingMode::NONE);
7022
7023 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7024 // Two-block message.
7025 string message = "1234567890123456";
7026 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7027 string ciphertext1 = EncryptMessage(message, inParams);
7028 EXPECT_EQ(message.size(), ciphertext1.size());
7029
7030 string ciphertext2 = EncryptMessage(string(message), inParams);
7031 EXPECT_EQ(message.size(), ciphertext2.size());
7032
7033 // ECB is deterministic.
7034 EXPECT_EQ(ciphertext1, ciphertext2);
7035
7036 string plaintext = DecryptMessage(ciphertext1, inParams);
7037 EXPECT_EQ(message, plaintext);
7038}
7039
7040/*
7041 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7042 *
7043 * Verifies that CBC keys reject ECB usage.
7044 */
7045TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7046 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7047 .TripleDesEncryptionKey(168)
7048 .BlockMode(BlockMode::CBC)
7049 .Authorization(TAG_NO_AUTH_REQUIRED)
7050 .Padding(PaddingMode::NONE)));
7051
7052 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7053 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7054}
7055
7056/*
7057 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7058 *
7059 * Tests ECB mode with PKCS#7 padding, various message sizes.
7060 */
7061TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7062 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7063 .TripleDesEncryptionKey(168)
7064 .BlockMode(BlockMode::ECB)
7065 .Authorization(TAG_NO_AUTH_REQUIRED)
7066 .Padding(PaddingMode::PKCS7)));
7067
7068 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007069 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007070 string message(i, 'a');
7071 auto inParams =
7072 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7073 string ciphertext = EncryptMessage(message, inParams);
7074 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7075 string plaintext = DecryptMessage(ciphertext, inParams);
7076 EXPECT_EQ(message, plaintext);
7077 }
7078}
7079
7080/*
7081 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7082 *
7083 * Verifies that keys configured for no padding reject PKCS7 padding
7084 */
7085TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7086 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7087 .TripleDesEncryptionKey(168)
7088 .BlockMode(BlockMode::ECB)
7089 .Authorization(TAG_NO_AUTH_REQUIRED)
7090 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00007091 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7092 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07007093}
7094
7095/*
7096 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7097 *
7098 * Verifies that corrupted padding is detected.
7099 */
7100TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7101 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7102 .TripleDesEncryptionKey(168)
7103 .BlockMode(BlockMode::ECB)
7104 .Authorization(TAG_NO_AUTH_REQUIRED)
7105 .Padding(PaddingMode::PKCS7)));
7106
7107 string message = "a";
7108 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7109 EXPECT_EQ(8U, ciphertext.size());
7110 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007111
7112 AuthorizationSetBuilder begin_params;
7113 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7114 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007115
7116 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7117 ++ciphertext[ciphertext.size() / 2];
7118
David Drysdale7fc26b92022-05-13 09:54:24 +01007119 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007120 string plaintext;
7121 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7122 ErrorCode error = Finish(&plaintext);
7123 if (error == ErrorCode::INVALID_ARGUMENT) {
7124 // This is the expected error, we can exit the test now.
7125 return;
7126 } else {
7127 // Very small chance we got valid decryption, so try again.
7128 ASSERT_EQ(error, ErrorCode::OK);
7129 }
7130 }
7131 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007132}
7133
7134struct TripleDesTestVector {
7135 const char* name;
7136 const KeyPurpose purpose;
7137 const BlockMode block_mode;
7138 const PaddingMode padding_mode;
7139 const char* key;
7140 const char* iv;
7141 const char* input;
7142 const char* output;
7143};
7144
7145// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7146// of the NIST vectors are multiples of the block size.
7147static const TripleDesTestVector kTripleDesTestVectors[] = {
7148 {
7149 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7150 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7151 "", // IV
7152 "329d86bdf1bc5af4", // input
7153 "d946c2756d78633f", // output
7154 },
7155 {
7156 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7157 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7158 "", // IV
7159 "6b1540781b01ce1997adae102dbf3c5b", // input
7160 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7161 },
7162 {
7163 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7164 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7165 "", // IV
7166 "6daad94ce08acfe7", // input
7167 "660e7d32dcc90e79", // output
7168 },
7169 {
7170 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7171 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7172 "", // IV
7173 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7174 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7175 },
7176 {
7177 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7178 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7179 "43f791134c5647ba", // IV
7180 "dcc153cef81d6f24", // input
7181 "92538bd8af18d3ba", // output
7182 },
7183 {
7184 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7185 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7186 "c2e999cb6249023c", // IV
7187 "c689aee38a301bb316da75db36f110b5", // input
7188 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7189 },
7190 {
7191 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7192 PaddingMode::PKCS7,
7193 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7194 "c2e999cb6249023c", // IV
7195 "c689aee38a301bb316da75db36f110b500", // input
7196 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7197 },
7198 {
7199 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7200 PaddingMode::PKCS7,
7201 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7202 "c2e999cb6249023c", // IV
7203 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7204 "c689aee38a301bb316da75db36f110b500", // output
7205 },
7206 {
7207 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7208 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7209 "41746c7e442d3681", // IV
7210 "c53a7b0ec40600fe", // input
7211 "d4f00eb455de1034", // output
7212 },
7213 {
7214 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7215 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7216 "3982bc02c3727d45", // IV
7217 "6006f10adef52991fcc777a1238bbb65", // input
7218 "edae09288e9e3bc05746d872b48e3b29", // output
7219 },
7220};
7221
7222/*
7223 * EncryptionOperationsTest.TripleDesTestVector
7224 *
7225 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7226 */
7227TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7228 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7229 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7230 SCOPED_TRACE(test->name);
7231 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7232 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7233 hex2str(test->output));
7234 }
7235}
7236
7237/*
7238 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7239 *
7240 * Validates CBC mode functionality.
7241 */
7242TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7243 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7244 .TripleDesEncryptionKey(168)
7245 .BlockMode(BlockMode::CBC)
7246 .Authorization(TAG_NO_AUTH_REQUIRED)
7247 .Padding(PaddingMode::NONE)));
7248
7249 ASSERT_GT(key_blob_.size(), 0U);
7250
Brian J Murray734c8412022-01-13 14:55:30 -08007251 // Four-block message.
7252 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007253 vector<uint8_t> iv1;
7254 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7255 EXPECT_EQ(message.size(), ciphertext1.size());
7256
7257 vector<uint8_t> iv2;
7258 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7259 EXPECT_EQ(message.size(), ciphertext2.size());
7260
7261 // IVs should be random, so ciphertexts should differ.
7262 EXPECT_NE(iv1, iv2);
7263 EXPECT_NE(ciphertext1, ciphertext2);
7264
7265 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7266 EXPECT_EQ(message, plaintext);
7267}
7268
7269/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007270 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7271 *
7272 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7273 */
7274TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7275 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7276 .TripleDesEncryptionKey(168)
7277 .BlockMode(BlockMode::CBC)
7278 .Authorization(TAG_NO_AUTH_REQUIRED)
7279 .Authorization(TAG_CALLER_NONCE)
7280 .Padding(PaddingMode::NONE)));
7281 auto params = AuthorizationSetBuilder()
7282 .BlockMode(BlockMode::CBC)
7283 .Padding(PaddingMode::NONE)
7284 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7285 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7286}
7287
7288/*
Selene Huang31ab4042020-04-29 04:22:39 -07007289 * EncryptionOperationsTest.TripleDesCallerIv
7290 *
7291 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7292 */
7293TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7294 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7295 .TripleDesEncryptionKey(168)
7296 .BlockMode(BlockMode::CBC)
7297 .Authorization(TAG_NO_AUTH_REQUIRED)
7298 .Authorization(TAG_CALLER_NONCE)
7299 .Padding(PaddingMode::NONE)));
7300 string message = "1234567890123456";
7301 vector<uint8_t> iv;
7302 // Don't specify IV, should get a random one.
7303 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7304 EXPECT_EQ(message.size(), ciphertext1.size());
7305 EXPECT_EQ(8U, iv.size());
7306
7307 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7308 EXPECT_EQ(message, plaintext);
7309
7310 // Now specify an IV, should also work.
7311 iv = AidlBuf("abcdefgh");
7312 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7313
7314 // Decrypt with correct IV.
7315 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7316 EXPECT_EQ(message, plaintext);
7317
7318 // Now try with wrong IV.
7319 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7320 EXPECT_NE(message, plaintext);
7321}
7322
7323/*
7324 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7325 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007326 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007327 */
7328TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7329 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7330 .TripleDesEncryptionKey(168)
7331 .BlockMode(BlockMode::CBC)
7332 .Authorization(TAG_NO_AUTH_REQUIRED)
7333 .Padding(PaddingMode::NONE)));
7334
7335 string message = "12345678901234567890123456789012";
7336 vector<uint8_t> iv;
7337 // Don't specify nonce, should get a random one.
7338 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7339 EXPECT_EQ(message.size(), ciphertext1.size());
7340 EXPECT_EQ(8U, iv.size());
7341
7342 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7343 EXPECT_EQ(message, plaintext);
7344
7345 // Now specify a nonce, should fail.
7346 auto input_params = AuthorizationSetBuilder()
7347 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7348 .BlockMode(BlockMode::CBC)
7349 .Padding(PaddingMode::NONE);
7350 AuthorizationSet output_params;
7351 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7352 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7353}
7354
7355/*
7356 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7357 *
7358 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7359 */
7360TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7361 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7362 .TripleDesEncryptionKey(168)
7363 .BlockMode(BlockMode::ECB)
7364 .Authorization(TAG_NO_AUTH_REQUIRED)
7365 .Padding(PaddingMode::NONE)));
7366 // Two-block message.
7367 string message = "1234567890123456";
7368 auto begin_params =
7369 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7370 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7371}
7372
7373/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007374 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007375 *
7376 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7377 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007378TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7379 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007380 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007381 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7382 .TripleDesEncryptionKey(168)
7383 .BlockMode(blockMode)
7384 .Authorization(TAG_NO_AUTH_REQUIRED)
7385 .Padding(PaddingMode::NONE)));
7386 // Message is slightly shorter than two blocks.
7387 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007388
David Drysdaled2cc8c22021-04-15 13:29:45 +01007389 auto begin_params =
7390 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7391 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007392 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007393 string ciphertext;
7394 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7395
7396 CheckedDeleteKey();
7397 }
Selene Huang31ab4042020-04-29 04:22:39 -07007398}
7399
7400/*
7401 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7402 *
7403 * Verifies that PKCS7 padding works correctly in CBC mode.
7404 */
7405TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7406 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7407 .TripleDesEncryptionKey(168)
7408 .BlockMode(BlockMode::CBC)
7409 .Authorization(TAG_NO_AUTH_REQUIRED)
7410 .Padding(PaddingMode::PKCS7)));
7411
7412 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007413 for (size_t i = 0; i <= 32; i++) {
7414 SCOPED_TRACE(testing::Message() << "i = " << i);
7415 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7416 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007417 vector<uint8_t> iv;
7418 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7419 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7420 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7421 EXPECT_EQ(message, plaintext);
7422 }
7423}
7424
7425/*
7426 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7427 *
7428 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7429 */
7430TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7431 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7432 .TripleDesEncryptionKey(168)
7433 .BlockMode(BlockMode::CBC)
7434 .Authorization(TAG_NO_AUTH_REQUIRED)
7435 .Padding(PaddingMode::NONE)));
7436
7437 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007438 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007439 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007440 auto begin_params =
7441 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7442 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7443 }
7444}
7445
7446/*
7447 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7448 *
7449 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7450 */
7451TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7452 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7453 .TripleDesEncryptionKey(168)
7454 .BlockMode(BlockMode::CBC)
7455 .Authorization(TAG_NO_AUTH_REQUIRED)
7456 .Padding(PaddingMode::PKCS7)));
7457
7458 string message = "a";
7459 vector<uint8_t> iv;
7460 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7461 EXPECT_EQ(8U, ciphertext.size());
7462 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007463
7464 auto begin_params = AuthorizationSetBuilder()
7465 .BlockMode(BlockMode::CBC)
7466 .Padding(PaddingMode::PKCS7)
7467 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007468
7469 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007470 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007471 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007472 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007473 string plaintext;
7474 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7475 ErrorCode error = Finish(&plaintext);
7476 if (error == ErrorCode::INVALID_ARGUMENT) {
7477 // This is the expected error, we can exit the test now.
7478 return;
7479 } else {
7480 // Very small chance we got valid decryption, so try again.
7481 ASSERT_EQ(error, ErrorCode::OK);
7482 }
7483 }
7484 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007485}
7486
7487/*
7488 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7489 *
7490 * Verifies that 3DES CBC works with many different input sizes.
7491 */
7492TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7493 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7494 .TripleDesEncryptionKey(168)
7495 .BlockMode(BlockMode::CBC)
7496 .Authorization(TAG_NO_AUTH_REQUIRED)
7497 .Padding(PaddingMode::NONE)));
7498
7499 int increment = 7;
7500 string message(240, 'a');
7501 AuthorizationSet input_params =
7502 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7503 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007504 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007505
7506 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007507 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007508 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007509 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7510 EXPECT_EQ(message.size(), ciphertext.size());
7511
7512 // Move TAG_NONCE into input_params
7513 input_params = output_params;
7514 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7515 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7516 output_params.Clear();
7517
David Drysdale7fc26b92022-05-13 09:54:24 +01007518 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007519 string plaintext;
7520 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007521 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007522 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7523 EXPECT_EQ(ciphertext.size(), plaintext.size());
7524 EXPECT_EQ(message, plaintext);
7525}
7526
7527INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7528
7529typedef KeyMintAidlTestBase MaxOperationsTest;
7530
7531/*
7532 * MaxOperationsTest.TestLimitAes
7533 *
7534 * Verifies that the max uses per boot tag works correctly with AES keys.
7535 */
7536TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007537 if (SecLevel() == SecurityLevel::STRONGBOX) {
7538 GTEST_SKIP() << "Test not applicable to StrongBox device";
7539 }
Selene Huang31ab4042020-04-29 04:22:39 -07007540
7541 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7542 .Authorization(TAG_NO_AUTH_REQUIRED)
7543 .AesEncryptionKey(128)
7544 .EcbMode()
7545 .Padding(PaddingMode::NONE)
7546 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7547
7548 string message = "1234567890123456";
7549
7550 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7551
7552 EncryptMessage(message, params);
7553 EncryptMessage(message, params);
7554 EncryptMessage(message, params);
7555
7556 // Fourth time should fail.
7557 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7558}
7559
7560/*
Qi Wud22ec842020-11-26 13:27:53 +08007561 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007562 *
7563 * Verifies that the max uses per boot tag works correctly with RSA keys.
7564 */
7565TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007566 if (SecLevel() == SecurityLevel::STRONGBOX) {
7567 GTEST_SKIP() << "Test not applicable to StrongBox device";
7568 }
Selene Huang31ab4042020-04-29 04:22:39 -07007569
7570 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7571 .Authorization(TAG_NO_AUTH_REQUIRED)
7572 .RsaSigningKey(1024, 65537)
7573 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007574 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7575 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007576
7577 string message = "1234567890123456";
7578
7579 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7580
7581 SignMessage(message, params);
7582 SignMessage(message, params);
7583 SignMessage(message, params);
7584
7585 // Fourth time should fail.
7586 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7587}
7588
7589INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7590
Qi Wud22ec842020-11-26 13:27:53 +08007591typedef KeyMintAidlTestBase UsageCountLimitTest;
7592
7593/*
Qi Wubeefae42021-01-28 23:16:37 +08007594 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007595 *
Qi Wubeefae42021-01-28 23:16:37 +08007596 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007597 */
Qi Wubeefae42021-01-28 23:16:37 +08007598TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007599 if (SecLevel() == SecurityLevel::STRONGBOX) {
7600 GTEST_SKIP() << "Test not applicable to StrongBox device";
7601 }
Qi Wud22ec842020-11-26 13:27:53 +08007602
7603 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7604 .Authorization(TAG_NO_AUTH_REQUIRED)
7605 .AesEncryptionKey(128)
7606 .EcbMode()
7607 .Padding(PaddingMode::NONE)
7608 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7609
7610 // Check the usage count limit tag appears in the authorizations.
7611 AuthorizationSet auths;
7612 for (auto& entry : key_characteristics_) {
7613 auths.push_back(AuthorizationSet(entry.authorizations));
7614 }
7615 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7616 << "key usage count limit " << 1U << " missing";
7617
7618 string message = "1234567890123456";
7619 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7620
Qi Wubeefae42021-01-28 23:16:37 +08007621 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7622 AuthorizationSet keystore_auths =
7623 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7624
Qi Wud22ec842020-11-26 13:27:53 +08007625 // First usage of AES key should work.
7626 EncryptMessage(message, params);
7627
Qi Wud22ec842020-11-26 13:27:53 +08007628 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7629 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7630 // must be invalidated from secure storage (such as RPMB partition).
7631 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7632 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007633 // Usage count limit tag is enforced by keystore, keymint does nothing.
7634 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007635 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007636 }
7637}
7638
7639/*
Qi Wubeefae42021-01-28 23:16:37 +08007640 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007641 *
Qi Wubeefae42021-01-28 23:16:37 +08007642 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007643 */
Qi Wubeefae42021-01-28 23:16:37 +08007644TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007645 if (SecLevel() == SecurityLevel::STRONGBOX) {
7646 GTEST_SKIP() << "Test not applicable to StrongBox device";
7647 }
Qi Wubeefae42021-01-28 23:16:37 +08007648
7649 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7650 .Authorization(TAG_NO_AUTH_REQUIRED)
7651 .AesEncryptionKey(128)
7652 .EcbMode()
7653 .Padding(PaddingMode::NONE)
7654 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7655
7656 // Check the usage count limit tag appears in the authorizations.
7657 AuthorizationSet auths;
7658 for (auto& entry : key_characteristics_) {
7659 auths.push_back(AuthorizationSet(entry.authorizations));
7660 }
7661 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7662 << "key usage count limit " << 3U << " missing";
7663
7664 string message = "1234567890123456";
7665 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7666
7667 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7668 AuthorizationSet keystore_auths =
7669 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7670
7671 EncryptMessage(message, params);
7672 EncryptMessage(message, params);
7673 EncryptMessage(message, params);
7674
7675 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7676 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7677 // must be invalidated from secure storage (such as RPMB partition).
7678 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7679 } else {
7680 // Usage count limit tag is enforced by keystore, keymint does nothing.
7681 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007682 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007683 }
7684}
7685
7686/*
7687 * UsageCountLimitTest.TestSingleUseRsa
7688 *
7689 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7690 */
7691TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007692 if (SecLevel() == SecurityLevel::STRONGBOX) {
7693 GTEST_SKIP() << "Test not applicable to StrongBox device";
7694 }
Qi Wud22ec842020-11-26 13:27:53 +08007695
7696 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7697 .Authorization(TAG_NO_AUTH_REQUIRED)
7698 .RsaSigningKey(1024, 65537)
7699 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007700 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7701 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007702
7703 // Check the usage count limit tag appears in the authorizations.
7704 AuthorizationSet auths;
7705 for (auto& entry : key_characteristics_) {
7706 auths.push_back(AuthorizationSet(entry.authorizations));
7707 }
7708 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7709 << "key usage count limit " << 1U << " missing";
7710
7711 string message = "1234567890123456";
7712 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7713
Qi Wubeefae42021-01-28 23:16:37 +08007714 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7715 AuthorizationSet keystore_auths =
7716 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7717
Qi Wud22ec842020-11-26 13:27:53 +08007718 // First usage of RSA key should work.
7719 SignMessage(message, params);
7720
Qi Wud22ec842020-11-26 13:27:53 +08007721 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7722 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7723 // must be invalidated from secure storage (such as RPMB partition).
7724 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7725 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007726 // Usage count limit tag is enforced by keystore, keymint does nothing.
7727 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007728 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007729 }
7730}
7731
7732/*
7733 * UsageCountLimitTest.TestLimitUseRsa
7734 *
7735 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7736 */
7737TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007738 if (SecLevel() == SecurityLevel::STRONGBOX) {
7739 GTEST_SKIP() << "Test not applicable to StrongBox device";
7740 }
Qi Wubeefae42021-01-28 23:16:37 +08007741
7742 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7743 .Authorization(TAG_NO_AUTH_REQUIRED)
7744 .RsaSigningKey(1024, 65537)
7745 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007746 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7747 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007748
7749 // Check the usage count limit tag appears in the authorizations.
7750 AuthorizationSet auths;
7751 for (auto& entry : key_characteristics_) {
7752 auths.push_back(AuthorizationSet(entry.authorizations));
7753 }
7754 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7755 << "key usage count limit " << 3U << " missing";
7756
7757 string message = "1234567890123456";
7758 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7759
7760 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7761 AuthorizationSet keystore_auths =
7762 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7763
7764 SignMessage(message, params);
7765 SignMessage(message, params);
7766 SignMessage(message, params);
7767
7768 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7769 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7770 // must be invalidated from secure storage (such as RPMB partition).
7771 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7772 } else {
7773 // Usage count limit tag is enforced by keystore, keymint does nothing.
7774 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007775 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007776 }
7777}
7778
Qi Wu8e727f72021-02-11 02:49:33 +08007779/*
7780 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7781 *
7782 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7783 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7784 * in hardware.
7785 */
7786TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007787 if (SecLevel() == SecurityLevel::STRONGBOX) {
7788 GTEST_SKIP() << "Test not applicable to StrongBox device";
7789 }
Qi Wu8e727f72021-02-11 02:49:33 +08007790
7791 auto error = GenerateKey(AuthorizationSetBuilder()
7792 .RsaSigningKey(2048, 65537)
7793 .Digest(Digest::NONE)
7794 .Padding(PaddingMode::NONE)
7795 .Authorization(TAG_NO_AUTH_REQUIRED)
7796 .Authorization(TAG_ROLLBACK_RESISTANCE)
7797 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007798 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7799 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007800 }
David Drysdale513bf122021-10-06 11:53:13 +01007801
7802 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7803 ASSERT_EQ(ErrorCode::OK, error);
7804 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7805 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7806 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7807
7808 // The KeyMint should also enforce single use key in hardware when it supports rollback
7809 // resistance.
7810 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7811 .Authorization(TAG_NO_AUTH_REQUIRED)
7812 .RsaSigningKey(1024, 65537)
7813 .NoDigestOrPadding()
7814 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7815 .SetDefaultValidity()));
7816
7817 // Check the usage count limit tag appears in the hardware authorizations.
7818 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7819 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7820 << "key usage count limit " << 1U << " missing";
7821
7822 string message = "1234567890123456";
7823 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7824
7825 // First usage of RSA key should work.
7826 SignMessage(message, params);
7827
7828 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7829 // must be invalidated from secure storage (such as RPMB partition).
7830 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007831}
7832
Qi Wud22ec842020-11-26 13:27:53 +08007833INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7834
David Drysdale7de9feb2021-03-05 14:56:19 +00007835typedef KeyMintAidlTestBase GetHardwareInfoTest;
7836
7837TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7838 // Retrieving hardware info should give the same result each time.
7839 KeyMintHardwareInfo info;
7840 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7841 KeyMintHardwareInfo info2;
7842 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7843 EXPECT_EQ(info, info2);
7844}
7845
7846INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7847
Selene Huang31ab4042020-04-29 04:22:39 -07007848typedef KeyMintAidlTestBase AddEntropyTest;
7849
7850/*
7851 * AddEntropyTest.AddEntropy
7852 *
7853 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7854 * is actually added.
7855 */
7856TEST_P(AddEntropyTest, AddEntropy) {
7857 string data = "foo";
7858 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7859}
7860
7861/*
7862 * AddEntropyTest.AddEmptyEntropy
7863 *
7864 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7865 */
7866TEST_P(AddEntropyTest, AddEmptyEntropy) {
7867 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7868}
7869
7870/*
7871 * AddEntropyTest.AddLargeEntropy
7872 *
7873 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7874 */
7875TEST_P(AddEntropyTest, AddLargeEntropy) {
7876 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7877}
7878
David Drysdalebb3d85e2021-04-13 11:15:51 +01007879/*
7880 * AddEntropyTest.AddTooLargeEntropy
7881 *
7882 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7883 */
7884TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7885 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7886 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7887}
7888
Selene Huang31ab4042020-04-29 04:22:39 -07007889INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7890
Selene Huang31ab4042020-04-29 04:22:39 -07007891typedef KeyMintAidlTestBase KeyDeletionTest;
7892
7893/**
7894 * KeyDeletionTest.DeleteKey
7895 *
7896 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7897 * valid key blob.
7898 */
7899TEST_P(KeyDeletionTest, DeleteKey) {
7900 auto error = GenerateKey(AuthorizationSetBuilder()
7901 .RsaSigningKey(2048, 65537)
7902 .Digest(Digest::NONE)
7903 .Padding(PaddingMode::NONE)
7904 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007905 .Authorization(TAG_ROLLBACK_RESISTANCE)
7906 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007907 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7908 GTEST_SKIP() << "Rollback resistance not supported";
7909 }
Selene Huang31ab4042020-04-29 04:22:39 -07007910
7911 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007912 ASSERT_EQ(ErrorCode::OK, error);
7913 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7914 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007915
David Drysdale513bf122021-10-06 11:53:13 +01007916 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007917
David Drysdale513bf122021-10-06 11:53:13 +01007918 string message = "12345678901234567890123456789012";
7919 AuthorizationSet begin_out_params;
7920 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7921 Begin(KeyPurpose::SIGN, key_blob_,
7922 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7923 &begin_out_params));
7924 AbortIfNeeded();
7925 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007926}
7927
7928/**
7929 * KeyDeletionTest.DeleteInvalidKey
7930 *
7931 * This test checks that the HAL excepts invalid key blobs..
7932 */
7933TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7934 // Generate key just to check if rollback protection is implemented
7935 auto error = GenerateKey(AuthorizationSetBuilder()
7936 .RsaSigningKey(2048, 65537)
7937 .Digest(Digest::NONE)
7938 .Padding(PaddingMode::NONE)
7939 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007940 .Authorization(TAG_ROLLBACK_RESISTANCE)
7941 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007942 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7943 GTEST_SKIP() << "Rollback resistance not supported";
7944 }
Selene Huang31ab4042020-04-29 04:22:39 -07007945
7946 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007947 ASSERT_EQ(ErrorCode::OK, error);
7948 AuthorizationSet enforced(SecLevelAuthorizations());
7949 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007950
David Drysdale513bf122021-10-06 11:53:13 +01007951 // Delete the key we don't care about the result at this point.
7952 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007953
David Drysdale513bf122021-10-06 11:53:13 +01007954 // Now create an invalid key blob and delete it.
7955 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007956
David Drysdale513bf122021-10-06 11:53:13 +01007957 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007958}
7959
7960/**
7961 * KeyDeletionTest.DeleteAllKeys
7962 *
7963 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7964 *
7965 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7966 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7967 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7968 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7969 * credentials stored in Keystore/Keymint.
7970 */
7971TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007972 if (!arm_deleteAllKeys) {
7973 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7974 return;
7975 }
Selene Huang31ab4042020-04-29 04:22:39 -07007976 auto error = GenerateKey(AuthorizationSetBuilder()
7977 .RsaSigningKey(2048, 65537)
7978 .Digest(Digest::NONE)
7979 .Padding(PaddingMode::NONE)
7980 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007981 .Authorization(TAG_ROLLBACK_RESISTANCE)
7982 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007983 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7984 GTEST_SKIP() << "Rollback resistance not supported";
7985 }
Selene Huang31ab4042020-04-29 04:22:39 -07007986
7987 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007988 ASSERT_EQ(ErrorCode::OK, error);
7989 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7990 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007991
David Drysdale513bf122021-10-06 11:53:13 +01007992 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007993
David Drysdale513bf122021-10-06 11:53:13 +01007994 string message = "12345678901234567890123456789012";
7995 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007996
David Drysdale513bf122021-10-06 11:53:13 +01007997 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7998 Begin(KeyPurpose::SIGN, key_blob_,
7999 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8000 &begin_out_params));
8001 AbortIfNeeded();
8002 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07008003}
8004
8005INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8006
David Drysdaled2cc8c22021-04-15 13:29:45 +01008007typedef KeyMintAidlTestBase KeyUpgradeTest;
8008
8009/**
8010 * KeyUpgradeTest.UpgradeInvalidKey
8011 *
8012 * This test checks that the HAL excepts invalid key blobs..
8013 */
8014TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8015 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8016
8017 std::vector<uint8_t> new_blob;
8018 Status result = keymint_->upgradeKey(key_blob,
8019 AuthorizationSetBuilder()
8020 .Authorization(TAG_APPLICATION_ID, "clientid")
8021 .Authorization(TAG_APPLICATION_DATA, "appdata")
8022 .vector_data(),
8023 &new_blob);
8024 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8025}
8026
8027INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8028
Selene Huang31ab4042020-04-29 04:22:39 -07008029using UpgradeKeyTest = KeyMintAidlTestBase;
8030
8031/*
8032 * UpgradeKeyTest.UpgradeKey
8033 *
8034 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8035 */
8036TEST_P(UpgradeKeyTest, UpgradeKey) {
8037 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8038 .AesEncryptionKey(128)
8039 .Padding(PaddingMode::NONE)
8040 .Authorization(TAG_NO_AUTH_REQUIRED)));
8041
8042 auto result = UpgradeKey(key_blob_);
8043
8044 // Key doesn't need upgrading. Should get okay, but no new key blob.
8045 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8046}
8047
8048INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8049
8050using ClearOperationsTest = KeyMintAidlTestBase;
8051
8052/*
8053 * ClearSlotsTest.TooManyOperations
8054 *
8055 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8056 * operations are started without being finished or aborted. Also verifies
8057 * that aborting the operations clears the operations.
8058 *
8059 */
8060TEST_P(ClearOperationsTest, TooManyOperations) {
8061 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8062 .Authorization(TAG_NO_AUTH_REQUIRED)
8063 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08008064 .Padding(PaddingMode::NONE)
8065 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07008066
8067 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8068 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08008069 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07008070 AuthorizationSet out_params;
8071 ErrorCode result;
8072 size_t i;
8073
8074 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00008075 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07008076 if (ErrorCode::OK != result) {
8077 break;
8078 }
8079 }
8080 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8081 // Try again just in case there's a weird overflow bug
8082 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00008083 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008084 for (size_t j = 0; j < i; j++) {
8085 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8086 << "Aboort failed for i = " << j << std::endl;
8087 }
David Drysdale7fc26b92022-05-13 09:54:24 +01008088 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008089 AbortIfNeeded();
8090}
8091
8092INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8093
8094typedef KeyMintAidlTestBase TransportLimitTest;
8095
8096/*
David Drysdale7de9feb2021-03-05 14:56:19 +00008097 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07008098 *
8099 * Verifies that passing input data to finish succeeds as expected.
8100 */
8101TEST_P(TransportLimitTest, LargeFinishInput) {
8102 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8103 .Authorization(TAG_NO_AUTH_REQUIRED)
8104 .AesEncryptionKey(128)
8105 .BlockMode(BlockMode::ECB)
8106 .Padding(PaddingMode::NONE)));
8107
8108 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008109 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008110 auto cipher_params =
8111 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8112
8113 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008114 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008115
8116 string plain_message = std::string(1 << msg_size, 'x');
8117 string encrypted_message;
8118 auto rc = Finish(plain_message, &encrypted_message);
8119
8120 EXPECT_EQ(ErrorCode::OK, rc);
8121 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8122 << "Encrypt finish returned OK, but did not consume all of the given input";
8123 cipher_params.push_back(out_params);
8124
David Drysdale7fc26b92022-05-13 09:54:24 +01008125 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008126
8127 string decrypted_message;
8128 rc = Finish(encrypted_message, &decrypted_message);
8129 EXPECT_EQ(ErrorCode::OK, rc);
8130 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8131 << "Decrypt finish returned OK, did not consume all of the given input";
8132 }
8133}
8134
8135INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8136
Seth Moored79a0ec2021-12-13 20:03:33 +00008137static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008138 switch (curve) {
8139 case EcCurve::P_224:
8140 return NID_secp224r1;
8141 case EcCurve::P_256:
8142 return NID_X9_62_prime256v1;
8143 case EcCurve::P_384:
8144 return NID_secp384r1;
8145 case EcCurve::P_521:
8146 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008147 case EcCurve::CURVE_25519:
8148 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008149 }
8150}
8151
David Drysdale42fe1892021-10-14 14:43:46 +01008152class KeyAgreementTest : public KeyMintAidlTestBase {
8153 protected:
8154 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8155 std::vector<uint8_t>* localPublicKey) {
8156 // Generate EC key locally (with access to private key material)
8157 if (localCurve == EcCurve::CURVE_25519) {
8158 uint8_t privKeyData[32];
8159 uint8_t pubKeyData[32];
8160 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008161 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8162 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8163 } else {
8164 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8165 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8166 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8167 ASSERT_NE(group, nullptr);
8168 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8169 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8170 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8171 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008172 }
David Drysdalea410b772022-05-09 16:44:13 +01008173
8174 // Get encoded form of the public part of the locally generated key...
8175 unsigned char* p = nullptr;
8176 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8177 ASSERT_GT(localPublicKeySize, 0);
8178 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8179 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8180 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008181 }
8182
8183 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8184 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008185 auto builder = AuthorizationSetBuilder()
8186 .Authorization(TAG_NO_AUTH_REQUIRED)
8187 .Authorization(TAG_EC_CURVE, curve)
8188 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8189 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8190 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8191 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8192 .SetDefaultValidity();
8193 ErrorCode result = GenerateKey(builder);
8194
8195 if (SecLevel() == SecurityLevel::STRONGBOX) {
8196 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8197 result = GenerateKeyWithSelfSignedAttestKey(
8198 AuthorizationSetBuilder()
8199 .EcdsaKey(EcCurve::P_256)
8200 .AttestKey()
8201 .SetDefaultValidity(), /* attest key params */
8202 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8203 }
8204 }
David Drysdale42fe1892021-10-14 14:43:46 +01008205 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8206 ASSERT_GT(cert_chain_.size(), 0);
8207 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8208 ASSERT_NE(kmKeyCert, nullptr);
8209 // Check that keyAgreement (bit 4) is set in KeyUsage
8210 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8211 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8212 ASSERT_NE(*kmPubKey, nullptr);
8213 if (dump_Attestations) {
8214 for (size_t n = 0; n < cert_chain_.size(); n++) {
8215 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8216 }
8217 }
8218 }
8219
8220 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8221 const std::vector<uint8_t>& localPublicKey) {
8222 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8223 string ZabFromKeyMintStr;
8224 ASSERT_EQ(ErrorCode::OK,
8225 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8226 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8227 vector<uint8_t> ZabFromTest;
8228
8229 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8230 size_t kmPubKeySize = 32;
8231 uint8_t kmPubKeyData[32];
8232 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8233 ASSERT_EQ(kmPubKeySize, 32);
8234
8235 uint8_t localPrivKeyData[32];
8236 size_t localPrivKeySize = 32;
8237 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8238 &localPrivKeySize));
8239 ASSERT_EQ(localPrivKeySize, 32);
8240
8241 uint8_t sharedKey[32];
8242 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8243 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8244 } else {
8245 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8246 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8247 ASSERT_NE(ctx, nullptr);
8248 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8249 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8250 size_t ZabFromTestLen = 0;
8251 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8252 ZabFromTest.resize(ZabFromTestLen);
8253 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8254 }
8255 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8256 }
8257};
8258
David Zeuthene0c40892021-01-08 12:54:11 -05008259/*
8260 * KeyAgreementTest.Ecdh
8261 *
David Drysdale42fe1892021-10-14 14:43:46 +01008262 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008263 */
8264TEST_P(KeyAgreementTest, Ecdh) {
8265 // Because it's possible to use this API with keys on different curves, we
8266 // check all N^2 combinations where N is the number of supported
8267 // curves.
8268 //
8269 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8270 // lot more curves we can be smart about things and just pick |otherCurve| so
8271 // it's not |curve| and that way we end up with only 2*N runs
8272 //
8273 for (auto curve : ValidCurves()) {
8274 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008275 SCOPED_TRACE(testing::Message()
8276 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8277
David Zeuthene0c40892021-01-08 12:54:11 -05008278 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008279 EVP_PKEY_Ptr localPrivKey;
8280 vector<uint8_t> localPublicKey;
8281 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008282
8283 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008284 EVP_PKEY_Ptr kmPubKey;
8285 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008286
8287 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8288 if (curve != localCurve) {
8289 // If the keys are using different curves KeyMint should fail with
8290 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008291 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008292 string ZabFromKeyMintStr;
8293 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008294 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008295 &ZabFromKeyMintStr));
8296
8297 } else {
8298 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008299 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008300 }
8301
8302 CheckedDeleteKey();
8303 }
8304 }
8305}
8306
David Drysdale42fe1892021-10-14 14:43:46 +01008307/*
8308 * KeyAgreementTest.EcdhCurve25519
8309 *
8310 * Verifies that ECDH works for curve25519. This is also covered by the general
8311 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8312 * KeyMint 1.0.
8313 */
8314TEST_P(KeyAgreementTest, EcdhCurve25519) {
8315 if (!Curve25519Supported()) {
8316 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8317 }
8318
8319 // Generate EC key in KeyMint (only access to public key material)
8320 EcCurve curve = EcCurve::CURVE_25519;
8321 EVP_PKEY_Ptr kmPubKey = nullptr;
8322 GenerateKeyMintEcKey(curve, &kmPubKey);
8323
8324 // Generate EC key on same curve locally (with access to private key material).
8325 EVP_PKEY_Ptr privKey;
8326 vector<uint8_t> encodedPublicKey;
8327 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8328
8329 // Agree on a key between local and KeyMint and check it.
8330 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8331
8332 CheckedDeleteKey();
8333}
8334
8335/*
8336 * KeyAgreementTest.EcdhCurve25519Imported
8337 *
8338 * Verifies that ECDH works for an imported curve25519 key.
8339 */
8340TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8341 if (!Curve25519Supported()) {
8342 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8343 }
8344
8345 // Import x25519 key into KeyMint.
8346 EcCurve curve = EcCurve::CURVE_25519;
8347 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8348 .Authorization(TAG_NO_AUTH_REQUIRED)
8349 .EcdsaKey(EcCurve::CURVE_25519)
8350 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8351 .SetDefaultValidity(),
8352 KeyFormat::PKCS8, x25519_pkcs8_key));
8353 ASSERT_GT(cert_chain_.size(), 0);
8354 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8355 ASSERT_NE(kmKeyCert, nullptr);
8356 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8357 ASSERT_NE(kmPubKey.get(), nullptr);
8358
8359 // Expect the import to emit corresponding public key data.
8360 size_t kmPubKeySize = 32;
8361 uint8_t kmPubKeyData[32];
8362 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8363 ASSERT_EQ(kmPubKeySize, 32);
8364 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8365 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8366
8367 // Generate EC key on same curve locally (with access to private key material).
8368 EVP_PKEY_Ptr privKey;
8369 vector<uint8_t> encodedPublicKey;
8370 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8371
8372 // Agree on a key between local and KeyMint and check it.
8373 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8374
8375 CheckedDeleteKey();
8376}
8377
8378/*
8379 * KeyAgreementTest.EcdhCurve25519InvalidSize
8380 *
8381 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8382 */
8383TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8384 if (!Curve25519Supported()) {
8385 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8386 }
8387
8388 // Generate EC key in KeyMint (only access to public key material)
8389 EcCurve curve = EcCurve::CURVE_25519;
8390 EVP_PKEY_Ptr kmPubKey = nullptr;
8391 GenerateKeyMintEcKey(curve, &kmPubKey);
8392
8393 // Generate EC key on same curve locally (with access to private key material).
8394 EVP_PKEY_Ptr privKey;
8395 vector<uint8_t> encodedPublicKey;
8396 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8397
8398 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8399 string ZabFromKeyMintStr;
8400 // Send in an incomplete public key.
8401 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8402 &ZabFromKeyMintStr));
8403
8404 CheckedDeleteKey();
8405}
8406
8407/*
8408 * KeyAgreementTest.EcdhCurve25519Mismatch
8409 *
8410 * Verifies that ECDH fails between curve25519 and other curves.
8411 */
8412TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8413 if (!Curve25519Supported()) {
8414 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8415 }
8416
8417 // Generate EC key in KeyMint (only access to public key material)
8418 EcCurve curve = EcCurve::CURVE_25519;
8419 EVP_PKEY_Ptr kmPubKey = nullptr;
8420 GenerateKeyMintEcKey(curve, &kmPubKey);
8421
8422 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008423 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008424 if (localCurve == curve) {
8425 continue;
8426 }
8427 // Generate EC key on a different curve locally (with access to private key material).
8428 EVP_PKEY_Ptr privKey;
8429 vector<uint8_t> encodedPublicKey;
8430 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8431
David Drysdale7fc26b92022-05-13 09:54:24 +01008432 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008433 string ZabFromKeyMintStr;
8434 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8435 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8436 &ZabFromKeyMintStr));
8437 }
8438
8439 CheckedDeleteKey();
8440}
8441
David Zeuthene0c40892021-01-08 12:54:11 -05008442INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8443
David Drysdaled2cc8c22021-04-15 13:29:45 +01008444using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8445
8446// This is a problematic test, as it can render the device under test permanently unusable.
8447// Re-enable and run at your own risk.
8448TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8449 auto result = DestroyAttestationIds();
8450 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8451}
8452
8453INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8454
Shawn Willdend659c7c2021-02-19 14:51:51 -07008455using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008456
David Drysdaledb0dcf52021-05-18 11:43:31 +01008457/*
8458 * EarlyBootKeyTest.CreateEarlyBootKeys
8459 *
8460 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8461 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008462TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008463 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008464 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8465 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8466
David Drysdaleadfe6112021-05-27 12:00:53 +01008467 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8468 ASSERT_GT(keyData.blob.size(), 0U);
8469 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8470 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8471 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008472 CheckedDeleteKey(&aesKeyData.blob);
8473 CheckedDeleteKey(&hmacKeyData.blob);
8474 CheckedDeleteKey(&rsaKeyData.blob);
8475 CheckedDeleteKey(&ecdsaKeyData.blob);
8476}
8477
David Drysdaledb0dcf52021-05-18 11:43:31 +01008478/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008479 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8480 *
8481 * Verifies that creating an early boot key with attestation succeeds.
8482 */
8483TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8484 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8485 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8486 builder->AttestationChallenge("challenge");
8487 builder->AttestationApplicationId("app_id");
8488 });
8489
8490 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008491 // Strongbox may not support factory attestation. Key creation might fail with
8492 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8493 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8494 continue;
8495 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008496 ASSERT_GT(keyData.blob.size(), 0U);
8497 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8498 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8499 }
8500 CheckedDeleteKey(&aesKeyData.blob);
8501 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00008502 if (rsaKeyData.blob.size() != 0U) {
8503 CheckedDeleteKey(&rsaKeyData.blob);
8504 }
8505 if (ecdsaKeyData.blob.size() != 0U) {
8506 CheckedDeleteKey(&ecdsaKeyData.blob);
8507 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008508}
8509
8510/*
8511 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008512 *
8513 * Verifies that using early boot keys at a later stage fails.
8514 */
8515TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8516 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8517 .Authorization(TAG_NO_AUTH_REQUIRED)
8518 .Authorization(TAG_EARLY_BOOT_ONLY)
8519 .HmacKey(128)
8520 .Digest(Digest::SHA_2_256)
8521 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8522 AuthorizationSet output_params;
8523 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8524 AuthorizationSetBuilder()
8525 .Digest(Digest::SHA_2_256)
8526 .Authorization(TAG_MAC_LENGTH, 256),
8527 &output_params));
8528}
8529
8530/*
8531 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8532 *
8533 * Verifies that importing early boot keys fails.
8534 */
8535TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8536 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8537 .Authorization(TAG_NO_AUTH_REQUIRED)
8538 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008539 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008540 .Digest(Digest::SHA_2_256)
8541 .SetDefaultValidity(),
8542 KeyFormat::PKCS8, ec_256_key));
8543}
8544
David Drysdaled2cc8c22021-04-15 13:29:45 +01008545// 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 +00008546// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8547// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8548// early boot, so you'll have to reboot between runs.
8549TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8550 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8551 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8552 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8553 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8554 EXPECT_TRUE(
8555 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8556 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8557 EXPECT_TRUE(
8558 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8559
8560 // Should be able to use keys, since early boot has not ended
8561 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8562 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8563 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8564 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8565
8566 // End early boot
8567 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8568 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8569
8570 // Should not be able to use already-created keys.
8571 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8572 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8573 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8574 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8575
8576 CheckedDeleteKey(&aesKeyData.blob);
8577 CheckedDeleteKey(&hmacKeyData.blob);
8578 CheckedDeleteKey(&rsaKeyData.blob);
8579 CheckedDeleteKey(&ecdsaKeyData.blob);
8580
8581 // Should not be able to create new keys
8582 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
8583 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
8584
8585 CheckedDeleteKey(&aesKeyData.blob);
8586 CheckedDeleteKey(&hmacKeyData.blob);
8587 CheckedDeleteKey(&rsaKeyData.blob);
8588 CheckedDeleteKey(&ecdsaKeyData.blob);
8589}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008590
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008591INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8592
Shawn Willdend659c7c2021-02-19 14:51:51 -07008593using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008594
8595// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8596// between runs... and on most test devices there are no enrolled credentials so it can't be
8597// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8598// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8599// a manual test process, which includes unlocking between runs, which is why it's included here.
8600// Well, that and the fact that it's the only test we can do without also making calls into the
8601// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8602// implications might be, so that may or may not be a solution.
8603TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8604 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8605 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
8606
8607 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8608 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8609 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8610 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8611
8612 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008613 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008614 ASSERT_EQ(ErrorCode::OK, rc);
8615 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8616 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8617 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8618 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8619
8620 CheckedDeleteKey(&aesKeyData.blob);
8621 CheckedDeleteKey(&hmacKeyData.blob);
8622 CheckedDeleteKey(&rsaKeyData.blob);
8623 CheckedDeleteKey(&ecdsaKeyData.blob);
8624}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008625
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008626INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8627
Shawn Willden22fb9c12022-06-02 14:04:33 -06008628using VsrRequirementTest = KeyMintAidlTestBase;
8629
8630TEST_P(VsrRequirementTest, Vsr13Test) {
8631 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008632 if (vsr_api_level < __ANDROID_API_T__) {
Shawn Willden22fb9c12022-06-02 14:04:33 -06008633 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8634 }
8635 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8636}
8637
Eran Messerib9346f52022-12-15 14:58:34 +00008638TEST_P(VsrRequirementTest, Vsr14Test) {
8639 int vsr_api_level = get_vsr_api_level();
Shawn Willden1a545db2023-02-22 14:32:33 -07008640 if (vsr_api_level < __ANDROID_API_U__) {
Eran Messerib9346f52022-12-15 14:58:34 +00008641 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8642 }
8643 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8644}
8645
Shawn Willden22fb9c12022-06-02 14:04:33 -06008646INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8647
Janis Danisevskis24c04702020-12-16 18:28:39 -08008648} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008649
8650int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008651 std::cout << "Testing ";
8652 auto halInstances =
8653 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8654 std::cout << "HAL instances:\n";
8655 for (auto& entry : halInstances) {
8656 std::cout << " " << entry << '\n';
8657 }
8658
Selene Huang31ab4042020-04-29 04:22:39 -07008659 ::testing::InitGoogleTest(&argc, argv);
8660 for (int i = 1; i < argc; ++i) {
8661 if (argv[i][0] == '-') {
8662 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008663 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8664 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008665 }
8666 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008667 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8668 dump_Attestations = true;
8669 } else {
8670 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008671 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008672 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8673 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8674 // be run in emulated environments that don't have the normal bootloader
8675 // interactions.
8676 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8677 }
David Drysdale9f5c0c52022-11-03 15:10:16 +00008678 if (std::string(argv[i]) == "--keyblob_dir") {
8679 if (i + 1 >= argc) {
8680 std::cerr << "Missing argument for --keyblob_dir\n";
8681 return 1;
8682 }
8683 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::keyblob_dir =
8684 std::string(argv[i + 1]);
8685 ++i;
8686 }
Selene Huang31ab4042020-04-29 04:22:39 -07008687 }
8688 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008689 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008690}