blob: d109058b8f49d59409407f0d25223eb372902922 [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 Zeuthene0c40892021-01-08 12:54:11 -050025#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070026#include <openssl/evp.h>
27#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050028#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070029
30#include <cutils/properties.h>
31
David Drysdale4dc01072021-04-01 12:17:35 +010032#include <android/binder_manager.h>
33
34#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080035#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070036
Shawn Willden08a7e432020-12-11 13:05:27 +000037#include <keymint_support/key_param_output.h>
38#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070039
40#include "KeyMintAidlTestBase.h"
41
Janis Danisevskis24c04702020-12-16 18:28:39 -080042using aidl::android::hardware::security::keymint::AuthorizationSet;
43using aidl::android::hardware::security::keymint::KeyCharacteristics;
44using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070045
Selene Huang31ab4042020-04-29 04:22:39 -070046namespace std {
47
Janis Danisevskis24c04702020-12-16 18:28:39 -080048using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070049
50template <>
51struct std::equal_to<KeyCharacteristics> {
52 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070053 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070054
Shawn Willden7f424372021-01-10 18:06:50 -070055 // this isn't very efficient. Oh, well.
56 AuthorizationSet a_auths(a.authorizations);
57 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070058
Shawn Willden7f424372021-01-10 18:06:50 -070059 a_auths.Sort();
60 b_auths.Sort();
61
62 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070063 }
64};
65
66} // namespace std
67
Janis Danisevskis24c04702020-12-16 18:28:39 -080068namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000069
Selene Huang31ab4042020-04-29 04:22:39 -070070namespace {
71
David Drysdaledbbbe2e2021-12-02 07:44:23 +000072// Whether to check that BOOT_PATCHLEVEL is populated.
73bool check_boot_pl = true;
74
Seth Moore7a55ae32021-06-23 14:28:11 -070075// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000076// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070077// is a small (roughly 1/256) chance that corrupting ciphertext still results
78// in valid PKCS7 padding.
79constexpr size_t kMaxPaddingCorruptionRetries = 8;
80
Selene Huang31ab4042020-04-29 04:22:39 -070081template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000082bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
83 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070084 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080085 if (auto p = authorizationValue(ttag, param)) {
86 return *p == expected_value;
87 }
88 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070089 });
90 return (it != set.end());
91}
92
93template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000094bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070095 auto it = std::find_if(set.begin(), set.end(),
96 [&](const KeyParameter& param) { return param.tag == tag; });
97 return (it != set.end());
98}
99
100constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
101 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
102 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
103 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
104 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
107 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
111 0, 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
117string hex2str(string a) {
118 string b;
119 size_t num = a.size() / 2;
120 b.resize(num);
121 for (size_t i = 0; i < num; i++) {
122 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
123 }
124 return b;
125}
126
David Drysdaled2cc8c22021-04-15 13:29:45 +0100127string rsa_key = hex2str(
128 // RFC 5208 s5
129 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
130 "020100" // INTEGER length 1 value 0x00 (version)
131 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
132 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
133 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
134 "0500" // NULL (parameters)
135 // } end SEQUENCE (AlgorithmIdentifier)
136 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
137 // RFC 8017 A.1.2
138 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
139 "020100" // INTEGER length 1 value 0x00 (version)
140 "028181" // INTEGER length 0x81 value (modulus) ...
141 "00c6095409047d8634812d5a218176e4"
142 "5c41d60a75b13901f234226cffe77652"
143 "1c5a77b9e389417b71c0b6a44d13afe4"
144 "e4a2805d46c9da2935adb1ff0c1f24ea"
145 "06e62b20d776430a4d435157233c6f91"
146 "6783c30e310fcbd89b85c2d567711697"
147 "85ac12bca244abda72bfb19fc44d27c8"
148 "1e1d92de284f4061edfd99280745ea6d"
149 "25"
150 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
151 "028180" // INTEGER length 0x80 (privateExponent) value...
152 "1be0f04d9cae3718691f035338308e91"
153 "564b55899ffb5084d2460e6630257e05"
154 "b3ceab02972dfabcd6ce5f6ee2589eb6"
155 "7911ed0fac16e43a444b8c861e544a05"
156 "93365772f8baf6b22fc9e3c5f1024b06"
157 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
158 "ace7240290bef16c0b3f7f3cdd64ce3a"
159 "b5912cf6e32f39ab188358afcccd8081"
160 "0241" // INTEGER length 0x41 (prime1)
161 "00e4b49ef50f765d3b24dde01aceaaf1"
162 "30f2c76670a91a61ae08af497b4a82be"
163 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
164 "8c92bfab137fba2285227b83c342ff7c"
165 "55"
166 "0241" // INTEGER length 0x41 (prime2)
167 "00ddabb5839c4c7f6bf3d4183231f005"
168 "b31aa58affdda5c79e4cce217f6bc930"
169 "dbe563d480706c24e9ebfcab28a6cdef"
170 "d324b77e1bf7251b709092c24ff501fd"
171 "91"
172 "0240" // INTEGER length 0x40 (exponent1)
173 "23d4340eda3445d8cd26c14411da6fdc"
174 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
175 "842c1d280405bc2f6c1bea214a1d742a"
176 "b996b35b63a82a5e470fa88dbf823cdd"
177 "0240" // INTEGER length 0x40 (exponent2)
178 "1b7b57449ad30d1518249a5f56bb9829"
179 "4d4b6ac12ffc86940497a5a5837a6cf9"
180 "46262b494526d328c11e1126380fde04"
181 "c24f916dec250892db09a6d77cdba351"
182 "0240" // INTEGER length 0x40 (coefficient)
183 "7762cd8f4d050da56bd591adb515d24d"
184 "7ccd32cca0d05f866d583514bd7324d5"
185 "f33645e8ed8b4a1cb3cc4a1d67987399"
186 "f2a09f5b3fb68c88d5e5d90ac33492d6"
187 // } end SEQUENCE (PrivateKey)
188 // } end SEQUENCE (PrivateKeyInfo)
189);
Selene Huang31ab4042020-04-29 04:22:39 -0700190
Selene Huange5727e62021-04-13 22:41:20 -0700191/*
192 * DER-encoded PKCS#8 format RSA key. Generated using:
193 *
194 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
195 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100196string rsa_2048_key = hex2str(
197 // RFC 5208 s5
198 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
199 "020100" // INTEGER length 1 value 0x00 (version)
200 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
201 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
202 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
203 "0500" // NULL (parameters)
204 // } end SEQUENCE (AlgorithmIdentifier)
205 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
206 // RFC 8017 A.1.2
207 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
208 "020100" // INTEGER length 1 value 0x00 (version)
209 "02820101" // INTEGER length 0x101 value (modulus) ...
210 "00BEBC342B56D443B1299F9A6A7056E8"
211 "0A897E318476A5A18029E63B2ED739A6"
212 "1791D339F58DC763D9D14911F2EDEC38"
213 "3DEE11F6319B44510E7A3ECD9B79B973"
214 "82E49500ACF8117DC89CAF0E621F7775"
215 "6554A2FD4664BFE7AB8B59AB48340DBF"
216 "A27B93B5A81F6ECDEB02D0759307128D"
217 "F3E3BAD4055C8B840216DFAA5700670E"
218 "6C5126F0962FCB70FF308F25049164CC"
219 "F76CC2DA66A7DD9A81A714C2809D6918"
220 "6133D29D84568E892B6FFBF3199BDB14"
221 "383EE224407F190358F111A949552ABA"
222 "6714227D1BD7F6B20DD0CB88F9467B71"
223 "9339F33BFF35B3870B3F62204E4286B0"
224 "948EA348B524544B5F9838F29EE643B0"
225 "79EEF8A713B220D7806924CDF7295070"
226 "C5"
227 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
228 "02820100" // INTEGER length 0x100 (privateExponent) value...
229 "69F377F35F2F584EF075353CCD1CA997"
230 "38DB3DBC7C7FF35F9366CE176DFD1B13"
231 "5AB10030344ABF5FBECF1D4659FDEF1C"
232 "0FC430834BE1BE3911951377BB3D563A"
233 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
234 "2686C7B4B3C09A7B8354133E6F93F790"
235 "D59EAEB92E84C9A4339302CCE28FDF04"
236 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
237 "6AB706645BF074A4E4090D06FB163124"
238 "365FD5EE7A20D350E9958CC30D91326E"
239 "1B292E9EF5DB408EC42DAF737D201497"
240 "04D0A678A0FB5B5446863B099228A352"
241 "D604BA8091A164D01D5AB05397C71EAD"
242 "20BE2A08FC528FE442817809C787FEE4"
243 "AB97F97B9130D022153EDC6EB6CBE7B0"
244 "F8E3473F2E901209B5DB10F93604DB01"
245 "028181" // INTEGER length 0x81 (prime1)
246 "00E83C0998214941EA4F9293F1B77E2E"
247 "99E6CF305FAF358238E126124FEAF2EB"
248 "9724B2EA7B78E6032343821A80E55D1D"
249 "88FB12D220C3F41A56142FEC85796D19"
250 "17F1E8C774F142B67D3D6E7B7E6B4383"
251 "E94DB5929089DBB346D5BDAB40CC2D96"
252 "EE0409475E175C63BF78CFD744136740"
253 "838127EA723FF3FE7FA368C1311B4A4E"
254 "05"
255 "028181" // INTEGER length 0x81 (prime2)
256 "00D240FCC0F5D7715CDE21CB2DC86EA1"
257 "46132EA3B06F61FF2AF54BF38473F59D"
258 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
259 "B1B58C39F95E4798CCBB43E83D0119AC"
260 "F532F359CA743C85199F0286610E2009"
261 "97D7312917179AC9B67558773212EC96"
262 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
263 "94D94E066A0900B7B70E82A44FB30053"
264 "C1"
265 "028181" // INTEGER length 0x81 (exponent1)
266 "00AD15DA1CBD6A492B66851BA8C316D3"
267 "8AB700E2CFDDD926A658003513C54BAA"
268 "152B30021D667D20078F500F8AD3E7F3"
269 "945D74A891ED1A28EAD0FEEAEC8C14A8"
270 "E834CF46A13D1378C99D18940823CFDD"
271 "27EC5810D59339E0C34198AC638E09C8"
272 "7CBB1B634A9864AE9F4D5EB2D53514F6"
273 "7B4CAEC048C8AB849A02E397618F3271"
274 "35"
275 "028180" // INTEGER length 0x80 (exponent2)
276 "1FA2C1A5331880A92D8F3E281C617108"
277 "BF38244F16E352E69ED417C7153F9EC3"
278 "18F211839C643DCF8B4DD67CE2AC312E"
279 "95178D5D952F06B1BF779F4916924B70"
280 "F582A23F11304E02A5E7565AE22A35E7"
281 "4FECC8B6FDC93F92A1A37703E4CF0E63"
282 "783BD02EB716A7ECBBFA606B10B74D01"
283 "579522E7EF84D91FC522292108D902C1"
284 "028180" // INTEGER length 0x80 (coefficient)
285 "796FE3825F9DCC85DF22D58690065D93"
286 "898ACD65C087BEA8DA3A63BF4549B795"
287 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
288 "0D74F40DED8E1102C52152A31B6165F8"
289 "3A6722AECFCC35A493D7634664B888A0"
290 "8D3EB034F12EA28BFEE346E205D33482"
291 "7F778B16ED40872BD29FCB36536B6E93"
292 "FFB06778696B4A9D81BB0A9423E63DE5"
293 // } end SEQUENCE (PrivateKey)
294 // } end SEQUENCE (PrivateKeyInfo)
295);
Selene Huange5727e62021-04-13 22:41:20 -0700296
David Drysdaled2cc8c22021-04-15 13:29:45 +0100297string ec_256_key = hex2str(
298 // RFC 5208 s5
299 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
300 "020100" // INTEGER length 1 value 0 (version)
301 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
302 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
303 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
304 "0608" // OBJECT IDENTIFIER length 8 (param)
305 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
306 // } end SEQUENCE (AlgorithmIdentifier)
307 "046d" // OCTET STRING length 0x6d (privateKey) holding...
308 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
309 "020101" // INTEGER length 1 value 1 (version)
310 "0420" // OCTET STRING length 0x20 (privateKey)
311 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
312 "941eed09366bc03299986481f3a4d859"
313 "a144" // TAG [1] len 0x44 (publicKey) {
314 "03420004bf85d7720d07c25461683bc6"
315 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
316 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
317 "bcc41c6eb00083cf3376d11fd44949e0"
318 "b2183bfe"
319 // } end SEQUENCE (ECPrivateKey)
320 // } end SEQUENCE (PrivateKeyInfo)
321);
Selene Huang31ab4042020-04-29 04:22:39 -0700322
David Drysdaled2cc8c22021-04-15 13:29:45 +0100323string ec_521_key = hex2str(
324 // RFC 5208 s5
325 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
326 "020100" // INTEGER length 1 value 0 (version)
327 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
328 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
329 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
330 "0605" // OBJECT IDENTIFIER length 5 (param)
331 "2B81040023" // 1.3.132.0.35 (secp521r1)
332 // } end SEQUENCE (AlgorithmIdentifier)
333 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
334 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
335 "020101" // INTEGER length 1 value 1 (version)
336 "0442" // OCTET STRING length 0x42 (privateKey)
337 "0011458C586DB5DAA92AFAB03F4FE46A"
338 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
339 "9D18D7D08B5BCFA0E53C75B064AD51C4"
340 "49BAE0258D54B94B1E885DED08ED4FB2"
341 "5CE9"
342 "A18189" // TAG [1] len 0x89 (publicKey) {
343 "03818600040149EC11C6DF0FA122C6A9"
344 "AFD9754A4FA9513A627CA329E349535A"
345 "5629875A8ADFBE27DCB932C051986377"
346 "108D054C28C6F39B6F2C9AF81802F9F3"
347 "26B842FF2E5F3C00AB7635CFB36157FC"
348 "0882D574A10D839C1A0C049DC5E0D775"
349 "E2EE50671A208431BB45E78E70BEFE93"
350 "0DB34818EE4D5C26259F5C6B8E28A652"
351 "950F9F88D7B4B2C9D9"
352 // } end SEQUENCE (ECPrivateKey)
353 // } end SEQUENCE (PrivateKeyInfo)
354);
Selene Huang31ab4042020-04-29 04:22:39 -0700355
David Drysdaled2cc8c22021-04-15 13:29:45 +0100356string ec_256_key_rfc5915 = hex2str(
357 // RFC 5208 s5
358 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
359 "020100" // INTEGER length 1 value 0 (version)
360 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
361 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
362 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
363 "0608" // OBJECT IDENTIFIER length 8 (param)
364 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
365 // } end SEQUENCE (AlgorithmIdentifier)
366 "0479" // OCTET STRING length 0x79 (privateKey) holding...
367 // RFC 5915 s3
368 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
369 "020101" // INTEGER length 1 value 1 (version)
370 "0420" // OCTET STRING length 0x42 (privateKey)
371 "782370a8c8ce5537baadd04dcff079c8"
372 "158cfa9c67b818b38e8d21c9fa750c1d"
373 "a00a" // TAG [0] length 0xa (parameters)
374 "0608" // OBJECT IDENTIFIER length 8
375 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
376 // } end TAG [0]
377 "a144" // TAG [1] length 0x44 (publicKey) {
378 "0342" // BIT STRING length 0x42
379 "00" // no pad bits
380 "04e2cc561ee701da0ad0ef0d176bb0c9"
381 "19d42e79c393fdc1bd6c4010d85cf2cf"
382 "8e68c905464666f98dad4f01573ba810"
383 "78b3428570a439ba3229fbc026c55068"
384 "2f"
385 // } end SEQUENCE (ECPrivateKey)
386 // } end SEQUENCE (PrivateKeyInfo)
387);
Selene Huang31ab4042020-04-29 04:22:39 -0700388
David Drysdaled2cc8c22021-04-15 13:29:45 +0100389string ec_256_key_sec1 = hex2str(
390 // RFC 5208 s5
391 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
392 "020100" // INTEGER length 1 value 0 (version)
393 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
394 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
395 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
396 "0608" // OBJECT IDENTIFIER length 8 (param)
397 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
398 // } end SEQUENCE (AlgorithmIdentifier)
399 "046d" // OCTET STRING length 0x6d (privateKey) holding...
400 // SEC1-v2 C.4
401 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
402 "020101" // INTEGER length 1 value 0x01 (version)
403 "0420" // OCTET STRING length 0x20 (privateKey)
404 "782370a8c8ce5537baadd04dcff079c8"
405 "158cfa9c67b818b38e8d21c9fa750c1d"
406 "a144" // TAG [1] length 0x44 (publicKey) {
407 "0342" // BIT STRING length 0x42
408 "00" // no pad bits
409 "04e2cc561ee701da0ad0ef0d176bb0c9"
410 "19d42e79c393fdc1bd6c4010d85cf2cf"
411 "8e68c905464666f98dad4f01573ba810"
412 "78b3428570a439ba3229fbc026c55068"
413 "2f"
414 // } end TAG [1] (publicKey)
415 // } end SEQUENCE (PrivateKeyInfo)
416);
Selene Huang31ab4042020-04-29 04:22:39 -0700417
418struct RSA_Delete {
419 void operator()(RSA* p) { RSA_free(p); }
420};
421
Selene Huang31ab4042020-04-29 04:22:39 -0700422std::string make_string(const uint8_t* data, size_t length) {
423 return std::string(reinterpret_cast<const char*>(data), length);
424}
425
426template <size_t N>
427std::string make_string(const uint8_t (&a)[N]) {
428 return make_string(a, N);
429}
430
431class AidlBuf : public vector<uint8_t> {
432 typedef vector<uint8_t> super;
433
434 public:
435 AidlBuf() {}
436 AidlBuf(const super& other) : super(other) {}
437 AidlBuf(super&& other) : super(std::move(other)) {}
438 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
439
440 AidlBuf& operator=(const super& other) {
441 super::operator=(other);
442 return *this;
443 }
444
445 AidlBuf& operator=(super&& other) {
446 super::operator=(std::move(other));
447 return *this;
448 }
449
450 AidlBuf& operator=(const string& other) {
451 resize(other.size());
452 for (size_t i = 0; i < other.size(); ++i) {
453 (*this)[i] = static_cast<uint8_t>(other[i]);
454 }
455 return *this;
456 }
457
458 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
459};
460
David Drysdale4dc01072021-04-01 12:17:35 +0100461string device_suffix(const string& name) {
462 size_t pos = name.find('/');
463 if (pos == string::npos) {
464 return name;
465 }
466 return name.substr(pos + 1);
467}
468
469bool matching_rp_instance(const string& km_name,
470 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
471 string km_suffix = device_suffix(km_name);
472
473 vector<string> rp_names =
474 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
475 for (const string& rp_name : rp_names) {
476 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
477 // KeyMint instance, assume they match.
478 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
479 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
480 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
481 return true;
482 }
483 }
484 return false;
485}
486
Selene Huang31ab4042020-04-29 04:22:39 -0700487} // namespace
488
489class NewKeyGenerationTest : public KeyMintAidlTestBase {
490 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700491 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000492 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700493 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700494
Selene Huang31ab4042020-04-29 04:22:39 -0700495 // Check that some unexpected tags/values are NOT present.
496 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
497 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000498 }
499
500 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
501 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
502 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
503 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
504
505 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000506 }
507
508 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
509 // TODO(swillden): Distinguish which params should be in which auth list.
510 AuthorizationSet auths;
511 for (auto& entry : keyCharacteristics) {
512 auths.push_back(AuthorizationSet(entry.authorizations));
513 }
514 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
515
516 // Verify that App data, ROT and auth timeout are NOT included.
517 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
518 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700519 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
520
David Drysdaled2cc8c22021-04-15 13:29:45 +0100521 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
522 // never adds it.
523 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
524
David Drysdale7de9feb2021-03-05 14:56:19 +0000525 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700526 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000527 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700528 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700529 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000530 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700531 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000532
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000533 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100534 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
535 EXPECT_TRUE(vendor_pl);
536 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000537
538 // Should include boot patchlevel (but there are some test scenarios where this is not
539 // possible).
540 if (check_boot_pl) {
541 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
542 EXPECT_TRUE(boot_pl);
543 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100544
David Drysdale7de9feb2021-03-05 14:56:19 +0000545 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700546 }
547};
548
549/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000550 * NewKeyGenerationTest.Aes
551 *
552 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
553 * have correct characteristics.
554 */
555TEST_P(NewKeyGenerationTest, Aes) {
556 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
557 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
558 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
559 SCOPED_TRACE(testing::Message()
560 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
561 vector<uint8_t> key_blob;
562 vector<KeyCharacteristics> key_characteristics;
563 auto builder = AuthorizationSetBuilder()
564 .AesEncryptionKey(key_size)
565 .BlockMode(block_mode)
566 .Padding(padding_mode)
567 .SetDefaultValidity();
568 if (block_mode == BlockMode::GCM) {
569 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
570 }
571 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
572
573 EXPECT_GT(key_blob.size(), 0U);
574 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100575 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000576
577 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
578
579 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
580 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
581 << "Key size " << key_size << "missing";
582
583 CheckedDeleteKey(&key_blob);
584 }
585 }
586 }
587}
588
589/*
590 * NewKeyGenerationTest.AesInvalidSize
591 *
592 * Verifies that specifying an invalid key size for AES key generation returns
593 * UNSUPPORTED_KEY_SIZE.
594 */
595TEST_P(NewKeyGenerationTest, AesInvalidSize) {
596 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
597 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
598 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
599 SCOPED_TRACE(testing::Message()
600 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
601 vector<uint8_t> key_blob;
602 vector<KeyCharacteristics> key_characteristics;
603 auto builder = AuthorizationSetBuilder()
604 .AesEncryptionKey(key_size)
605 .BlockMode(block_mode)
606 .Padding(padding_mode)
607 .SetDefaultValidity();
608 if (block_mode == BlockMode::GCM) {
609 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
610 }
611 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
612 GenerateKey(builder, &key_blob, &key_characteristics));
613 }
614 }
615 }
616
617 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
618 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
619 vector<uint8_t> key_blob;
620 vector<KeyCharacteristics> key_characteristics;
621 // No key size specified
622 auto builder = AuthorizationSetBuilder()
623 .Authorization(TAG_ALGORITHM, Algorithm::AES)
624 .BlockMode(block_mode)
625 .Padding(padding_mode)
626 .SetDefaultValidity();
627 if (block_mode == BlockMode::GCM) {
628 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
629 }
630 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
631 GenerateKey(builder, &key_blob, &key_characteristics));
632 }
633 }
634}
635
636/*
637 * NewKeyGenerationTest.AesInvalidPadding
638 *
639 * Verifies that specifying an invalid padding on AES keys gives a failure
640 * somewhere along the way.
641 */
642TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
643 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
644 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
645 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
646 SCOPED_TRACE(testing::Message()
647 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000648 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800649 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000650 .AesEncryptionKey(key_size)
651 .BlockMode(block_mode)
652 .Padding(padding_mode)
653 .SetDefaultValidity();
654 if (block_mode == BlockMode::GCM) {
655 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
656 }
657
Tommy Chiu3950b452021-05-03 22:01:46 +0800658 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000659 if (result == ErrorCode::OK) {
660 // Key creation was OK but has generated a key that cannot be used.
661 auto params =
662 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800663 if (block_mode == BlockMode::GCM) {
664 params.Authorization(TAG_MAC_LENGTH, 128);
665 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000666 auto result = Begin(KeyPurpose::ENCRYPT, params);
667 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100668 result == ErrorCode::INVALID_KEY_BLOB)
669 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000670 } else {
671 // The KeyMint implementation detected that the generated key
672 // is unusable.
673 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
674 }
675 }
676 }
677 }
678}
679
680/*
681 * NewKeyGenerationTest.AesGcmMissingMinMac
682 *
683 * Verifies that specifying an invalid key size for AES key generation returns
684 * UNSUPPORTED_KEY_SIZE.
685 */
686TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
687 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
688 BlockMode block_mode = BlockMode::GCM;
689 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
690 SCOPED_TRACE(testing::Message()
691 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
692 vector<uint8_t> key_blob;
693 vector<KeyCharacteristics> key_characteristics;
694 // No MIN_MAC_LENGTH provided.
695 auto builder = AuthorizationSetBuilder()
696 .AesEncryptionKey(key_size)
697 .BlockMode(block_mode)
698 .Padding(padding_mode)
699 .SetDefaultValidity();
700 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
701 GenerateKey(builder, &key_blob, &key_characteristics));
702 }
703 }
704}
705
706/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100707 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
708 *
709 * Verifies that specifying an invalid min MAC size for AES key generation returns
710 * UNSUPPORTED_MIN_MAC_LENGTH.
711 */
712TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
713 for (size_t min_mac_len : {88, 136}) {
714 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
715 BlockMode block_mode = BlockMode::GCM;
716 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
717 SCOPED_TRACE(testing::Message()
718 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
719 vector<uint8_t> key_blob;
720 vector<KeyCharacteristics> key_characteristics;
721 auto builder = AuthorizationSetBuilder()
722 .AesEncryptionKey(key_size)
723 .BlockMode(block_mode)
724 .Padding(padding_mode)
725 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
726 .SetDefaultValidity();
727 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
728 GenerateKey(builder, &key_blob, &key_characteristics));
729 }
730 }
731 }
732}
733
734/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000735 * NewKeyGenerationTest.TripleDes
736 *
737 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
738 * have correct characteristics.
739 */
740TEST_P(NewKeyGenerationTest, TripleDes) {
741 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
742 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
743 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
744 SCOPED_TRACE(testing::Message()
745 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
746 vector<uint8_t> key_blob;
747 vector<KeyCharacteristics> key_characteristics;
748 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
749 .TripleDesEncryptionKey(key_size)
750 .BlockMode(block_mode)
751 .Padding(padding_mode)
752 .Authorization(TAG_NO_AUTH_REQUIRED)
753 .SetDefaultValidity(),
754 &key_blob, &key_characteristics));
755
756 EXPECT_GT(key_blob.size(), 0U);
757 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100758 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000759
760 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
761
762 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
763 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
764 << "Key size " << key_size << "missing";
765
766 CheckedDeleteKey(&key_blob);
767 }
768 }
769 }
770}
771
772/*
773 * NewKeyGenerationTest.TripleDesWithAttestation
774 *
775 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
776 * have correct characteristics.
777 *
778 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
779 * put in a certificate) but which isn't an error.
780 */
781TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
782 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
783 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
784 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
785 SCOPED_TRACE(testing::Message()
786 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
787
788 auto challenge = "hello";
789 auto app_id = "foo";
790
791 vector<uint8_t> key_blob;
792 vector<KeyCharacteristics> key_characteristics;
793 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
794 .TripleDesEncryptionKey(key_size)
795 .BlockMode(block_mode)
796 .Padding(padding_mode)
797 .Authorization(TAG_NO_AUTH_REQUIRED)
798 .AttestationChallenge(challenge)
799 .AttestationApplicationId(app_id)
800 .SetDefaultValidity(),
801 &key_blob, &key_characteristics));
802
803 EXPECT_GT(key_blob.size(), 0U);
804 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100805 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000806
807 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
808
809 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
810 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
811 << "Key size " << key_size << "missing";
812
813 CheckedDeleteKey(&key_blob);
814 }
815 }
816 }
817}
818
819/*
820 * NewKeyGenerationTest.TripleDesInvalidSize
821 *
822 * Verifies that specifying an invalid key size for 3-DES key generation returns
823 * UNSUPPORTED_KEY_SIZE.
824 */
825TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
826 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
827 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
828 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
829 SCOPED_TRACE(testing::Message()
830 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
831 vector<uint8_t> key_blob;
832 vector<KeyCharacteristics> key_characteristics;
833 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
834 GenerateKey(AuthorizationSetBuilder()
835 .TripleDesEncryptionKey(key_size)
836 .BlockMode(block_mode)
837 .Padding(padding_mode)
838 .Authorization(TAG_NO_AUTH_REQUIRED)
839 .SetDefaultValidity(),
840 &key_blob, &key_characteristics));
841 }
842 }
843 }
844
845 // Omitting the key size fails.
846 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
847 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
848 SCOPED_TRACE(testing::Message()
849 << "3DES-default-" << block_mode << "-" << padding_mode);
850 vector<uint8_t> key_blob;
851 vector<KeyCharacteristics> key_characteristics;
852 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
853 GenerateKey(AuthorizationSetBuilder()
854 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
855 .BlockMode(block_mode)
856 .Padding(padding_mode)
857 .Authorization(TAG_NO_AUTH_REQUIRED)
858 .SetDefaultValidity(),
859 &key_blob, &key_characteristics));
860 }
861 }
862}
863
864/*
Selene Huang31ab4042020-04-29 04:22:39 -0700865 * NewKeyGenerationTest.Rsa
866 *
867 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
868 * have correct characteristics.
869 */
870TEST_P(NewKeyGenerationTest, Rsa) {
871 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
872 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700873 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700874 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
875 .RsaSigningKey(key_size, 65537)
876 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800877 .Padding(PaddingMode::NONE)
878 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700879 &key_blob, &key_characteristics));
880
881 ASSERT_GT(key_blob.size(), 0U);
882 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100883 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700884
Shawn Willden7f424372021-01-10 18:06:50 -0700885 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700886
887 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
888 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
889 << "Key size " << key_size << "missing";
890 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
891
892 CheckedDeleteKey(&key_blob);
893 }
894}
895
896/*
Qi Wud22ec842020-11-26 13:27:53 +0800897 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700898 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100899 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
900 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700901 */
902TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700903 auto challenge = "hello";
904 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700905
Selene Huang6e46f142021-04-20 19:20:11 -0700906 auto subject = "cert subj 2";
907 vector<uint8_t> subject_der(make_name_from_str(subject));
908
909 uint64_t serial_int = 66;
910 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
911
Selene Huang4f64c222021-04-13 19:54:36 -0700912 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700913 vector<uint8_t> key_blob;
914 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700915 ASSERT_EQ(ErrorCode::OK,
916 GenerateKey(AuthorizationSetBuilder()
917 .RsaSigningKey(key_size, 65537)
918 .Digest(Digest::NONE)
919 .Padding(PaddingMode::NONE)
920 .AttestationChallenge(challenge)
921 .AttestationApplicationId(app_id)
922 .Authorization(TAG_NO_AUTH_REQUIRED)
923 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
924 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
925 .SetDefaultValidity(),
926 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700927
928 ASSERT_GT(key_blob.size(), 0U);
929 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100930 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700931
932 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
933
934 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
935 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
936 << "Key size " << key_size << "missing";
937 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
938
Selene Huang6e46f142021-04-20 19:20:11 -0700939 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700940 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700941 ASSERT_GT(cert_chain_.size(), 0);
942
943 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
944 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +0000945 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700946 sw_enforced, hw_enforced, SecLevel(),
947 cert_chain_[0].encodedCertificate));
948
949 CheckedDeleteKey(&key_blob);
950 }
951}
952
953/*
David Drysdale4dc01072021-04-01 12:17:35 +0100954 * NewKeyGenerationTest.RsaWithRpkAttestation
955 *
956 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
957 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +0100958 *
959 * This test is disabled because the KeyMint specification does not require that implementations
960 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
961 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +0100962 */
David Drysdale0fce69d2021-04-13 17:22:13 +0100963TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +0100964 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
965 // instance.
966 std::shared_ptr<IRemotelyProvisionedComponent> rp;
967 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
968 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
969
970 // Generate a P-256 keypair to use as an attestation key.
971 MacedPublicKey macedPubKey;
972 std::vector<uint8_t> privateKeyBlob;
973 auto status =
974 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
975 ASSERT_TRUE(status.isOk());
976 vector<uint8_t> coseKeyData;
977 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
978
979 AttestationKey attestation_key;
980 attestation_key.keyBlob = std::move(privateKeyBlob);
981 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
982
983 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
984 auto challenge = "hello";
985 auto app_id = "foo";
986
987 vector<uint8_t> key_blob;
988 vector<KeyCharacteristics> key_characteristics;
989 ASSERT_EQ(ErrorCode::OK,
990 GenerateKey(AuthorizationSetBuilder()
991 .RsaSigningKey(key_size, 65537)
992 .Digest(Digest::NONE)
993 .Padding(PaddingMode::NONE)
994 .AttestationChallenge(challenge)
995 .AttestationApplicationId(app_id)
996 .Authorization(TAG_NO_AUTH_REQUIRED)
997 .SetDefaultValidity(),
998 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
999
1000 ASSERT_GT(key_blob.size(), 0U);
1001 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001002 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001003
1004 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1005
1006 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1007 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1008 << "Key size " << key_size << "missing";
1009 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1010
1011 // Attestation by itself is not valid (last entry is not self-signed).
1012 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1013
1014 // The signature over the attested key should correspond to the P256 public key.
1015 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1016 ASSERT_TRUE(key_cert.get());
1017 EVP_PKEY_Ptr signing_pubkey;
1018 p256_pub_key(coseKeyData, &signing_pubkey);
1019 ASSERT_TRUE(signing_pubkey.get());
1020
1021 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1022 << "Verification of attested certificate failed "
1023 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1024
1025 CheckedDeleteKey(&key_blob);
1026 }
1027}
1028
1029/*
Selene Huang4f64c222021-04-13 19:54:36 -07001030 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1031 *
1032 * Verifies that keymint attestation for RSA encryption keys with challenge and
1033 * app id is also successful.
1034 */
1035TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1036 auto key_size = 2048;
1037 auto challenge = "hello";
1038 auto app_id = "foo";
1039
Selene Huang6e46f142021-04-20 19:20:11 -07001040 auto subject = "subj 2";
1041 vector<uint8_t> subject_der(make_name_from_str(subject));
1042
1043 uint64_t serial_int = 111166;
1044 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1045
Selene Huang4f64c222021-04-13 19:54:36 -07001046 vector<uint8_t> key_blob;
1047 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001048 ASSERT_EQ(ErrorCode::OK,
1049 GenerateKey(AuthorizationSetBuilder()
1050 .RsaEncryptionKey(key_size, 65537)
1051 .Padding(PaddingMode::NONE)
1052 .AttestationChallenge(challenge)
1053 .AttestationApplicationId(app_id)
1054 .Authorization(TAG_NO_AUTH_REQUIRED)
1055 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1056 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1057 .SetDefaultValidity(),
1058 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001059
1060 ASSERT_GT(key_blob.size(), 0U);
1061 AuthorizationSet auths;
1062 for (auto& entry : key_characteristics) {
1063 auths.push_back(AuthorizationSet(entry.authorizations));
1064 }
1065
1066 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1067 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1068
1069 // Verify that App data and ROT are NOT included.
1070 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1071 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1072
1073 // Check that some unexpected tags/values are NOT present.
1074 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1075 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1076
1077 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1078
1079 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1080 ASSERT_TRUE(os_ver);
1081 EXPECT_EQ(*os_ver, os_version());
1082
1083 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1084
1085 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1086 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1087 << "Key size " << key_size << "missing";
1088 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1089
Selene Huang6e46f142021-04-20 19:20:11 -07001090 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001091 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1092 ASSERT_GT(cert_chain_.size(), 0);
1093
1094 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1095 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001096 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001097 sw_enforced, hw_enforced, SecLevel(),
1098 cert_chain_[0].encodedCertificate));
1099
1100 CheckedDeleteKey(&key_blob);
1101}
1102
1103/*
1104 * NewKeyGenerationTest.RsaWithSelfSign
1105 *
1106 * Verifies that attesting to RSA key generation is successful, and returns
1107 * self signed certificate if no challenge is provided. And signing etc
1108 * works as expected.
1109 */
1110TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001111 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1112 vector<uint8_t> subject_der(make_name_from_str(subject));
1113
1114 uint64_t serial_int = 0;
1115 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1116
Selene Huang4f64c222021-04-13 19:54:36 -07001117 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1118 vector<uint8_t> key_blob;
1119 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001120 ASSERT_EQ(ErrorCode::OK,
1121 GenerateKey(AuthorizationSetBuilder()
1122 .RsaSigningKey(key_size, 65537)
1123 .Digest(Digest::NONE)
1124 .Padding(PaddingMode::NONE)
1125 .Authorization(TAG_NO_AUTH_REQUIRED)
1126 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1127 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1128 .SetDefaultValidity(),
1129 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001130
1131 ASSERT_GT(key_blob.size(), 0U);
1132 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001133 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001134
1135 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1136
1137 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1138 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1139 << "Key size " << key_size << "missing";
1140 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1141
Selene Huang6e46f142021-04-20 19:20:11 -07001142 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001143 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1144 ASSERT_EQ(cert_chain_.size(), 1);
1145
1146 CheckedDeleteKey(&key_blob);
1147 }
1148}
1149
1150/*
1151 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1152 *
1153 * Verifies that attesting to RSA checks for missing app ID.
1154 */
1155TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1156 auto challenge = "hello";
1157 vector<uint8_t> key_blob;
1158 vector<KeyCharacteristics> key_characteristics;
1159
1160 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1161 GenerateKey(AuthorizationSetBuilder()
1162 .RsaSigningKey(2048, 65537)
1163 .Digest(Digest::NONE)
1164 .Padding(PaddingMode::NONE)
1165 .AttestationChallenge(challenge)
1166 .Authorization(TAG_NO_AUTH_REQUIRED)
1167 .SetDefaultValidity(),
1168 &key_blob, &key_characteristics));
1169}
1170
1171/*
1172 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1173 *
1174 * Verifies that attesting to RSA ignores app id if challenge is missing.
1175 */
1176TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1177 auto key_size = 2048;
1178 auto app_id = "foo";
1179
Selene Huang6e46f142021-04-20 19:20:11 -07001180 auto subject = "cert subj 2";
1181 vector<uint8_t> subject_der(make_name_from_str(subject));
1182
1183 uint64_t serial_int = 1;
1184 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1185
Selene Huang4f64c222021-04-13 19:54:36 -07001186 vector<uint8_t> key_blob;
1187 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001188 ASSERT_EQ(ErrorCode::OK,
1189 GenerateKey(AuthorizationSetBuilder()
1190 .RsaSigningKey(key_size, 65537)
1191 .Digest(Digest::NONE)
1192 .Padding(PaddingMode::NONE)
1193 .AttestationApplicationId(app_id)
1194 .Authorization(TAG_NO_AUTH_REQUIRED)
1195 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1196 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1197 .SetDefaultValidity(),
1198 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001199
1200 ASSERT_GT(key_blob.size(), 0U);
1201 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001202 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001203
1204 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1205
1206 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1207 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1208 << "Key size " << key_size << "missing";
1209 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1210
Selene Huang6e46f142021-04-20 19:20:11 -07001211 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001212 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1213 ASSERT_EQ(cert_chain_.size(), 1);
1214
1215 CheckedDeleteKey(&key_blob);
1216}
1217
1218/*
Qi Wud22ec842020-11-26 13:27:53 +08001219 * NewKeyGenerationTest.LimitedUsageRsa
1220 *
1221 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1222 * resulting keys have correct characteristics.
1223 */
1224TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1225 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1226 vector<uint8_t> key_blob;
1227 vector<KeyCharacteristics> key_characteristics;
1228 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1229 .RsaSigningKey(key_size, 65537)
1230 .Digest(Digest::NONE)
1231 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001232 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1233 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001234 &key_blob, &key_characteristics));
1235
1236 ASSERT_GT(key_blob.size(), 0U);
1237 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001238 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001239
1240 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1241
1242 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1243 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1244 << "Key size " << key_size << "missing";
1245 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1246
1247 // Check the usage count limit tag appears in the authorizations.
1248 AuthorizationSet auths;
1249 for (auto& entry : key_characteristics) {
1250 auths.push_back(AuthorizationSet(entry.authorizations));
1251 }
1252 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1253 << "key usage count limit " << 1U << " missing";
1254
1255 CheckedDeleteKey(&key_blob);
1256 }
1257}
1258
1259/*
Qi Wubeefae42021-01-28 23:16:37 +08001260 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1261 *
1262 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1263 * resulting keys have correct characteristics and attestation.
1264 */
1265TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001266 auto challenge = "hello";
1267 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001268
Selene Huang6e46f142021-04-20 19:20:11 -07001269 auto subject = "cert subj 2";
1270 vector<uint8_t> subject_der(make_name_from_str(subject));
1271
1272 uint64_t serial_int = 66;
1273 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1274
Selene Huang4f64c222021-04-13 19:54:36 -07001275 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001276 vector<uint8_t> key_blob;
1277 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001278 ASSERT_EQ(ErrorCode::OK,
1279 GenerateKey(AuthorizationSetBuilder()
1280 .RsaSigningKey(key_size, 65537)
1281 .Digest(Digest::NONE)
1282 .Padding(PaddingMode::NONE)
1283 .AttestationChallenge(challenge)
1284 .AttestationApplicationId(app_id)
1285 .Authorization(TAG_NO_AUTH_REQUIRED)
1286 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1287 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1288 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1289 .SetDefaultValidity(),
1290 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001291
1292 ASSERT_GT(key_blob.size(), 0U);
1293 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001294 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001295
1296 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1297
1298 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1299 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1300 << "Key size " << key_size << "missing";
1301 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1302
1303 // Check the usage count limit tag appears in the authorizations.
1304 AuthorizationSet auths;
1305 for (auto& entry : key_characteristics) {
1306 auths.push_back(AuthorizationSet(entry.authorizations));
1307 }
1308 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1309 << "key usage count limit " << 1U << " missing";
1310
1311 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001312 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001313 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001314 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001315
1316 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1317 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001318 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001319 sw_enforced, hw_enforced, SecLevel(),
1320 cert_chain_[0].encodedCertificate));
1321
1322 CheckedDeleteKey(&key_blob);
1323 }
1324}
1325
1326/*
Selene Huang31ab4042020-04-29 04:22:39 -07001327 * NewKeyGenerationTest.NoInvalidRsaSizes
1328 *
1329 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1330 */
1331TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1332 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1333 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001334 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001335 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1336 GenerateKey(AuthorizationSetBuilder()
1337 .RsaSigningKey(key_size, 65537)
1338 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001339 .Padding(PaddingMode::NONE)
1340 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001341 &key_blob, &key_characteristics));
1342 }
1343}
1344
1345/*
1346 * NewKeyGenerationTest.RsaNoDefaultSize
1347 *
1348 * Verifies that failing to specify a key size for RSA key generation returns
1349 * UNSUPPORTED_KEY_SIZE.
1350 */
1351TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1352 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1353 GenerateKey(AuthorizationSetBuilder()
1354 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1355 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001356 .SigningKey()
1357 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001358}
1359
1360/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001361 * NewKeyGenerationTest.RsaMissingParams
1362 *
1363 * Verifies that omitting optional tags works.
1364 */
1365TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1366 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1367 ASSERT_EQ(ErrorCode::OK,
1368 GenerateKey(
1369 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1370 CheckedDeleteKey();
1371 }
1372}
1373
1374/*
Selene Huang31ab4042020-04-29 04:22:39 -07001375 * NewKeyGenerationTest.Ecdsa
1376 *
1377 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1378 * have correct characteristics.
1379 */
1380TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001381 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001382 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001383 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001384 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001385 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001386 .Digest(Digest::NONE)
1387 .SetDefaultValidity(),
1388 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001389 ASSERT_GT(key_blob.size(), 0U);
1390 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001391 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001392
Shawn Willden7f424372021-01-10 18:06:50 -07001393 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001394
1395 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001396 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001397
1398 CheckedDeleteKey(&key_blob);
1399 }
1400}
1401
1402/*
Selene Huang4f64c222021-04-13 19:54:36 -07001403 * NewKeyGenerationTest.EcdsaAttestation
1404 *
1405 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1406 * an attestation will be generated.
1407 */
1408TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1409 auto challenge = "hello";
1410 auto app_id = "foo";
1411
Selene Huang6e46f142021-04-20 19:20:11 -07001412 auto subject = "cert subj 2";
1413 vector<uint8_t> subject_der(make_name_from_str(subject));
1414
1415 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1416 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1417
David Drysdaledf09e542021-06-08 15:46:11 +01001418 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001419 vector<uint8_t> key_blob;
1420 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001421 ASSERT_EQ(ErrorCode::OK,
1422 GenerateKey(AuthorizationSetBuilder()
1423 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001424 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001425 .Digest(Digest::NONE)
1426 .AttestationChallenge(challenge)
1427 .AttestationApplicationId(app_id)
1428 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1429 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1430 .SetDefaultValidity(),
1431 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001432 ASSERT_GT(key_blob.size(), 0U);
1433 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001434 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001435
1436 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1437
1438 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001439 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001440
1441 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1442 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001443 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001444
1445 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1446 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001447 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001448 sw_enforced, hw_enforced, SecLevel(),
1449 cert_chain_[0].encodedCertificate));
1450
1451 CheckedDeleteKey(&key_blob);
1452 }
1453}
1454
1455/*
David Drysdale37af4b32021-05-14 16:46:59 +01001456 * NewKeyGenerationTest.EcdsaAttestationTags
1457 *
1458 * Verifies that creation of an attested ECDSA key includes various tags in the
1459 * attestation extension.
1460 */
1461TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1462 auto challenge = "hello";
1463 auto app_id = "foo";
1464 auto subject = "cert subj 2";
1465 vector<uint8_t> subject_der(make_name_from_str(subject));
1466 uint64_t serial_int = 0x1010;
1467 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1468 const AuthorizationSetBuilder base_builder =
1469 AuthorizationSetBuilder()
1470 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001471 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001472 .Digest(Digest::NONE)
1473 .AttestationChallenge(challenge)
1474 .AttestationApplicationId(app_id)
1475 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1476 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1477 .SetDefaultValidity();
1478
1479 // Various tags that map to fields in the attestation extension ASN.1 schema.
1480 auto extra_tags = AuthorizationSetBuilder()
1481 .Authorization(TAG_ROLLBACK_RESISTANCE)
1482 .Authorization(TAG_EARLY_BOOT_ONLY)
1483 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1484 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1485 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1486 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1487 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1488 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1489 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1490 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1491 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1492 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001493
David Drysdale37af4b32021-05-14 16:46:59 +01001494 for (const KeyParameter& tag : extra_tags) {
1495 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1496 vector<uint8_t> key_blob;
1497 vector<KeyCharacteristics> key_characteristics;
1498 AuthorizationSetBuilder builder = base_builder;
1499 builder.push_back(tag);
1500 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1501 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1502 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1503 continue;
1504 }
Seth Mooreb393b082021-07-12 14:18:28 -07001505 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1506 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001507 continue;
1508 }
1509 ASSERT_EQ(result, ErrorCode::OK);
1510 ASSERT_GT(key_blob.size(), 0U);
1511
1512 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1513 ASSERT_GT(cert_chain_.size(), 0);
1514 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1515
1516 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1517 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001518 // Some tags are optional, so don't require them to be in the enforcements.
1519 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001520 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1521 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1522 }
1523
1524 // Verifying the attestation record will check for the specific tag because
1525 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001526 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1527 hw_enforced, SecLevel(),
1528 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001529
1530 CheckedDeleteKey(&key_blob);
1531 }
1532
David Drysdalec53b7d92021-10-11 12:35:58 +01001533 // Collection of invalid attestation ID tags.
1534 auto invalid_tags =
1535 AuthorizationSetBuilder()
1536 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1537 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1538 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1539 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1540 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1541 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1542 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1543 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001544 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001545 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001546 vector<uint8_t> key_blob;
1547 vector<KeyCharacteristics> key_characteristics;
1548 AuthorizationSetBuilder builder =
1549 AuthorizationSetBuilder()
1550 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001551 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001552 .Digest(Digest::NONE)
1553 .AttestationChallenge(challenge)
1554 .AttestationApplicationId(app_id)
1555 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1556 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1557 .SetDefaultValidity();
1558 builder.push_back(tag);
1559 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1560 GenerateKey(builder, &key_blob, &key_characteristics));
1561 }
1562}
1563
1564/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001565 * NewKeyGenerationTest.EcdsaAttestationIdTags
1566 *
1567 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1568 * attestation extension.
1569 */
1570TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
1571 auto challenge = "hello";
1572 auto app_id = "foo";
1573 auto subject = "cert subj 2";
1574 vector<uint8_t> subject_der(make_name_from_str(subject));
1575 uint64_t serial_int = 0x1010;
1576 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1577 const AuthorizationSetBuilder base_builder =
1578 AuthorizationSetBuilder()
1579 .Authorization(TAG_NO_AUTH_REQUIRED)
1580 .EcdsaSigningKey(EcCurve::P_256)
1581 .Digest(Digest::NONE)
1582 .AttestationChallenge(challenge)
1583 .AttestationApplicationId(app_id)
1584 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1585 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1586 .SetDefaultValidity();
1587
1588 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1589 auto extra_tags = AuthorizationSetBuilder();
1590 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1591 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1592 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1593 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1594 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1595 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1596
1597 for (const KeyParameter& tag : extra_tags) {
1598 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1599 vector<uint8_t> key_blob;
1600 vector<KeyCharacteristics> key_characteristics;
1601 AuthorizationSetBuilder builder = base_builder;
1602 builder.push_back(tag);
1603 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1604 if (result == ErrorCode::CANNOT_ATTEST_IDS) {
1605 // Device ID attestation is optional; KeyMint may not support it at all.
1606 continue;
1607 }
1608 ASSERT_EQ(result, ErrorCode::OK);
1609 ASSERT_GT(key_blob.size(), 0U);
1610
1611 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1612 ASSERT_GT(cert_chain_.size(), 0);
1613 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1614
1615 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1616 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1617
1618 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
1619 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
1620 // attestation extension should contain them, so make sure the extra tag is added.
1621 hw_enforced.push_back(tag);
1622
1623 // Verifying the attestation record will check for the specific tag because
1624 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001625 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1626 hw_enforced, SecLevel(),
1627 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01001628
1629 CheckedDeleteKey(&key_blob);
1630 }
1631}
1632
1633/*
David Drysdale565ccc72021-10-11 12:49:50 +01001634 * NewKeyGenerationTest.EcdsaAttestationUniqueId
1635 *
1636 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
1637 */
1638TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
1639 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00001640 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01001641 auto challenge = "hello";
1642 auto subject = "cert subj 2";
1643 vector<uint8_t> subject_der(make_name_from_str(subject));
1644 uint64_t serial_int = 0x1010;
1645 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00001646 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01001647 AuthorizationSetBuilder()
1648 .Authorization(TAG_NO_AUTH_REQUIRED)
1649 .Authorization(TAG_INCLUDE_UNIQUE_ID)
1650 .EcdsaSigningKey(EcCurve::P_256)
1651 .Digest(Digest::NONE)
1652 .AttestationChallenge(challenge)
1653 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1654 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1655 .AttestationApplicationId(app_id)
1656 .Authorization(TAG_CREATION_DATETIME, datetime)
1657 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00001658 if (reset) {
1659 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
1660 }
David Drysdale565ccc72021-10-11 12:49:50 +01001661
1662 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
1663 ASSERT_GT(key_blob_.size(), 0U);
1664
1665 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1666 ASSERT_GT(cert_chain_.size(), 0);
1667 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1668
1669 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
1670 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
1671
1672 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001673 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1674 hw_enforced, SecLevel(),
1675 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01001676 EXPECT_GT(unique_id->size(), 0);
1677 CheckedDeleteKey();
1678 };
1679
1680 // Generate unique ID
1681 auto app_id = "foo";
1682 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
1683 vector<uint8_t> unique_id;
1684 get_unique_id(app_id, cert_date, &unique_id);
1685
1686 // Generating a new key with the same parameters should give the same unique ID.
1687 vector<uint8_t> unique_id2;
1688 get_unique_id(app_id, cert_date, &unique_id2);
1689 EXPECT_EQ(unique_id, unique_id2);
1690
1691 // Generating a new key with a slightly different date should give the same unique ID.
1692 uint64_t rounded_date = cert_date / 2592000000LLU;
1693 uint64_t min_date = rounded_date * 2592000000LLU;
1694 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
1695
1696 vector<uint8_t> unique_id3;
1697 get_unique_id(app_id, min_date, &unique_id3);
1698 EXPECT_EQ(unique_id, unique_id3);
1699
1700 vector<uint8_t> unique_id4;
1701 get_unique_id(app_id, max_date, &unique_id4);
1702 EXPECT_EQ(unique_id, unique_id4);
1703
1704 // A different attestation application ID should yield a different unique ID.
1705 auto app_id2 = "different_foo";
1706 vector<uint8_t> unique_id5;
1707 get_unique_id(app_id2, cert_date, &unique_id5);
1708 EXPECT_NE(unique_id, unique_id5);
1709
1710 // A radically different date should yield a different unique ID.
1711 vector<uint8_t> unique_id6;
1712 get_unique_id(app_id, 1611621648000, &unique_id6);
1713 EXPECT_NE(unique_id, unique_id6);
1714
1715 vector<uint8_t> unique_id7;
1716 get_unique_id(app_id, max_date + 1, &unique_id7);
1717 EXPECT_NE(unique_id, unique_id7);
1718
1719 vector<uint8_t> unique_id8;
1720 get_unique_id(app_id, min_date - 1, &unique_id8);
1721 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00001722
1723 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
1724 vector<uint8_t> unique_id9;
1725 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
1726 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01001727}
1728
1729/*
David Drysdale37af4b32021-05-14 16:46:59 +01001730 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1731 *
1732 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1733 */
1734TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1735 auto challenge = "hello";
1736 auto attest_app_id = "foo";
1737 auto subject = "cert subj 2";
1738 vector<uint8_t> subject_der(make_name_from_str(subject));
1739 uint64_t serial_int = 0x1010;
1740 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1741
1742 // Earlier versions of the attestation extension schema included a slot:
1743 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1744 // This should never have been included, and should never be filled in.
1745 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1746 // to confirm that this field never makes it into the attestation extension.
1747 vector<uint8_t> key_blob;
1748 vector<KeyCharacteristics> key_characteristics;
1749 auto result = GenerateKey(AuthorizationSetBuilder()
1750 .Authorization(TAG_NO_AUTH_REQUIRED)
1751 .EcdsaSigningKey(EcCurve::P_256)
1752 .Digest(Digest::NONE)
1753 .AttestationChallenge(challenge)
1754 .AttestationApplicationId(attest_app_id)
1755 .Authorization(TAG_APPLICATION_ID, "client_id")
1756 .Authorization(TAG_APPLICATION_DATA, "appdata")
1757 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1758 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1759 .SetDefaultValidity(),
1760 &key_blob, &key_characteristics);
1761 ASSERT_EQ(result, ErrorCode::OK);
1762 ASSERT_GT(key_blob.size(), 0U);
1763
1764 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1765 ASSERT_GT(cert_chain_.size(), 0);
1766 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1767
1768 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1769 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001770 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
1771 hw_enforced, SecLevel(),
1772 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001773
1774 // Check that the app id is not in the cert.
1775 string app_id = "clientid";
1776 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1777 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1778 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1779 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1780 cert_chain_[0].encodedCertificate.end());
1781
1782 CheckedDeleteKey(&key_blob);
1783}
1784
1785/*
Selene Huang4f64c222021-04-13 19:54:36 -07001786 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1787 *
1788 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1789 * the key will generate a self signed attestation.
1790 */
1791TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001792 auto subject = "cert subj 2";
1793 vector<uint8_t> subject_der(make_name_from_str(subject));
1794
1795 uint64_t serial_int = 0x123456FFF1234;
1796 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1797
David Drysdaledf09e542021-06-08 15:46:11 +01001798 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001799 vector<uint8_t> key_blob;
1800 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001801 ASSERT_EQ(ErrorCode::OK,
1802 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001803 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001804 .Digest(Digest::NONE)
1805 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1806 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1807 .SetDefaultValidity(),
1808 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001809 ASSERT_GT(key_blob.size(), 0U);
1810 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001811 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001812
1813 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1814
1815 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001816 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001817
1818 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001819 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001820 ASSERT_EQ(cert_chain_.size(), 1);
1821
1822 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1823 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1824
1825 CheckedDeleteKey(&key_blob);
1826 }
1827}
1828
1829/*
1830 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1831 *
1832 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1833 * app id must also be provided or else it will fail.
1834 */
1835TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1836 auto challenge = "hello";
1837 vector<uint8_t> key_blob;
1838 vector<KeyCharacteristics> key_characteristics;
1839
1840 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1841 GenerateKey(AuthorizationSetBuilder()
1842 .EcdsaSigningKey(EcCurve::P_256)
1843 .Digest(Digest::NONE)
1844 .AttestationChallenge(challenge)
1845 .SetDefaultValidity(),
1846 &key_blob, &key_characteristics));
1847}
1848
1849/*
1850 * NewKeyGenerationTest.EcdsaIgnoreAppId
1851 *
1852 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1853 * any appid will be ignored, and keymint will generate a self sign certificate.
1854 */
1855TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1856 auto app_id = "foo";
1857
David Drysdaledf09e542021-06-08 15:46:11 +01001858 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001859 vector<uint8_t> key_blob;
1860 vector<KeyCharacteristics> key_characteristics;
1861 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001862 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001863 .Digest(Digest::NONE)
1864 .AttestationApplicationId(app_id)
1865 .SetDefaultValidity(),
1866 &key_blob, &key_characteristics));
1867
1868 ASSERT_GT(key_blob.size(), 0U);
1869 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001870 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001871
1872 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1873
1874 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001875 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001876
1877 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1878 ASSERT_EQ(cert_chain_.size(), 1);
1879
1880 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1881 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1882
1883 CheckedDeleteKey(&key_blob);
1884 }
1885}
1886
1887/*
1888 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1889 *
1890 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1891 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1892 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1893 * to specify how many following bytes will be used to encode the length.
1894 */
1895TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1896 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001897 std::vector<uint32_t> app_id_lengths{143, 258};
1898
1899 for (uint32_t length : app_id_lengths) {
1900 const string app_id(length, 'a');
1901 vector<uint8_t> key_blob;
1902 vector<KeyCharacteristics> key_characteristics;
1903 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1904 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001905 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001906 .Digest(Digest::NONE)
1907 .AttestationChallenge(challenge)
1908 .AttestationApplicationId(app_id)
1909 .SetDefaultValidity(),
1910 &key_blob, &key_characteristics));
1911 ASSERT_GT(key_blob.size(), 0U);
1912 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001913 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001914
1915 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1916
1917 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001918 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001919
1920 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1921 ASSERT_GT(cert_chain_.size(), 0);
1922
1923 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1924 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001925 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001926 sw_enforced, hw_enforced, SecLevel(),
1927 cert_chain_[0].encodedCertificate));
1928
1929 CheckedDeleteKey(&key_blob);
1930 }
1931}
1932
1933/*
Qi Wud22ec842020-11-26 13:27:53 +08001934 * NewKeyGenerationTest.LimitedUsageEcdsa
1935 *
1936 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1937 * resulting keys have correct characteristics.
1938 */
1939TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001940 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001941 vector<uint8_t> key_blob;
1942 vector<KeyCharacteristics> key_characteristics;
1943 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001944 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001945 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001946 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1947 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001948 &key_blob, &key_characteristics));
1949
1950 ASSERT_GT(key_blob.size(), 0U);
1951 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001952 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001953
1954 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1955
1956 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001957 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001958
1959 // Check the usage count limit tag appears in the authorizations.
1960 AuthorizationSet auths;
1961 for (auto& entry : key_characteristics) {
1962 auths.push_back(AuthorizationSet(entry.authorizations));
1963 }
1964 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1965 << "key usage count limit " << 1U << " missing";
1966
1967 CheckedDeleteKey(&key_blob);
1968 }
1969}
1970
1971/*
Selene Huang31ab4042020-04-29 04:22:39 -07001972 * NewKeyGenerationTest.EcdsaDefaultSize
1973 *
David Drysdaledf09e542021-06-08 15:46:11 +01001974 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001975 * UNSUPPORTED_KEY_SIZE.
1976 */
1977TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1978 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1979 GenerateKey(AuthorizationSetBuilder()
1980 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1981 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001982 .Digest(Digest::NONE)
1983 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001984}
1985
1986/*
1987 * NewKeyGenerationTest.EcdsaInvalidSize
1988 *
1989 * Verifies that specifying an invalid key size for EC key generation returns
1990 * UNSUPPORTED_KEY_SIZE.
1991 */
1992TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdaledf09e542021-06-08 15:46:11 +01001993 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001994 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001995 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001996 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001997 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001998 .Digest(Digest::NONE)
1999 .SetDefaultValidity(),
2000 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07002001 }
2002
David Drysdaledf09e542021-06-08 15:46:11 +01002003 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2004 GenerateKey(AuthorizationSetBuilder()
2005 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2006 .Authorization(TAG_KEY_SIZE, 190)
2007 .SigningKey()
2008 .Digest(Digest::NONE)
2009 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002010}
2011
2012/*
2013 * NewKeyGenerationTest.EcdsaMismatchKeySize
2014 *
2015 * Verifies that specifying mismatched key size and curve for EC key generation returns
2016 * INVALID_ARGUMENT.
2017 */
2018TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002019 if (SecLevel() == SecurityLevel::STRONGBOX) {
2020 GTEST_SKIP() << "Test not applicable to StrongBox device";
2021 }
Selene Huang31ab4042020-04-29 04:22:39 -07002022
David Drysdaledf09e542021-06-08 15:46:11 +01002023 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002024 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002025 .Authorization(TAG_KEY_SIZE, 224)
2026 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002027 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002028 .Digest(Digest::NONE)
2029 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002030 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002031}
2032
2033/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002034 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002035 *
2036 * Verifies that keymint does not support any curve designated as unsupported.
2037 */
2038TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2039 Digest digest;
2040 if (SecLevel() == SecurityLevel::STRONGBOX) {
2041 digest = Digest::SHA_2_256;
2042 } else {
2043 digest = Digest::SHA_2_512;
2044 }
2045 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002046 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2047 .EcdsaSigningKey(curve)
2048 .Digest(digest)
2049 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002050 << "Failed to generate key on curve: " << curve;
2051 CheckedDeleteKey();
2052 }
2053}
2054
2055/*
2056 * NewKeyGenerationTest.Hmac
2057 *
2058 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2059 * characteristics.
2060 */
2061TEST_P(NewKeyGenerationTest, Hmac) {
2062 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2063 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002064 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002065 constexpr size_t key_size = 128;
2066 ASSERT_EQ(ErrorCode::OK,
2067 GenerateKey(
2068 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2069 TAG_MIN_MAC_LENGTH, 128),
2070 &key_blob, &key_characteristics));
2071
2072 ASSERT_GT(key_blob.size(), 0U);
2073 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002074 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002075
Shawn Willden7f424372021-01-10 18:06:50 -07002076 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2077 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2078 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2079 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002080
2081 CheckedDeleteKey(&key_blob);
2082 }
2083}
2084
2085/*
Selene Huang4f64c222021-04-13 19:54:36 -07002086 * NewKeyGenerationTest.HmacNoAttestation
2087 *
2088 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2089 * and app id are provided.
2090 */
2091TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2092 auto challenge = "hello";
2093 auto app_id = "foo";
2094
2095 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2096 vector<uint8_t> key_blob;
2097 vector<KeyCharacteristics> key_characteristics;
2098 constexpr size_t key_size = 128;
2099 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2100 .HmacKey(key_size)
2101 .Digest(digest)
2102 .AttestationChallenge(challenge)
2103 .AttestationApplicationId(app_id)
2104 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2105 &key_blob, &key_characteristics));
2106
2107 ASSERT_GT(key_blob.size(), 0U);
2108 ASSERT_EQ(cert_chain_.size(), 0);
2109 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002110 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002111
2112 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2113 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2114 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2115 << "Key size " << key_size << "missing";
2116
2117 CheckedDeleteKey(&key_blob);
2118 }
2119}
2120
2121/*
Qi Wud22ec842020-11-26 13:27:53 +08002122 * NewKeyGenerationTest.LimitedUsageHmac
2123 *
2124 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2125 * resulting keys have correct characteristics.
2126 */
2127TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2128 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2129 vector<uint8_t> key_blob;
2130 vector<KeyCharacteristics> key_characteristics;
2131 constexpr size_t key_size = 128;
2132 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2133 .HmacKey(key_size)
2134 .Digest(digest)
2135 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2136 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2137 &key_blob, &key_characteristics));
2138
2139 ASSERT_GT(key_blob.size(), 0U);
2140 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002141 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002142
2143 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2144 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2145 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2146 << "Key size " << key_size << "missing";
2147
2148 // Check the usage count limit tag appears in the authorizations.
2149 AuthorizationSet auths;
2150 for (auto& entry : key_characteristics) {
2151 auths.push_back(AuthorizationSet(entry.authorizations));
2152 }
2153 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2154 << "key usage count limit " << 1U << " missing";
2155
2156 CheckedDeleteKey(&key_blob);
2157 }
2158}
2159
2160/*
Selene Huang31ab4042020-04-29 04:22:39 -07002161 * NewKeyGenerationTest.HmacCheckKeySizes
2162 *
2163 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2164 */
2165TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2166 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2167 if (key_size < 64 || key_size % 8 != 0) {
2168 // To keep this test from being very slow, we only test a random fraction of
2169 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2170 // them, we expect to run ~40 of them in each run.
2171 if (key_size % 8 == 0 || random() % 10 == 0) {
2172 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2173 GenerateKey(AuthorizationSetBuilder()
2174 .HmacKey(key_size)
2175 .Digest(Digest::SHA_2_256)
2176 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2177 << "HMAC key size " << key_size << " invalid";
2178 }
2179 } else {
2180 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2181 .HmacKey(key_size)
2182 .Digest(Digest::SHA_2_256)
2183 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2184 << "Failed to generate HMAC key of size " << key_size;
2185 CheckedDeleteKey();
2186 }
2187 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002188 if (SecLevel() == SecurityLevel::STRONGBOX) {
2189 // STRONGBOX devices must not support keys larger than 512 bits.
2190 size_t key_size = 520;
2191 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2192 GenerateKey(AuthorizationSetBuilder()
2193 .HmacKey(key_size)
2194 .Digest(Digest::SHA_2_256)
2195 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2196 << "HMAC key size " << key_size << " unexpectedly valid";
2197 }
Selene Huang31ab4042020-04-29 04:22:39 -07002198}
2199
2200/*
2201 * NewKeyGenerationTest.HmacCheckMinMacLengths
2202 *
2203 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2204 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2205 * specific MAC length that failed, so reproducing a failed run will be easy.
2206 */
2207TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2208 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2209 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2210 // To keep this test from being very long, we only test a random fraction of
2211 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2212 // we expect to run ~17 of them in each run.
2213 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2214 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2215 GenerateKey(AuthorizationSetBuilder()
2216 .HmacKey(128)
2217 .Digest(Digest::SHA_2_256)
2218 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2219 << "HMAC min mac length " << min_mac_length << " invalid.";
2220 }
2221 } else {
2222 EXPECT_EQ(ErrorCode::OK,
2223 GenerateKey(AuthorizationSetBuilder()
2224 .HmacKey(128)
2225 .Digest(Digest::SHA_2_256)
2226 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2227 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2228 CheckedDeleteKey();
2229 }
2230 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002231
2232 // Minimum MAC length must be no more than 512 bits.
2233 size_t min_mac_length = 520;
2234 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2235 GenerateKey(AuthorizationSetBuilder()
2236 .HmacKey(128)
2237 .Digest(Digest::SHA_2_256)
2238 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2239 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002240}
2241
2242/*
2243 * NewKeyGenerationTest.HmacMultipleDigests
2244 *
2245 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2246 */
2247TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002248 if (SecLevel() == SecurityLevel::STRONGBOX) {
2249 GTEST_SKIP() << "Test not applicable to StrongBox device";
2250 }
Selene Huang31ab4042020-04-29 04:22:39 -07002251
2252 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2253 GenerateKey(AuthorizationSetBuilder()
2254 .HmacKey(128)
2255 .Digest(Digest::SHA1)
2256 .Digest(Digest::SHA_2_256)
2257 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2258}
2259
2260/*
2261 * NewKeyGenerationTest.HmacDigestNone
2262 *
2263 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2264 */
2265TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2266 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2267 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2268 128)));
2269
2270 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2271 GenerateKey(AuthorizationSetBuilder()
2272 .HmacKey(128)
2273 .Digest(Digest::NONE)
2274 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2275}
2276
Selene Huang4f64c222021-04-13 19:54:36 -07002277/*
2278 * NewKeyGenerationTest.AesNoAttestation
2279 *
2280 * Verifies that attestation parameters to AES keys are ignored and generateKey
2281 * will succeed.
2282 */
2283TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2284 auto challenge = "hello";
2285 auto app_id = "foo";
2286
2287 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2288 .Authorization(TAG_NO_AUTH_REQUIRED)
2289 .AesEncryptionKey(128)
2290 .EcbMode()
2291 .Padding(PaddingMode::PKCS7)
2292 .AttestationChallenge(challenge)
2293 .AttestationApplicationId(app_id)));
2294
2295 ASSERT_EQ(cert_chain_.size(), 0);
2296}
2297
2298/*
2299 * NewKeyGenerationTest.TripleDesNoAttestation
2300 *
2301 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2302 * will be successful. No attestation should be generated.
2303 */
2304TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2305 auto challenge = "hello";
2306 auto app_id = "foo";
2307
2308 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2309 .TripleDesEncryptionKey(168)
2310 .BlockMode(BlockMode::ECB)
2311 .Authorization(TAG_NO_AUTH_REQUIRED)
2312 .Padding(PaddingMode::NONE)
2313 .AttestationChallenge(challenge)
2314 .AttestationApplicationId(app_id)));
2315 ASSERT_EQ(cert_chain_.size(), 0);
2316}
2317
Selene Huang31ab4042020-04-29 04:22:39 -07002318INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2319
2320typedef KeyMintAidlTestBase SigningOperationsTest;
2321
2322/*
2323 * SigningOperationsTest.RsaSuccess
2324 *
2325 * Verifies that raw RSA signature operations succeed.
2326 */
2327TEST_P(SigningOperationsTest, RsaSuccess) {
2328 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2329 .RsaSigningKey(2048, 65537)
2330 .Digest(Digest::NONE)
2331 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002332 .Authorization(TAG_NO_AUTH_REQUIRED)
2333 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002334 string message = "12345678901234567890123456789012";
2335 string signature = SignMessage(
2336 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002337 LocalVerifyMessage(message, signature,
2338 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2339}
2340
2341/*
2342 * SigningOperationsTest.RsaAllPaddingsAndDigests
2343 *
2344 * Verifies RSA signature/verification for all padding modes and digests.
2345 */
2346TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2347 auto authorizations = AuthorizationSetBuilder()
2348 .Authorization(TAG_NO_AUTH_REQUIRED)
2349 .RsaSigningKey(2048, 65537)
2350 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2351 .Padding(PaddingMode::NONE)
2352 .Padding(PaddingMode::RSA_PSS)
2353 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2354 .SetDefaultValidity();
2355
2356 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2357
2358 string message(128, 'a');
2359 string corrupt_message(message);
2360 ++corrupt_message[corrupt_message.size() / 2];
2361
2362 for (auto padding :
2363 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2364 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2365 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2366 // Digesting only makes sense with padding.
2367 continue;
2368 }
2369
2370 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2371 // PSS requires digesting.
2372 continue;
2373 }
2374
2375 string signature =
2376 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2377 LocalVerifyMessage(message, signature,
2378 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2379 }
2380 }
Selene Huang31ab4042020-04-29 04:22:39 -07002381}
2382
2383/*
2384 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2385 *
Shawn Willden7f424372021-01-10 18:06:50 -07002386 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002387 */
2388TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2389 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2390 .Authorization(TAG_NO_AUTH_REQUIRED)
2391 .RsaSigningKey(2048, 65537)
2392 .Digest(Digest::NONE)
2393 .Padding(PaddingMode::NONE)
2394 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002395 .Authorization(TAG_APPLICATION_DATA, "appdata")
2396 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002397
2398 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2399
Selene Huang31ab4042020-04-29 04:22:39 -07002400 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2401 Begin(KeyPurpose::SIGN,
2402 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2403 AbortIfNeeded();
2404 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2405 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2406 .Digest(Digest::NONE)
2407 .Padding(PaddingMode::NONE)
2408 .Authorization(TAG_APPLICATION_ID, "clientid")));
2409 AbortIfNeeded();
2410 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2411 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2412 .Digest(Digest::NONE)
2413 .Padding(PaddingMode::NONE)
2414 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2415 AbortIfNeeded();
2416 EXPECT_EQ(ErrorCode::OK,
2417 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2418 .Digest(Digest::NONE)
2419 .Padding(PaddingMode::NONE)
2420 .Authorization(TAG_APPLICATION_DATA, "appdata")
2421 .Authorization(TAG_APPLICATION_ID, "clientid")));
2422 AbortIfNeeded();
2423}
2424
2425/*
2426 * SigningOperationsTest.RsaPssSha256Success
2427 *
2428 * Verifies that RSA-PSS signature operations succeed.
2429 */
2430TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2431 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2432 .RsaSigningKey(2048, 65537)
2433 .Digest(Digest::SHA_2_256)
2434 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002435 .Authorization(TAG_NO_AUTH_REQUIRED)
2436 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002437 // Use large message, which won't work without digesting.
2438 string message(1024, 'a');
2439 string signature = SignMessage(
2440 message,
2441 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2442}
2443
2444/*
2445 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2446 *
2447 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2448 * supports only unpadded operations.
2449 */
2450TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2451 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2452 .RsaSigningKey(2048, 65537)
2453 .Digest(Digest::NONE)
2454 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002455 .Padding(PaddingMode::NONE)
2456 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002457 string message = "12345678901234567890123456789012";
2458 string signature;
2459
2460 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2461 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2462 .Digest(Digest::NONE)
2463 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2464}
2465
2466/*
2467 * SigningOperationsTest.NoUserConfirmation
2468 *
2469 * Verifies that keymint rejects signing operations for keys with
2470 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2471 * presented.
2472 */
2473TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002474 if (SecLevel() == SecurityLevel::STRONGBOX) {
2475 GTEST_SKIP() << "Test not applicable to StrongBox device";
2476 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002477 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2478 .RsaSigningKey(1024, 65537)
2479 .Digest(Digest::NONE)
2480 .Padding(PaddingMode::NONE)
2481 .Authorization(TAG_NO_AUTH_REQUIRED)
2482 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2483 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002484
2485 const string message = "12345678901234567890123456789012";
2486 EXPECT_EQ(ErrorCode::OK,
2487 Begin(KeyPurpose::SIGN,
2488 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2489 string signature;
2490 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2491}
2492
2493/*
2494 * SigningOperationsTest.RsaPkcs1Sha256Success
2495 *
2496 * Verifies that digested RSA-PKCS1 signature operations succeed.
2497 */
2498TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2499 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2500 .RsaSigningKey(2048, 65537)
2501 .Digest(Digest::SHA_2_256)
2502 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002503 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2504 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002505 string message(1024, 'a');
2506 string signature = SignMessage(message, AuthorizationSetBuilder()
2507 .Digest(Digest::SHA_2_256)
2508 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2509}
2510
2511/*
2512 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2513 *
2514 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2515 */
2516TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2517 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2518 .RsaSigningKey(2048, 65537)
2519 .Digest(Digest::NONE)
2520 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002521 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2522 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002523 string message(53, 'a');
2524 string signature = SignMessage(message, AuthorizationSetBuilder()
2525 .Digest(Digest::NONE)
2526 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2527}
2528
2529/*
2530 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2531 *
2532 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2533 * given a too-long message.
2534 */
2535TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2536 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2537 .RsaSigningKey(2048, 65537)
2538 .Digest(Digest::NONE)
2539 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002540 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2541 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002542 string message(257, 'a');
2543
2544 EXPECT_EQ(ErrorCode::OK,
2545 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2546 .Digest(Digest::NONE)
2547 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2548 string signature;
2549 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2550}
2551
2552/*
2553 * SigningOperationsTest.RsaPssSha512TooSmallKey
2554 *
2555 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2556 * used with a key that is too small for the message.
2557 *
2558 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2559 * keymint specification requires that salt_size == digest_size, so the message will be
2560 * digest_size * 2 +
2561 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2562 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2563 * for a 1024-bit key.
2564 */
2565TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01002566 if (SecLevel() == SecurityLevel::STRONGBOX) {
2567 GTEST_SKIP() << "Test not applicable to StrongBox device";
2568 }
Selene Huang31ab4042020-04-29 04:22:39 -07002569 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2570 .RsaSigningKey(1024, 65537)
2571 .Digest(Digest::SHA_2_512)
2572 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002573 .Padding(PaddingMode::RSA_PSS)
2574 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002575 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2576 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2577 .Digest(Digest::SHA_2_512)
2578 .Padding(PaddingMode::RSA_PSS)));
2579}
2580
2581/*
2582 * SigningOperationsTest.RsaNoPaddingTooLong
2583 *
2584 * Verifies that raw RSA signature operations fail with the correct error code when
2585 * given a too-long message.
2586 */
2587TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2589 .RsaSigningKey(2048, 65537)
2590 .Digest(Digest::NONE)
2591 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002592 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2593 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002594 // One byte too long
2595 string message(2048 / 8 + 1, 'a');
2596 ASSERT_EQ(ErrorCode::OK,
2597 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2598 .Digest(Digest::NONE)
2599 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2600 string result;
2601 ErrorCode finish_error_code = Finish(message, &result);
2602 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2603 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2604
2605 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2606 message = string(128 * 1024, 'a');
2607 ASSERT_EQ(ErrorCode::OK,
2608 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2609 .Digest(Digest::NONE)
2610 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2611 finish_error_code = Finish(message, &result);
2612 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2613 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2614}
2615
2616/*
2617 * SigningOperationsTest.RsaAbort
2618 *
2619 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2620 * test, but the behavior should be algorithm and purpose-independent.
2621 */
2622TEST_P(SigningOperationsTest, RsaAbort) {
2623 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2624 .RsaSigningKey(2048, 65537)
2625 .Digest(Digest::NONE)
2626 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002627 .Padding(PaddingMode::NONE)
2628 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002629
2630 ASSERT_EQ(ErrorCode::OK,
2631 Begin(KeyPurpose::SIGN,
2632 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2633 EXPECT_EQ(ErrorCode::OK, Abort());
2634
2635 // Another abort should fail
2636 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2637
2638 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002639 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002640}
2641
2642/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002643 * SigningOperationsTest.RsaNonUniqueParams
2644 *
2645 * Verifies that an operation with multiple padding modes is rejected.
2646 */
2647TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2648 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2649 .RsaSigningKey(2048, 65537)
2650 .Digest(Digest::NONE)
2651 .Digest(Digest::SHA1)
2652 .Authorization(TAG_NO_AUTH_REQUIRED)
2653 .Padding(PaddingMode::NONE)
2654 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2655 .SetDefaultValidity()));
2656
2657 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2658 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2659 .Digest(Digest::NONE)
2660 .Padding(PaddingMode::NONE)
2661 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2662
Tommy Chiuc93c4392021-05-11 18:36:50 +08002663 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2664 .Digest(Digest::NONE)
2665 .Digest(Digest::SHA1)
2666 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2667 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002668
2669 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2670 Begin(KeyPurpose::SIGN,
2671 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2672}
2673
2674/*
Selene Huang31ab4042020-04-29 04:22:39 -07002675 * SigningOperationsTest.RsaUnsupportedPadding
2676 *
2677 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2678 * with a padding mode inappropriate for RSA.
2679 */
2680TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2681 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2682 .RsaSigningKey(2048, 65537)
2683 .Authorization(TAG_NO_AUTH_REQUIRED)
2684 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002685 .Padding(PaddingMode::PKCS7)
2686 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002687 ASSERT_EQ(
2688 ErrorCode::UNSUPPORTED_PADDING_MODE,
2689 Begin(KeyPurpose::SIGN,
2690 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002691 CheckedDeleteKey();
2692
2693 ASSERT_EQ(ErrorCode::OK,
2694 GenerateKey(
2695 AuthorizationSetBuilder()
2696 .RsaSigningKey(2048, 65537)
2697 .Authorization(TAG_NO_AUTH_REQUIRED)
2698 .Digest(Digest::SHA_2_256 /* supported digest */)
2699 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2700 .SetDefaultValidity()));
2701 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2702 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2703 .Digest(Digest::SHA_2_256)
2704 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002705}
2706
2707/*
2708 * SigningOperationsTest.RsaPssNoDigest
2709 *
2710 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2711 */
2712TEST_P(SigningOperationsTest, RsaNoDigest) {
2713 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2714 .RsaSigningKey(2048, 65537)
2715 .Authorization(TAG_NO_AUTH_REQUIRED)
2716 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002717 .Padding(PaddingMode::RSA_PSS)
2718 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002719 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2720 Begin(KeyPurpose::SIGN,
2721 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2722
2723 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2724 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2725}
2726
2727/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002728 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002729 *
2730 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2731 * supported in some cases (as validated in other tests), but a mode must be specified.
2732 */
2733TEST_P(SigningOperationsTest, RsaNoPadding) {
2734 // Padding must be specified
2735 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2736 .RsaKey(2048, 65537)
2737 .Authorization(TAG_NO_AUTH_REQUIRED)
2738 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002739 .Digest(Digest::NONE)
2740 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002741 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2742 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2743}
2744
2745/*
2746 * SigningOperationsTest.RsaShortMessage
2747 *
2748 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2749 */
2750TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2751 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2752 .Authorization(TAG_NO_AUTH_REQUIRED)
2753 .RsaSigningKey(2048, 65537)
2754 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002755 .Padding(PaddingMode::NONE)
2756 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002757
2758 // Barely shorter
2759 string message(2048 / 8 - 1, 'a');
2760 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2761
2762 // Much shorter
2763 message = "a";
2764 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2765}
2766
2767/*
2768 * SigningOperationsTest.RsaSignWithEncryptionKey
2769 *
2770 * Verifies that RSA encryption keys cannot be used to sign.
2771 */
2772TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2773 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2774 .Authorization(TAG_NO_AUTH_REQUIRED)
2775 .RsaEncryptionKey(2048, 65537)
2776 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002777 .Padding(PaddingMode::NONE)
2778 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002779 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2780 Begin(KeyPurpose::SIGN,
2781 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2782}
2783
2784/*
2785 * SigningOperationsTest.RsaSignTooLargeMessage
2786 *
2787 * Verifies that attempting a raw signature of a message which is the same length as the key,
2788 * but numerically larger than the public modulus, fails with the correct error.
2789 */
2790TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2791 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2792 .Authorization(TAG_NO_AUTH_REQUIRED)
2793 .RsaSigningKey(2048, 65537)
2794 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002795 .Padding(PaddingMode::NONE)
2796 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002797
2798 // Largest possible message will always be larger than the public modulus.
2799 string message(2048 / 8, static_cast<char>(0xff));
2800 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2801 .Authorization(TAG_NO_AUTH_REQUIRED)
2802 .Digest(Digest::NONE)
2803 .Padding(PaddingMode::NONE)));
2804 string signature;
2805 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2806}
2807
2808/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01002809 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2810 *
2811 * Verifies ECDSA signature/verification for all digests and curves.
2812 */
2813TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2814 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2815
2816 string message = "1234567890";
2817 string corrupt_message = "2234567890";
2818 for (auto curve : ValidCurves()) {
2819 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2820 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2821 .Authorization(TAG_NO_AUTH_REQUIRED)
2822 .EcdsaSigningKey(curve)
2823 .Digest(digests)
2824 .SetDefaultValidity());
2825 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2826 if (error != ErrorCode::OK) {
2827 continue;
2828 }
2829
2830 for (auto digest : digests) {
2831 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2832 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2833 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2834 }
2835
2836 auto rc = DeleteKey();
2837 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2838 }
2839}
2840
2841/*
Selene Huang31ab4042020-04-29 04:22:39 -07002842 * SigningOperationsTest.EcdsaAllCurves
2843 *
2844 * Verifies that ECDSA operations succeed with all possible curves.
2845 */
2846TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2847 for (auto curve : ValidCurves()) {
2848 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2849 .Authorization(TAG_NO_AUTH_REQUIRED)
2850 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002851 .Digest(Digest::SHA_2_256)
2852 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002853 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2854 if (error != ErrorCode::OK) continue;
2855
2856 string message(1024, 'a');
2857 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2858 CheckedDeleteKey();
2859 }
2860}
2861
2862/*
2863 * SigningOperationsTest.EcdsaNoDigestHugeData
2864 *
2865 * Verifies that ECDSA operations support very large messages, even without digesting. This
2866 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2867 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2868 * the framework.
2869 */
2870TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2871 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2872 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002873 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002874 .Digest(Digest::NONE)
2875 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002876 string message(1 * 1024, 'a');
2877 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2878}
2879
2880/*
2881 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2882 *
2883 * Verifies that using an EC key requires the correct app ID/data.
2884 */
2885TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2886 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2887 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002888 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002889 .Digest(Digest::NONE)
2890 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002891 .Authorization(TAG_APPLICATION_DATA, "appdata")
2892 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002893
2894 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2895
Selene Huang31ab4042020-04-29 04:22:39 -07002896 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2897 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2898 AbortIfNeeded();
2899 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2900 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2901 .Digest(Digest::NONE)
2902 .Authorization(TAG_APPLICATION_ID, "clientid")));
2903 AbortIfNeeded();
2904 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2905 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2906 .Digest(Digest::NONE)
2907 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2908 AbortIfNeeded();
2909 EXPECT_EQ(ErrorCode::OK,
2910 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2911 .Digest(Digest::NONE)
2912 .Authorization(TAG_APPLICATION_DATA, "appdata")
2913 .Authorization(TAG_APPLICATION_ID, "clientid")));
2914 AbortIfNeeded();
2915}
2916
2917/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002918 * SigningOperationsTest.EcdsaIncompatibleDigest
2919 *
2920 * Verifies that using an EC key requires compatible digest.
2921 */
2922TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2923 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2924 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002925 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002926 .Digest(Digest::NONE)
2927 .Digest(Digest::SHA1)
2928 .SetDefaultValidity()));
2929 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2930 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2931 AbortIfNeeded();
2932}
2933
2934/*
Selene Huang31ab4042020-04-29 04:22:39 -07002935 * SigningOperationsTest.AesEcbSign
2936 *
2937 * Verifies that attempts to use AES keys to sign fail in the correct way.
2938 */
2939TEST_P(SigningOperationsTest, AesEcbSign) {
2940 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2941 .Authorization(TAG_NO_AUTH_REQUIRED)
2942 .SigningKey()
2943 .AesEncryptionKey(128)
2944 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2945
2946 AuthorizationSet out_params;
2947 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2948 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2949 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2950 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2951}
2952
2953/*
2954 * SigningOperationsTest.HmacAllDigests
2955 *
2956 * Verifies that HMAC works with all digests.
2957 */
2958TEST_P(SigningOperationsTest, HmacAllDigests) {
2959 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2960 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2961 .Authorization(TAG_NO_AUTH_REQUIRED)
2962 .HmacKey(128)
2963 .Digest(digest)
2964 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2965 << "Failed to create HMAC key with digest " << digest;
2966 string message = "12345678901234567890123456789012";
2967 string signature = MacMessage(message, digest, 160);
2968 EXPECT_EQ(160U / 8U, signature.size())
2969 << "Failed to sign with HMAC key with digest " << digest;
2970 CheckedDeleteKey();
2971 }
2972}
2973
2974/*
2975 * SigningOperationsTest.HmacSha256TooLargeMacLength
2976 *
2977 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2978 * digest size.
2979 */
2980TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2981 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2982 .Authorization(TAG_NO_AUTH_REQUIRED)
2983 .HmacKey(128)
2984 .Digest(Digest::SHA_2_256)
2985 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2986 AuthorizationSet output_params;
2987 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2988 AuthorizationSetBuilder()
2989 .Digest(Digest::SHA_2_256)
2990 .Authorization(TAG_MAC_LENGTH, 264),
2991 &output_params));
2992}
2993
2994/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002995 * SigningOperationsTest.HmacSha256InvalidMacLength
2996 *
2997 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2998 * not a multiple of 8.
2999 */
3000TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3002 .Authorization(TAG_NO_AUTH_REQUIRED)
3003 .HmacKey(128)
3004 .Digest(Digest::SHA_2_256)
3005 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3006 AuthorizationSet output_params;
3007 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3008 AuthorizationSetBuilder()
3009 .Digest(Digest::SHA_2_256)
3010 .Authorization(TAG_MAC_LENGTH, 161),
3011 &output_params));
3012}
3013
3014/*
Selene Huang31ab4042020-04-29 04:22:39 -07003015 * SigningOperationsTest.HmacSha256TooSmallMacLength
3016 *
3017 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3018 * specified minimum MAC length.
3019 */
3020TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3021 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3022 .Authorization(TAG_NO_AUTH_REQUIRED)
3023 .HmacKey(128)
3024 .Digest(Digest::SHA_2_256)
3025 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3026 AuthorizationSet output_params;
3027 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3028 AuthorizationSetBuilder()
3029 .Digest(Digest::SHA_2_256)
3030 .Authorization(TAG_MAC_LENGTH, 120),
3031 &output_params));
3032}
3033
3034/*
3035 * SigningOperationsTest.HmacRfc4231TestCase3
3036 *
3037 * Validates against the test vectors from RFC 4231 test case 3.
3038 */
3039TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3040 string key(20, 0xaa);
3041 string message(50, 0xdd);
3042 uint8_t sha_224_expected[] = {
3043 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3044 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3045 };
3046 uint8_t sha_256_expected[] = {
3047 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3048 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3049 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3050 };
3051 uint8_t sha_384_expected[] = {
3052 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3053 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3054 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3055 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3056 };
3057 uint8_t sha_512_expected[] = {
3058 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3059 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3060 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3061 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3062 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3063 };
3064
3065 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3066 if (SecLevel() != SecurityLevel::STRONGBOX) {
3067 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3068 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3069 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3070 }
3071}
3072
3073/*
3074 * SigningOperationsTest.HmacRfc4231TestCase5
3075 *
3076 * Validates against the test vectors from RFC 4231 test case 5.
3077 */
3078TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3079 string key(20, 0x0c);
3080 string message = "Test With Truncation";
3081
3082 uint8_t sha_224_expected[] = {
3083 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3084 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3085 };
3086 uint8_t sha_256_expected[] = {
3087 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3088 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3089 };
3090 uint8_t sha_384_expected[] = {
3091 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3092 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3093 };
3094 uint8_t sha_512_expected[] = {
3095 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3096 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3097 };
3098
3099 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3100 if (SecLevel() != SecurityLevel::STRONGBOX) {
3101 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3102 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3103 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3104 }
3105}
3106
3107INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3108
3109typedef KeyMintAidlTestBase VerificationOperationsTest;
3110
3111/*
Selene Huang31ab4042020-04-29 04:22:39 -07003112 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3113 *
3114 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3115 */
3116TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3117 string key_material = "HelloThisIsAKey";
3118
3119 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003120 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003121 EXPECT_EQ(ErrorCode::OK,
3122 ImportKey(AuthorizationSetBuilder()
3123 .Authorization(TAG_NO_AUTH_REQUIRED)
3124 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3125 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3126 .Digest(Digest::SHA_2_256)
3127 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3128 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3129 EXPECT_EQ(ErrorCode::OK,
3130 ImportKey(AuthorizationSetBuilder()
3131 .Authorization(TAG_NO_AUTH_REQUIRED)
3132 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3133 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3134 .Digest(Digest::SHA_2_256)
3135 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3136 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3137
3138 string message = "This is a message.";
3139 string signature = SignMessage(
3140 signing_key, message,
3141 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3142
3143 // Signing key should not work.
3144 AuthorizationSet out_params;
3145 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3146 Begin(KeyPurpose::VERIFY, signing_key,
3147 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3148
3149 // Verification key should work.
3150 VerifyMessage(verification_key, message, signature,
3151 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3152
3153 CheckedDeleteKey(&signing_key);
3154 CheckedDeleteKey(&verification_key);
3155}
3156
Prashant Patildec9fdc2021-12-08 15:25:47 +00003157/*
3158 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3159 *
3160 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3161 */
3162TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3163 string key_material = "HelloThisIsAKey";
3164
3165 vector<uint8_t> signing_key, verification_key;
3166 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3167 EXPECT_EQ(ErrorCode::OK,
3168 ImportKey(AuthorizationSetBuilder()
3169 .Authorization(TAG_NO_AUTH_REQUIRED)
3170 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3171 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3172 .Digest(Digest::SHA_2_256)
3173 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3174 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3175 EXPECT_EQ(ErrorCode::OK,
3176 ImportKey(AuthorizationSetBuilder()
3177 .Authorization(TAG_NO_AUTH_REQUIRED)
3178 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3179 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3180 .Digest(Digest::SHA_2_256)
3181 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3182 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3183
3184 string message = "This is a message.";
3185 string signature = SignMessage(
3186 signing_key, message,
3187 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3188
3189 AuthorizationSet begin_out_params;
3190 ASSERT_EQ(ErrorCode::OK,
3191 Begin(KeyPurpose::VERIFY, verification_key,
3192 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3193
3194 string corruptMessage = "This is b message."; // Corrupted message
3195 string output;
3196 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3197
3198 ASSERT_EQ(ErrorCode::OK,
3199 Begin(KeyPurpose::VERIFY, verification_key,
3200 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3201
3202 signature[0] += 1; // Corrupt a signature
3203 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3204
3205 CheckedDeleteKey(&signing_key);
3206 CheckedDeleteKey(&verification_key);
3207}
3208
Selene Huang31ab4042020-04-29 04:22:39 -07003209INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3210
3211typedef KeyMintAidlTestBase ExportKeyTest;
3212
3213/*
3214 * ExportKeyTest.RsaUnsupportedKeyFormat
3215 *
3216 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3217 */
3218// TODO(seleneh) add ExportKey to GenerateKey
3219// check result
3220
3221class ImportKeyTest : public KeyMintAidlTestBase {
3222 public:
3223 template <TagType tag_type, Tag tag, typename ValueT>
3224 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3225 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003226 for (auto& entry : key_characteristics_) {
3227 if (entry.securityLevel == SecLevel()) {
3228 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3229 << "Tag " << tag << " with value " << expected
3230 << " not found at security level" << entry.securityLevel;
3231 } else {
3232 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3233 << "Tag " << tag << " found at security level " << entry.securityLevel;
3234 }
Selene Huang31ab4042020-04-29 04:22:39 -07003235 }
3236 }
3237
3238 void CheckOrigin() {
3239 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003240 // Origin isn't a crypto param, but it always lives with them.
3241 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003242 }
3243};
3244
3245/*
3246 * ImportKeyTest.RsaSuccess
3247 *
3248 * Verifies that importing and using an RSA key pair works correctly.
3249 */
3250TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003251 uint32_t key_size;
3252 string key;
3253
3254 if (SecLevel() == SecurityLevel::STRONGBOX) {
3255 key_size = 2048;
3256 key = rsa_2048_key;
3257 } else {
3258 key_size = 1024;
3259 key = rsa_key;
3260 }
3261
Selene Huang31ab4042020-04-29 04:22:39 -07003262 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3263 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003264 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003265 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003266 .Padding(PaddingMode::RSA_PSS)
3267 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003268 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003269
3270 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003271 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003272 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3273 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3274 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3275 CheckOrigin();
3276
3277 string message(1024 / 8, 'a');
3278 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3279 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003280 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003281}
3282
3283/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003284 * ImportKeyTest.RsaSuccessWithoutParams
3285 *
3286 * Verifies that importing and using an RSA key pair without specifying parameters
3287 * works correctly.
3288 */
3289TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3290 uint32_t key_size;
3291 string key;
3292
3293 if (SecLevel() == SecurityLevel::STRONGBOX) {
3294 key_size = 2048;
3295 key = rsa_2048_key;
3296 } else {
3297 key_size = 1024;
3298 key = rsa_key;
3299 }
3300
3301 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3302 .Authorization(TAG_NO_AUTH_REQUIRED)
3303 .SigningKey()
3304 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3305 .Digest(Digest::SHA_2_256)
3306 .Padding(PaddingMode::RSA_PSS)
3307 .SetDefaultValidity(),
3308 KeyFormat::PKCS8, key));
3309
3310 // Key size and public exponent are determined from the imported key material.
3311 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3312 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3313
3314 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3315 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3316 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3317 CheckOrigin();
3318
3319 string message(1024 / 8, 'a');
3320 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3321 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003322 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003323}
3324
3325/*
Selene Huang31ab4042020-04-29 04:22:39 -07003326 * ImportKeyTest.RsaKeySizeMismatch
3327 *
3328 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3329 * correct way.
3330 */
3331TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3332 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3333 ImportKey(AuthorizationSetBuilder()
3334 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3335 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003336 .Padding(PaddingMode::NONE)
3337 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003338 KeyFormat::PKCS8, rsa_key));
3339}
3340
3341/*
3342 * ImportKeyTest.RsaPublicExponentMismatch
3343 *
3344 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3345 * fails in the correct way.
3346 */
3347TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3348 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3349 ImportKey(AuthorizationSetBuilder()
3350 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3351 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003352 .Padding(PaddingMode::NONE)
3353 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003354 KeyFormat::PKCS8, rsa_key));
3355}
3356
3357/*
David Drysdalee60248c2021-10-04 12:54:13 +01003358 * ImportKeyTest.RsaAttestMultiPurposeFail
3359 *
3360 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3361 */
3362TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
3363 uint32_t key_size = 2048;
3364 string key = rsa_2048_key;
3365
3366 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3367 ImportKey(AuthorizationSetBuilder()
3368 .Authorization(TAG_NO_AUTH_REQUIRED)
3369 .RsaSigningKey(key_size, 65537)
3370 .AttestKey()
3371 .Digest(Digest::SHA_2_256)
3372 .Padding(PaddingMode::RSA_PSS)
3373 .SetDefaultValidity(),
3374 KeyFormat::PKCS8, key));
3375}
3376
3377/*
Selene Huang31ab4042020-04-29 04:22:39 -07003378 * ImportKeyTest.EcdsaSuccess
3379 *
3380 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3381 */
3382TEST_P(ImportKeyTest, EcdsaSuccess) {
3383 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3384 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003385 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003386 .Digest(Digest::SHA_2_256)
3387 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003388 KeyFormat::PKCS8, ec_256_key));
3389
3390 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003391 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3392 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3393
3394 CheckOrigin();
3395
3396 string message(32, 'a');
3397 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3398 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003399 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003400}
3401
3402/*
3403 * ImportKeyTest.EcdsaP256RFC5915Success
3404 *
3405 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3406 * correctly.
3407 */
3408TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3409 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3410 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003411 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003412 .Digest(Digest::SHA_2_256)
3413 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003414 KeyFormat::PKCS8, ec_256_key_rfc5915));
3415
3416 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003417 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3418 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3419
3420 CheckOrigin();
3421
3422 string message(32, 'a');
3423 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3424 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003425 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003426}
3427
3428/*
3429 * ImportKeyTest.EcdsaP256SEC1Success
3430 *
3431 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3432 */
3433TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3434 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3435 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003436 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003437 .Digest(Digest::SHA_2_256)
3438 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003439 KeyFormat::PKCS8, ec_256_key_sec1));
3440
3441 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003442 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3443 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3444
3445 CheckOrigin();
3446
3447 string message(32, 'a');
3448 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3449 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003450 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003451}
3452
3453/*
3454 * ImportKeyTest.Ecdsa521Success
3455 *
3456 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3457 */
3458TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01003459 if (SecLevel() == SecurityLevel::STRONGBOX) {
3460 GTEST_SKIP() << "Test not applicable to StrongBox device";
3461 }
Selene Huang31ab4042020-04-29 04:22:39 -07003462 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3463 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003464 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003465 .Digest(Digest::SHA_2_256)
3466 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003467 KeyFormat::PKCS8, ec_521_key));
3468
3469 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003470 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3471 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3472 CheckOrigin();
3473
3474 string message(32, 'a');
3475 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3476 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003477 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003478}
3479
3480/*
Selene Huang31ab4042020-04-29 04:22:39 -07003481 * ImportKeyTest.EcdsaCurveMismatch
3482 *
3483 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3484 * the correct way.
3485 */
3486TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3487 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3488 ImportKey(AuthorizationSetBuilder()
3489 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003490 .Digest(Digest::NONE)
3491 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003492 KeyFormat::PKCS8, ec_256_key));
3493}
3494
3495/*
David Drysdalee60248c2021-10-04 12:54:13 +01003496 * ImportKeyTest.EcdsaAttestMultiPurposeFail
3497 *
3498 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
3499 */
3500TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
3501 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3502 ImportKey(AuthorizationSetBuilder()
3503 .Authorization(TAG_NO_AUTH_REQUIRED)
3504 .EcdsaSigningKey(EcCurve::P_256)
3505 .AttestKey()
3506 .Digest(Digest::SHA_2_256)
3507 .SetDefaultValidity(),
3508 KeyFormat::PKCS8, ec_256_key));
3509}
3510
3511/*
Selene Huang31ab4042020-04-29 04:22:39 -07003512 * ImportKeyTest.AesSuccess
3513 *
3514 * Verifies that importing and using an AES key works.
3515 */
3516TEST_P(ImportKeyTest, AesSuccess) {
3517 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3518 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3519 .Authorization(TAG_NO_AUTH_REQUIRED)
3520 .AesEncryptionKey(key.size() * 8)
3521 .EcbMode()
3522 .Padding(PaddingMode::PKCS7),
3523 KeyFormat::RAW, key));
3524
3525 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3526 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3527 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3528 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3529 CheckOrigin();
3530
3531 string message = "Hello World!";
3532 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3533 string ciphertext = EncryptMessage(message, params);
3534 string plaintext = DecryptMessage(ciphertext, params);
3535 EXPECT_EQ(message, plaintext);
3536}
3537
3538/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003539 * ImportKeyTest.AesFailure
3540 *
3541 * Verifies that importing an invalid AES key fails.
3542 */
3543TEST_P(ImportKeyTest, AesFailure) {
3544 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3545 uint32_t bitlen = key.size() * 8;
3546 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003547 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003548 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003549 .Authorization(TAG_NO_AUTH_REQUIRED)
3550 .AesEncryptionKey(key_size)
3551 .EcbMode()
3552 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003553 KeyFormat::RAW, key);
3554 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003555 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3556 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003557 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003558
3559 // Explicit key size matches that of the provided key, but it's not a valid size.
3560 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3561 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3562 ImportKey(AuthorizationSetBuilder()
3563 .Authorization(TAG_NO_AUTH_REQUIRED)
3564 .AesEncryptionKey(long_key.size() * 8)
3565 .EcbMode()
3566 .Padding(PaddingMode::PKCS7),
3567 KeyFormat::RAW, long_key));
3568 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3569 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3570 ImportKey(AuthorizationSetBuilder()
3571 .Authorization(TAG_NO_AUTH_REQUIRED)
3572 .AesEncryptionKey(short_key.size() * 8)
3573 .EcbMode()
3574 .Padding(PaddingMode::PKCS7),
3575 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003576}
3577
3578/*
3579 * ImportKeyTest.TripleDesSuccess
3580 *
3581 * Verifies that importing and using a 3DES key works.
3582 */
3583TEST_P(ImportKeyTest, TripleDesSuccess) {
3584 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3585 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3586 .Authorization(TAG_NO_AUTH_REQUIRED)
3587 .TripleDesEncryptionKey(168)
3588 .EcbMode()
3589 .Padding(PaddingMode::PKCS7),
3590 KeyFormat::RAW, key));
3591
3592 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3593 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3594 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3595 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3596 CheckOrigin();
3597
3598 string message = "Hello World!";
3599 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3600 string ciphertext = EncryptMessage(message, params);
3601 string plaintext = DecryptMessage(ciphertext, params);
3602 EXPECT_EQ(message, plaintext);
3603}
3604
3605/*
3606 * ImportKeyTest.TripleDesFailure
3607 *
3608 * Verifies that importing an invalid 3DES key fails.
3609 */
3610TEST_P(ImportKeyTest, TripleDesFailure) {
3611 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003612 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003613 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003614 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003615 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003616 .Authorization(TAG_NO_AUTH_REQUIRED)
3617 .TripleDesEncryptionKey(key_size)
3618 .EcbMode()
3619 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003620 KeyFormat::RAW, key);
3621 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003622 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3623 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003624 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003625 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003626 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003627 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3628 ImportKey(AuthorizationSetBuilder()
3629 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003630 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003631 .EcbMode()
3632 .Padding(PaddingMode::PKCS7),
3633 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003634 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003635 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3636 ImportKey(AuthorizationSetBuilder()
3637 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003638 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003639 .EcbMode()
3640 .Padding(PaddingMode::PKCS7),
3641 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003642}
3643
3644/*
3645 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003646 *
3647 * Verifies that importing and using an HMAC key works.
3648 */
3649TEST_P(ImportKeyTest, HmacKeySuccess) {
3650 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3651 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3652 .Authorization(TAG_NO_AUTH_REQUIRED)
3653 .HmacKey(key.size() * 8)
3654 .Digest(Digest::SHA_2_256)
3655 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3656 KeyFormat::RAW, key));
3657
3658 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3659 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3660 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3661 CheckOrigin();
3662
3663 string message = "Hello World!";
3664 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3665 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3666}
3667
3668INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3669
3670auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003671 // IKeyMintDevice.aidl
3672 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3673 "020100" // INTEGER length 1 value 0x00 (version)
3674 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3675 "934bf94e2aa28a3f83c9f79297250262"
3676 "fbe3276b5a1c91159bbfa3ef8957aac8"
3677 "4b59b30b455a79c2973480823d8b3863"
3678 "c3deef4a8e243590268d80e18751a0e1"
3679 "30f67ce6a1ace9f79b95e097474febc9"
3680 "81195b1d13a69086c0863f66a7b7fdb4"
3681 "8792227b1ac5e2489febdf087ab54864"
3682 "83033a6f001ca5d1ec1e27f5c30f4cec"
3683 "2642074a39ae68aee552e196627a8e3d"
3684 "867e67a8c01b11e75f13cca0a97ab668"
3685 "b50cda07a8ecb7cd8e3dd7009c963653"
3686 "4f6f239cffe1fc8daa466f78b676c711"
3687 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3688 "99b801597d5220e307eaa5bee507fb94"
3689 "d1fa69f9e519b2de315bac92c36f2ea1"
3690 "fa1df4478c0ddedeae8c70e0233cd098"
3691 "040c" // OCTET STRING length 0x0c (initializationVector)
3692 "d796b02c370f1fa4cc0124f1"
3693 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3694 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3695 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3696 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3697 "3106" // SET length 0x06
3698 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3699 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3700 // } end SET
3701 // } end [1]
3702 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3703 "020120" // INTEGER length 1 value 0x20 (AES)
3704 // } end [2]
3705 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3706 "02020100" // INTEGER length 2 value 0x100
3707 // } end [3]
3708 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3709 "3103" // SET length 0x03 {
3710 "020101" // INTEGER length 1 value 0x01 (ECB)
3711 // } end SET
3712 // } end [4]
3713 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3714 "3103" // SET length 0x03 {
3715 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3716 // } end SET
3717 // } end [5]
3718 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3719 // (noAuthRequired)
3720 "0500" // NULL
3721 // } end [503]
3722 // } end SEQUENCE (AuthorizationList)
3723 // } end SEQUENCE (KeyDescription)
3724 "0420" // OCTET STRING length 0x20 (encryptedKey)
3725 "ccd540855f833a5e1480bfd2d36faf3a"
3726 "eee15df5beabe2691bc82dde2a7aa910"
3727 "0410" // OCTET STRING length 0x10 (tag)
3728 "64c9f689c60ff6223ab6e6999e0eb6e5"
3729 // } SEQUENCE (SecureKeyWrapper)
3730);
Selene Huang31ab4042020-04-29 04:22:39 -07003731
3732auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003733 // IKeyMintDevice.aidl
3734 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3735 "020100" // INTEGER length 1 value 0x00 (version)
3736 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3737 "aad93ed5924f283b4bb5526fbe7a1412"
3738 "f9d9749ec30db9062b29e574a8546f33"
3739 "c88732452f5b8e6a391ee76c39ed1712"
3740 "c61d8df6213dec1cffbc17a8c6d04c7b"
3741 "30893d8daa9b2015213e219468215532"
3742 "07f8f9931c4caba23ed3bee28b36947e"
3743 "47f10e0a5c3dc51c988a628daad3e5e1"
3744 "f4005e79c2d5a96c284b4b8d7e4948f3"
3745 "31e5b85dd5a236f85579f3ea1d1b8484"
3746 "87470bdb0ab4f81a12bee42c99fe0df4"
3747 "bee3759453e69ad1d68a809ce06b949f"
3748 "7694a990429b2fe81e066ff43e56a216"
3749 "02db70757922a4bcc23ab89f1e35da77"
3750 "586775f423e519c2ea394caf48a28d0c"
3751 "8020f1dcf6b3a68ec246f615ae96dae9"
3752 "a079b1f6eb959033c1af5c125fd94168"
3753 "040c" // OCTET STRING length 0x0c (initializationVector)
3754 "6d9721d08589581ab49204a3"
3755 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3756 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3757 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3758 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3759 "3106" // SET length 0x06
3760 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3761 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3762 // } end SET
3763 // } end [1]
3764 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3765 "020120" // INTEGER length 1 value 0x20 (AES)
3766 // } end [2]
3767 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3768 "02020100" // INTEGER length 2 value 0x100
3769 // } end [3]
3770 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3771 "3103" // SET length 0x03 {
3772 "020101" // INTEGER length 1 value 0x01 (ECB)
3773 // } end SET
3774 // } end [4]
3775 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3776 "3103" // SET length 0x03 {
3777 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3778 // } end SET
3779 // } end [5]
3780 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3781 // (noAuthRequired)
3782 "0500" // NULL
3783 // } end [503]
3784 // } end SEQUENCE (AuthorizationList)
3785 // } end SEQUENCE (KeyDescription)
3786 "0420" // OCTET STRING length 0x20 (encryptedKey)
3787 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3788 "c20d1f99a9a024a76f35c8e2cab9b68d"
3789 "0410" // OCTET STRING length 0x10 (tag)
3790 "2560c70109ae67c030f00b98b512a670"
3791 // } SEQUENCE (SecureKeyWrapper)
3792);
Selene Huang31ab4042020-04-29 04:22:39 -07003793
3794auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003795 // RFC 5208 s5
3796 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3797 "020100" // INTEGER length 1 value 0x00 (version)
3798 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3799 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3800 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3801 "0500" // NULL (parameters)
3802 // } SEQUENCE (AlgorithmIdentifier)
3803 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3804 // RFC 8017 A.1.2
3805 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3806 "020100" // INTEGER length 1 value 0x00 (version)
3807 "02820101" // INTEGER length 0x0101 (modulus) value...
3808 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3809 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3810 "7b06e673a837313d56b1c725150a3fef" // 0x30
3811 "86acbddc41bb759c2854eae32d35841e" // 0x40
3812 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3813 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3814 "312d7bd5921ffaea1347c157406fef71" // 0x70
3815 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3816 "f4645c11f5c1374c3886427411c44979" // 0x90
3817 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3818 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3819 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3820 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3821 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3822 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3823 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3824 "55" // 0x101
3825 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3826 "02820100" // INTEGER length 0x100 (privateExponent) value...
3827 "431447b6251908112b1ee76f99f3711a" // 0x10
3828 "52b6630960046c2de70de188d833f8b8" // 0x20
3829 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3830 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3831 "e710b630a03adc683b5d2c43080e52be" // 0x50
3832 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3833 "822bccff087d63c940ba8a45f670feb2" // 0x70
3834 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3835 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3836 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3837 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3838 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3839 "52659d5a5ba05b663737a8696281865b" // 0xd0
3840 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3841 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3842 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3843 "028181" // INTEGER length 0x81 (prime1) value...
3844 "00de392e18d682c829266cc3454e1d61" // 0x10
3845 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3846 "ff841be5bac82a164c5970007047b8c5" // 0x30
3847 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3848 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3849 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3850 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3851 "9e91346130748a6e3c124f9149d71c74" // 0x80
3852 "35"
3853 "028181" // INTEGER length 0x81 (prime2) value...
3854 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3855 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3856 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3857 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3858 "9ed39a2d934c880440aed8832f984316" // 0x50
3859 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3860 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3861 "b880677c068e1be936e81288815252a8" // 0x80
3862 "a1"
3863 "028180" // INTEGER length 0x80 (exponent1) value...
3864 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3865 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3866 "5a063212a4f105a3764743e53281988a" // 0x30
3867 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3868 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3869 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3870 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3871 "4719d6e2b9439823719cd08bcd031781" // 0x80
3872 "028181" // INTEGER length 0x81 (exponent2) value...
3873 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3874 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3875 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3876 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3877 "1254186af30b22c10582a8a43e34fe94" // 0x50
3878 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3879 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3880 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3881 "61"
3882 "028181" // INTEGER length 0x81 (coefficient) value...
3883 "00c931617c77829dfb1270502be9195c" // 0x10
3884 "8f2830885f57dba869536811e6864236" // 0x20
3885 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3886 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3887 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3888 "959356210723287b0affcc9f727044d4" // 0x60
3889 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3890 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3891 "22"
3892 // } SEQUENCE
3893 // } SEQUENCE ()
3894);
Selene Huang31ab4042020-04-29 04:22:39 -07003895
3896string zero_masking_key =
3897 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3898string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3899
3900class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3901
3902TEST_P(ImportWrappedKeyTest, Success) {
3903 auto wrapping_key_desc = AuthorizationSetBuilder()
3904 .RsaEncryptionKey(2048, 65537)
3905 .Digest(Digest::SHA_2_256)
3906 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003907 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3908 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003909
3910 ASSERT_EQ(ErrorCode::OK,
3911 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3912 AuthorizationSetBuilder()
3913 .Digest(Digest::SHA_2_256)
3914 .Padding(PaddingMode::RSA_OAEP)));
3915
3916 string message = "Hello World!";
3917 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3918 string ciphertext = EncryptMessage(message, params);
3919 string plaintext = DecryptMessage(ciphertext, params);
3920 EXPECT_EQ(message, plaintext);
3921}
3922
David Drysdaled2cc8c22021-04-15 13:29:45 +01003923/*
3924 * ImportWrappedKeyTest.SuccessSidsIgnored
3925 *
3926 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3927 * include Tag:USER_SECURE_ID.
3928 */
3929TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3930 auto wrapping_key_desc = AuthorizationSetBuilder()
3931 .RsaEncryptionKey(2048, 65537)
3932 .Digest(Digest::SHA_2_256)
3933 .Padding(PaddingMode::RSA_OAEP)
3934 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3935 .SetDefaultValidity();
3936
3937 int64_t password_sid = 42;
3938 int64_t biometric_sid = 24;
3939 ASSERT_EQ(ErrorCode::OK,
3940 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3941 AuthorizationSetBuilder()
3942 .Digest(Digest::SHA_2_256)
3943 .Padding(PaddingMode::RSA_OAEP),
3944 password_sid, biometric_sid));
3945
3946 string message = "Hello World!";
3947 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3948 string ciphertext = EncryptMessage(message, params);
3949 string plaintext = DecryptMessage(ciphertext, params);
3950 EXPECT_EQ(message, plaintext);
3951}
3952
Selene Huang31ab4042020-04-29 04:22:39 -07003953TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3954 auto wrapping_key_desc = AuthorizationSetBuilder()
3955 .RsaEncryptionKey(2048, 65537)
3956 .Digest(Digest::SHA_2_256)
3957 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003958 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3959 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003960
3961 ASSERT_EQ(ErrorCode::OK,
3962 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3963 AuthorizationSetBuilder()
3964 .Digest(Digest::SHA_2_256)
3965 .Padding(PaddingMode::RSA_OAEP)));
3966}
3967
3968TEST_P(ImportWrappedKeyTest, WrongMask) {
3969 auto wrapping_key_desc = AuthorizationSetBuilder()
3970 .RsaEncryptionKey(2048, 65537)
3971 .Digest(Digest::SHA_2_256)
3972 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003973 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3974 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003975
3976 ASSERT_EQ(
3977 ErrorCode::VERIFICATION_FAILED,
3978 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3979 AuthorizationSetBuilder()
3980 .Digest(Digest::SHA_2_256)
3981 .Padding(PaddingMode::RSA_OAEP)));
3982}
3983
3984TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3985 auto wrapping_key_desc = AuthorizationSetBuilder()
3986 .RsaEncryptionKey(2048, 65537)
3987 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003988 .Padding(PaddingMode::RSA_OAEP)
3989 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003990
3991 ASSERT_EQ(
3992 ErrorCode::INCOMPATIBLE_PURPOSE,
3993 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3994 AuthorizationSetBuilder()
3995 .Digest(Digest::SHA_2_256)
3996 .Padding(PaddingMode::RSA_OAEP)));
3997}
3998
David Drysdaled2cc8c22021-04-15 13:29:45 +01003999TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
4000 auto wrapping_key_desc = AuthorizationSetBuilder()
4001 .RsaEncryptionKey(2048, 65537)
4002 .Digest(Digest::SHA_2_256)
4003 .Padding(PaddingMode::RSA_PSS)
4004 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4005 .SetDefaultValidity();
4006
4007 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
4008 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4009 AuthorizationSetBuilder()
4010 .Digest(Digest::SHA_2_256)
4011 .Padding(PaddingMode::RSA_OAEP)));
4012}
4013
4014TEST_P(ImportWrappedKeyTest, WrongDigest) {
4015 auto wrapping_key_desc = AuthorizationSetBuilder()
4016 .RsaEncryptionKey(2048, 65537)
4017 .Digest(Digest::SHA_2_512)
4018 .Padding(PaddingMode::RSA_OAEP)
4019 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4020 .SetDefaultValidity();
4021
4022 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
4023 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4024 AuthorizationSetBuilder()
4025 .Digest(Digest::SHA_2_256)
4026 .Padding(PaddingMode::RSA_OAEP)));
4027}
4028
Selene Huang31ab4042020-04-29 04:22:39 -07004029INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
4030
4031typedef KeyMintAidlTestBase EncryptionOperationsTest;
4032
4033/*
4034 * EncryptionOperationsTest.RsaNoPaddingSuccess
4035 *
David Drysdale59cae642021-05-12 13:52:03 +01004036 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07004037 */
4038TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01004039 for (uint64_t exponent : {3, 65537}) {
4040 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4041 .Authorization(TAG_NO_AUTH_REQUIRED)
4042 .RsaEncryptionKey(2048, exponent)
4043 .Padding(PaddingMode::NONE)
4044 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004045
David Drysdaled2cc8c22021-04-15 13:29:45 +01004046 string message = string(2048 / 8, 'a');
4047 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004048 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004049 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004050
David Drysdale59cae642021-05-12 13:52:03 +01004051 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004052 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004053
David Drysdaled2cc8c22021-04-15 13:29:45 +01004054 // Unpadded RSA is deterministic
4055 EXPECT_EQ(ciphertext1, ciphertext2);
4056
4057 CheckedDeleteKey();
4058 }
Selene Huang31ab4042020-04-29 04:22:39 -07004059}
4060
4061/*
4062 * EncryptionOperationsTest.RsaNoPaddingShortMessage
4063 *
David Drysdale59cae642021-05-12 13:52:03 +01004064 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07004065 */
4066TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
4067 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4068 .Authorization(TAG_NO_AUTH_REQUIRED)
4069 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004070 .Padding(PaddingMode::NONE)
4071 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004072
4073 string message = "1";
4074 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4075
David Drysdale59cae642021-05-12 13:52:03 +01004076 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004077 EXPECT_EQ(2048U / 8, ciphertext.size());
4078
4079 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
4080 string plaintext = DecryptMessage(ciphertext, params);
4081
4082 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07004083}
4084
4085/*
Selene Huang31ab4042020-04-29 04:22:39 -07004086 * EncryptionOperationsTest.RsaOaepSuccess
4087 *
David Drysdale59cae642021-05-12 13:52:03 +01004088 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07004089 */
4090TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4091 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4092
4093 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01004094 ASSERT_EQ(ErrorCode::OK,
4095 GenerateKey(AuthorizationSetBuilder()
4096 .Authorization(TAG_NO_AUTH_REQUIRED)
4097 .RsaEncryptionKey(key_size, 65537)
4098 .Padding(PaddingMode::RSA_OAEP)
4099 .Digest(digests)
4100 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
4101 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004102
4103 string message = "Hello";
4104
4105 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01004106 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4107
4108 auto params = AuthorizationSetBuilder()
4109 .Digest(digest)
4110 .Padding(PaddingMode::RSA_OAEP)
4111 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
4112 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004113 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4114 EXPECT_EQ(key_size / 8, ciphertext1.size());
4115
David Drysdale59cae642021-05-12 13:52:03 +01004116 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004117 EXPECT_EQ(key_size / 8, ciphertext2.size());
4118
4119 // OAEP randomizes padding so every result should be different (with astronomically high
4120 // probability).
4121 EXPECT_NE(ciphertext1, ciphertext2);
4122
4123 string plaintext1 = DecryptMessage(ciphertext1, params);
4124 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4125 string plaintext2 = DecryptMessage(ciphertext2, params);
4126 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4127
4128 // Decrypting corrupted ciphertext should fail.
4129 size_t offset_to_corrupt = random() % ciphertext1.size();
4130 char corrupt_byte;
4131 do {
4132 corrupt_byte = static_cast<char>(random() % 256);
4133 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4134 ciphertext1[offset_to_corrupt] = corrupt_byte;
4135
4136 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4137 string result;
4138 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4139 EXPECT_EQ(0U, result.size());
4140 }
4141}
4142
4143/*
4144 * EncryptionOperationsTest.RsaOaepInvalidDigest
4145 *
David Drysdale59cae642021-05-12 13:52:03 +01004146 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07004147 * without a digest.
4148 */
4149TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
4150 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4151 .Authorization(TAG_NO_AUTH_REQUIRED)
4152 .RsaEncryptionKey(2048, 65537)
4153 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004154 .Digest(Digest::NONE)
4155 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004156
4157 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004158 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07004159}
4160
4161/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004162 * EncryptionOperationsTest.RsaOaepInvalidPadding
4163 *
David Drysdale59cae642021-05-12 13:52:03 +01004164 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01004165 * with a padding value that is only suitable for signing/verifying.
4166 */
4167TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
4168 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4169 .Authorization(TAG_NO_AUTH_REQUIRED)
4170 .RsaEncryptionKey(2048, 65537)
4171 .Padding(PaddingMode::RSA_PSS)
4172 .Digest(Digest::NONE)
4173 .SetDefaultValidity()));
4174
4175 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004176 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01004177}
4178
4179/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004180 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07004181 *
David Drysdale59cae642021-05-12 13:52:03 +01004182 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004183 * with a different digest than was used to encrypt.
4184 */
4185TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01004186 if (SecLevel() == SecurityLevel::STRONGBOX) {
4187 GTEST_SKIP() << "Test not applicable to StrongBox device";
4188 }
Selene Huang31ab4042020-04-29 04:22:39 -07004189
4190 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4191 .Authorization(TAG_NO_AUTH_REQUIRED)
4192 .RsaEncryptionKey(1024, 65537)
4193 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004194 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
4195 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004196 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01004197 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07004198 message,
4199 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
4200
4201 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4202 .Digest(Digest::SHA_2_256)
4203 .Padding(PaddingMode::RSA_OAEP)));
4204 string result;
4205 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
4206 EXPECT_EQ(0U, result.size());
4207}
4208
4209/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004210 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
4211 *
David Drysdale59cae642021-05-12 13:52:03 +01004212 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004213 * digests.
4214 */
4215TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
4216 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4217
4218 size_t key_size = 2048; // Need largish key for SHA-512 test.
4219 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4220 .OaepMGFDigest(digests)
4221 .Authorization(TAG_NO_AUTH_REQUIRED)
4222 .RsaEncryptionKey(key_size, 65537)
4223 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004224 .Digest(Digest::SHA_2_256)
4225 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004226
4227 string message = "Hello";
4228
4229 for (auto digest : digests) {
4230 auto params = AuthorizationSetBuilder()
4231 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4232 .Digest(Digest::SHA_2_256)
4233 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01004234 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004235 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4236 EXPECT_EQ(key_size / 8, ciphertext1.size());
4237
David Drysdale59cae642021-05-12 13:52:03 +01004238 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004239 EXPECT_EQ(key_size / 8, ciphertext2.size());
4240
4241 // OAEP randomizes padding so every result should be different (with astronomically high
4242 // probability).
4243 EXPECT_NE(ciphertext1, ciphertext2);
4244
4245 string plaintext1 = DecryptMessage(ciphertext1, params);
4246 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4247 string plaintext2 = DecryptMessage(ciphertext2, params);
4248 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4249
4250 // Decrypting corrupted ciphertext should fail.
4251 size_t offset_to_corrupt = random() % ciphertext1.size();
4252 char corrupt_byte;
4253 do {
4254 corrupt_byte = static_cast<char>(random() % 256);
4255 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4256 ciphertext1[offset_to_corrupt] = corrupt_byte;
4257
4258 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4259 string result;
4260 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4261 EXPECT_EQ(0U, result.size());
4262 }
4263}
4264
4265/*
4266 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4267 *
David Drysdale59cae642021-05-12 13:52:03 +01004268 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004269 * with incompatible MGF digest.
4270 */
4271TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4272 ASSERT_EQ(ErrorCode::OK,
4273 GenerateKey(AuthorizationSetBuilder()
4274 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4275 .Authorization(TAG_NO_AUTH_REQUIRED)
4276 .RsaEncryptionKey(2048, 65537)
4277 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004278 .Digest(Digest::SHA_2_256)
4279 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004280 string message = "Hello World!";
4281
4282 auto params = AuthorizationSetBuilder()
4283 .Padding(PaddingMode::RSA_OAEP)
4284 .Digest(Digest::SHA_2_256)
4285 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004286 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004287}
4288
4289/*
4290 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4291 *
4292 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4293 * with unsupported MGF digest.
4294 */
4295TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4296 ASSERT_EQ(ErrorCode::OK,
4297 GenerateKey(AuthorizationSetBuilder()
4298 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4299 .Authorization(TAG_NO_AUTH_REQUIRED)
4300 .RsaEncryptionKey(2048, 65537)
4301 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004302 .Digest(Digest::SHA_2_256)
4303 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004304 string message = "Hello World!";
4305
4306 auto params = AuthorizationSetBuilder()
4307 .Padding(PaddingMode::RSA_OAEP)
4308 .Digest(Digest::SHA_2_256)
4309 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004310 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004311}
4312
4313/*
Selene Huang31ab4042020-04-29 04:22:39 -07004314 * EncryptionOperationsTest.RsaPkcs1Success
4315 *
4316 * Verifies that RSA PKCS encryption/decrypts works.
4317 */
4318TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4319 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4320 .Authorization(TAG_NO_AUTH_REQUIRED)
4321 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004322 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4323 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004324
4325 string message = "Hello World!";
4326 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004327 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004328 EXPECT_EQ(2048U / 8, ciphertext1.size());
4329
David Drysdale59cae642021-05-12 13:52:03 +01004330 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004331 EXPECT_EQ(2048U / 8, ciphertext2.size());
4332
4333 // PKCS1 v1.5 randomizes padding so every result should be different.
4334 EXPECT_NE(ciphertext1, ciphertext2);
4335
4336 string plaintext = DecryptMessage(ciphertext1, params);
4337 EXPECT_EQ(message, plaintext);
4338
4339 // Decrypting corrupted ciphertext should fail.
4340 size_t offset_to_corrupt = random() % ciphertext1.size();
4341 char corrupt_byte;
4342 do {
4343 corrupt_byte = static_cast<char>(random() % 256);
4344 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4345 ciphertext1[offset_to_corrupt] = corrupt_byte;
4346
4347 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4348 string result;
4349 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4350 EXPECT_EQ(0U, result.size());
4351}
4352
4353/*
Selene Huang31ab4042020-04-29 04:22:39 -07004354 * EncryptionOperationsTest.EcdsaEncrypt
4355 *
4356 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4357 */
4358TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4359 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4360 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004361 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004362 .Digest(Digest::NONE)
4363 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004364 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4365 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4366 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4367}
4368
4369/*
4370 * EncryptionOperationsTest.HmacEncrypt
4371 *
4372 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4373 */
4374TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4375 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4376 .Authorization(TAG_NO_AUTH_REQUIRED)
4377 .HmacKey(128)
4378 .Digest(Digest::SHA_2_256)
4379 .Padding(PaddingMode::NONE)
4380 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4381 auto params = AuthorizationSetBuilder()
4382 .Digest(Digest::SHA_2_256)
4383 .Padding(PaddingMode::NONE)
4384 .Authorization(TAG_MAC_LENGTH, 128);
4385 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4386 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4387}
4388
4389/*
4390 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4391 *
4392 * Verifies that AES ECB mode works.
4393 */
4394TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4395 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4396 .Authorization(TAG_NO_AUTH_REQUIRED)
4397 .AesEncryptionKey(128)
4398 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4399 .Padding(PaddingMode::NONE)));
4400
4401 ASSERT_GT(key_blob_.size(), 0U);
4402 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4403
4404 // Two-block message.
4405 string message = "12345678901234567890123456789012";
4406 string ciphertext1 = EncryptMessage(message, params);
4407 EXPECT_EQ(message.size(), ciphertext1.size());
4408
4409 string ciphertext2 = EncryptMessage(string(message), params);
4410 EXPECT_EQ(message.size(), ciphertext2.size());
4411
4412 // ECB is deterministic.
4413 EXPECT_EQ(ciphertext1, ciphertext2);
4414
4415 string plaintext = DecryptMessage(ciphertext1, params);
4416 EXPECT_EQ(message, plaintext);
4417}
4418
4419/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004420 * EncryptionOperationsTest.AesEcbUnknownTag
4421 *
4422 * Verifies that AES ECB operations ignore unknown tags.
4423 */
4424TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4425 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4426 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4427 KeyParameter unknown_param;
4428 unknown_param.tag = unknown_tag;
4429
4430 vector<KeyCharacteristics> key_characteristics;
4431 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4432 .Authorization(TAG_NO_AUTH_REQUIRED)
4433 .AesEncryptionKey(128)
4434 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4435 .Padding(PaddingMode::NONE)
4436 .Authorization(unknown_param),
4437 &key_blob_, &key_characteristics));
4438 ASSERT_GT(key_blob_.size(), 0U);
4439
4440 // Unknown tags should not be returned in key characteristics.
4441 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4442 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4443 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4444 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4445
4446 // Encrypt without mentioning the unknown parameter.
4447 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4448 string message = "12345678901234567890123456789012";
4449 string ciphertext = EncryptMessage(message, params);
4450 EXPECT_EQ(message.size(), ciphertext.size());
4451
4452 // Decrypt including the unknown parameter.
4453 auto decrypt_params = AuthorizationSetBuilder()
4454 .BlockMode(BlockMode::ECB)
4455 .Padding(PaddingMode::NONE)
4456 .Authorization(unknown_param);
4457 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4458 EXPECT_EQ(message, plaintext);
4459}
4460
4461/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004462 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004463 *
4464 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4465 */
4466TEST_P(EncryptionOperationsTest, AesWrongMode) {
4467 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4468 .Authorization(TAG_NO_AUTH_REQUIRED)
4469 .AesEncryptionKey(128)
4470 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4471 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004472 ASSERT_GT(key_blob_.size(), 0U);
4473
Selene Huang31ab4042020-04-29 04:22:39 -07004474 EXPECT_EQ(
4475 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4476 Begin(KeyPurpose::ENCRYPT,
4477 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4478}
4479
4480/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004481 * EncryptionOperationsTest.AesWrongPadding
4482 *
4483 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4484 */
4485TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4486 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4487 .Authorization(TAG_NO_AUTH_REQUIRED)
4488 .AesEncryptionKey(128)
4489 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4490 .Padding(PaddingMode::NONE)));
4491 ASSERT_GT(key_blob_.size(), 0U);
4492
4493 EXPECT_EQ(
4494 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4495 Begin(KeyPurpose::ENCRYPT,
4496 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4497}
4498
4499/*
4500 * EncryptionOperationsTest.AesInvalidParams
4501 *
4502 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4503 */
4504TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4505 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4506 .Authorization(TAG_NO_AUTH_REQUIRED)
4507 .AesEncryptionKey(128)
4508 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4509 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4510 .Padding(PaddingMode::NONE)
4511 .Padding(PaddingMode::PKCS7)));
4512 ASSERT_GT(key_blob_.size(), 0U);
4513
4514 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4515 .BlockMode(BlockMode::CBC)
4516 .BlockMode(BlockMode::ECB)
4517 .Padding(PaddingMode::NONE));
4518 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4519 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4520
4521 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4522 .BlockMode(BlockMode::ECB)
4523 .Padding(PaddingMode::NONE)
4524 .Padding(PaddingMode::PKCS7));
4525 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4526 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4527}
4528
4529/*
Selene Huang31ab4042020-04-29 04:22:39 -07004530 * EncryptionOperationsTest.AesWrongPurpose
4531 *
4532 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4533 * specified.
4534 */
4535TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4536 auto err = GenerateKey(AuthorizationSetBuilder()
4537 .Authorization(TAG_NO_AUTH_REQUIRED)
4538 .AesKey(128)
4539 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4540 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4541 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4542 .Padding(PaddingMode::NONE));
4543 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4544 ASSERT_GT(key_blob_.size(), 0U);
4545
4546 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4547 .BlockMode(BlockMode::GCM)
4548 .Padding(PaddingMode::NONE)
4549 .Authorization(TAG_MAC_LENGTH, 128));
4550 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4551
4552 CheckedDeleteKey();
4553
4554 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4555 .Authorization(TAG_NO_AUTH_REQUIRED)
4556 .AesKey(128)
4557 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4558 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4559 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4560 .Padding(PaddingMode::NONE)));
4561
4562 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4563 .BlockMode(BlockMode::GCM)
4564 .Padding(PaddingMode::NONE)
4565 .Authorization(TAG_MAC_LENGTH, 128));
4566 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4567}
4568
4569/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004570 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004571 *
4572 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4573 * multiple of the block size and no padding is specified.
4574 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004575TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4576 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4577 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4578 .Authorization(TAG_NO_AUTH_REQUIRED)
4579 .AesEncryptionKey(128)
4580 .Authorization(TAG_BLOCK_MODE, blockMode)
4581 .Padding(PaddingMode::NONE)));
4582 // Message is slightly shorter than two blocks.
4583 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004584
David Drysdaled2cc8c22021-04-15 13:29:45 +01004585 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4586 AuthorizationSet out_params;
4587 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4588 string ciphertext;
4589 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4590 EXPECT_EQ(0U, ciphertext.size());
4591
4592 CheckedDeleteKey();
4593 }
Selene Huang31ab4042020-04-29 04:22:39 -07004594}
4595
4596/*
4597 * EncryptionOperationsTest.AesEcbPkcs7Padding
4598 *
4599 * Verifies that AES PKCS7 padding works for any message length.
4600 */
4601TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4602 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4603 .Authorization(TAG_NO_AUTH_REQUIRED)
4604 .AesEncryptionKey(128)
4605 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4606 .Padding(PaddingMode::PKCS7)));
4607
4608 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4609
4610 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08004611 for (size_t i = 0; i <= 48; i++) {
4612 SCOPED_TRACE(testing::Message() << "i = " << i);
4613 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
4614 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07004615 string ciphertext = EncryptMessage(message, params);
4616 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4617 string plaintext = DecryptMessage(ciphertext, params);
4618 EXPECT_EQ(message, plaintext);
4619 }
4620}
4621
4622/*
4623 * EncryptionOperationsTest.AesEcbWrongPadding
4624 *
4625 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4626 * specified.
4627 */
4628TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4629 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4630 .Authorization(TAG_NO_AUTH_REQUIRED)
4631 .AesEncryptionKey(128)
4632 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4633 .Padding(PaddingMode::NONE)));
4634
4635 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4636
4637 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08004638 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07004639 string message(i, 'a');
4640 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4641 }
4642}
4643
4644/*
4645 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4646 *
4647 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4648 */
4649TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4650 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4651 .Authorization(TAG_NO_AUTH_REQUIRED)
4652 .AesEncryptionKey(128)
4653 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4654 .Padding(PaddingMode::PKCS7)));
4655
4656 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4657
4658 string message = "a";
4659 string ciphertext = EncryptMessage(message, params);
4660 EXPECT_EQ(16U, ciphertext.size());
4661 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07004662
Seth Moore7a55ae32021-06-23 14:28:11 -07004663 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
4664 ++ciphertext[ciphertext.size() / 2];
4665
4666 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4667 string plaintext;
4668 ErrorCode error = Finish(message, &plaintext);
4669 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
4670 // This is the expected error, we can exit the test now.
4671 return;
4672 } else {
4673 // Very small chance we got valid decryption, so try again.
4674 ASSERT_EQ(error, ErrorCode::OK);
4675 }
4676 }
4677 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07004678}
4679
4680vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4681 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004682 EXPECT_TRUE(iv);
4683 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004684}
4685
4686/*
4687 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4688 *
4689 * Verifies that AES CTR mode works.
4690 */
4691TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4692 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4693 .Authorization(TAG_NO_AUTH_REQUIRED)
4694 .AesEncryptionKey(128)
4695 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4696 .Padding(PaddingMode::NONE)));
4697
4698 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4699
4700 string message = "123";
4701 AuthorizationSet out_params;
4702 string ciphertext1 = EncryptMessage(message, params, &out_params);
4703 vector<uint8_t> iv1 = CopyIv(out_params);
4704 EXPECT_EQ(16U, iv1.size());
4705
4706 EXPECT_EQ(message.size(), ciphertext1.size());
4707
4708 out_params.Clear();
4709 string ciphertext2 = EncryptMessage(message, params, &out_params);
4710 vector<uint8_t> iv2 = CopyIv(out_params);
4711 EXPECT_EQ(16U, iv2.size());
4712
4713 // IVs should be random, so ciphertexts should differ.
4714 EXPECT_NE(ciphertext1, ciphertext2);
4715
4716 auto params_iv1 =
4717 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4718 auto params_iv2 =
4719 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4720
4721 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4722 EXPECT_EQ(message, plaintext);
4723 plaintext = DecryptMessage(ciphertext2, params_iv2);
4724 EXPECT_EQ(message, plaintext);
4725
4726 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4727 plaintext = DecryptMessage(ciphertext1, params_iv2);
4728 EXPECT_NE(message, plaintext);
4729 plaintext = DecryptMessage(ciphertext2, params_iv1);
4730 EXPECT_NE(message, plaintext);
4731}
4732
4733/*
4734 * EncryptionOperationsTest.AesIncremental
4735 *
4736 * Verifies that AES works, all modes, when provided data in various size increments.
4737 */
4738TEST_P(EncryptionOperationsTest, AesIncremental) {
4739 auto block_modes = {
4740 BlockMode::ECB,
4741 BlockMode::CBC,
4742 BlockMode::CTR,
4743 BlockMode::GCM,
4744 };
4745
4746 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4747 .Authorization(TAG_NO_AUTH_REQUIRED)
4748 .AesEncryptionKey(128)
4749 .BlockMode(block_modes)
4750 .Padding(PaddingMode::NONE)
4751 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4752
4753 for (int increment = 1; increment <= 240; ++increment) {
4754 for (auto block_mode : block_modes) {
4755 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004756 auto params =
4757 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4758 if (block_mode == BlockMode::GCM) {
4759 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4760 }
Selene Huang31ab4042020-04-29 04:22:39 -07004761
4762 AuthorizationSet output_params;
4763 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4764
4765 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004766 string to_send;
4767 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004768 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004769 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004770 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4771 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004772
4773 switch (block_mode) {
4774 case BlockMode::GCM:
4775 EXPECT_EQ(message.size() + 16, ciphertext.size());
4776 break;
4777 case BlockMode::CTR:
4778 EXPECT_EQ(message.size(), ciphertext.size());
4779 break;
4780 case BlockMode::CBC:
4781 case BlockMode::ECB:
4782 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4783 break;
4784 }
4785
4786 auto iv = output_params.GetTagValue(TAG_NONCE);
4787 switch (block_mode) {
4788 case BlockMode::CBC:
4789 case BlockMode::GCM:
4790 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004791 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4792 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4793 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004794 break;
4795
4796 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004797 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004798 break;
4799 }
4800
4801 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4802 << "Decrypt begin() failed for block mode " << block_mode;
4803
4804 string plaintext;
4805 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004806 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004807 }
4808 ErrorCode error = Finish(to_send, &plaintext);
4809 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4810 << " and increment " << increment;
4811 if (error == ErrorCode::OK) {
4812 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4813 << block_mode << " and increment " << increment;
4814 }
4815 }
4816 }
4817}
4818
4819struct AesCtrSp80038aTestVector {
4820 const char* key;
4821 const char* nonce;
4822 const char* plaintext;
4823 const char* ciphertext;
4824};
4825
4826// These test vectors are taken from
4827// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4828static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4829 // AES-128
4830 {
4831 "2b7e151628aed2a6abf7158809cf4f3c",
4832 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4833 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4834 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4835 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4836 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4837 },
4838 // AES-192
4839 {
4840 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4841 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4842 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4843 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4844 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4845 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4846 },
4847 // AES-256
4848 {
4849 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4850 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4851 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4852 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4853 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4854 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4855 },
4856};
4857
4858/*
4859 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4860 *
4861 * Verifies AES CTR implementation against SP800-38A test vectors.
4862 */
4863TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4864 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4865 for (size_t i = 0; i < 3; i++) {
4866 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4867 const string key = hex2str(test.key);
4868 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4869 InvalidSizes.end())
4870 continue;
4871 const string nonce = hex2str(test.nonce);
4872 const string plaintext = hex2str(test.plaintext);
4873 const string ciphertext = hex2str(test.ciphertext);
4874 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4875 }
4876}
4877
4878/*
4879 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4880 *
4881 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4882 */
4883TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4884 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4885 .Authorization(TAG_NO_AUTH_REQUIRED)
4886 .AesEncryptionKey(128)
4887 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4888 .Padding(PaddingMode::PKCS7)));
4889 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4890 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4891}
4892
4893/*
4894 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4895 *
4896 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4897 */
4898TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4899 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4900 .Authorization(TAG_NO_AUTH_REQUIRED)
4901 .AesEncryptionKey(128)
4902 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4903 .Authorization(TAG_CALLER_NONCE)
4904 .Padding(PaddingMode::NONE)));
4905
4906 auto params = AuthorizationSetBuilder()
4907 .BlockMode(BlockMode::CTR)
4908 .Padding(PaddingMode::NONE)
4909 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4910 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4911
4912 params = AuthorizationSetBuilder()
4913 .BlockMode(BlockMode::CTR)
4914 .Padding(PaddingMode::NONE)
4915 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4916 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4917
4918 params = AuthorizationSetBuilder()
4919 .BlockMode(BlockMode::CTR)
4920 .Padding(PaddingMode::NONE)
4921 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4922 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4923}
4924
4925/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004926 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004927 *
4928 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4929 */
4930TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4931 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4932 .Authorization(TAG_NO_AUTH_REQUIRED)
4933 .AesEncryptionKey(128)
4934 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4935 .Padding(PaddingMode::NONE)));
4936 // Two-block message.
4937 string message = "12345678901234567890123456789012";
4938 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4939 AuthorizationSet out_params;
4940 string ciphertext1 = EncryptMessage(message, params, &out_params);
4941 vector<uint8_t> iv1 = CopyIv(out_params);
4942 EXPECT_EQ(message.size(), ciphertext1.size());
4943
4944 out_params.Clear();
4945
4946 string ciphertext2 = EncryptMessage(message, params, &out_params);
4947 vector<uint8_t> iv2 = CopyIv(out_params);
4948 EXPECT_EQ(message.size(), ciphertext2.size());
4949
4950 // IVs should be random, so ciphertexts should differ.
4951 EXPECT_NE(ciphertext1, ciphertext2);
4952
4953 params.push_back(TAG_NONCE, iv1);
4954 string plaintext = DecryptMessage(ciphertext1, params);
4955 EXPECT_EQ(message, plaintext);
4956}
4957
4958/*
4959 * EncryptionOperationsTest.AesCallerNonce
4960 *
4961 * Verifies that AES caller-provided nonces work correctly.
4962 */
4963TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4964 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4965 .Authorization(TAG_NO_AUTH_REQUIRED)
4966 .AesEncryptionKey(128)
4967 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4968 .Authorization(TAG_CALLER_NONCE)
4969 .Padding(PaddingMode::NONE)));
4970
4971 string message = "12345678901234567890123456789012";
4972
4973 // Don't specify nonce, should get a random one.
4974 AuthorizationSetBuilder params =
4975 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4976 AuthorizationSet out_params;
4977 string ciphertext = EncryptMessage(message, params, &out_params);
4978 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004979 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004980
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004981 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004982 string plaintext = DecryptMessage(ciphertext, params);
4983 EXPECT_EQ(message, plaintext);
4984
4985 // Now specify a nonce, should also work.
4986 params = AuthorizationSetBuilder()
4987 .BlockMode(BlockMode::CBC)
4988 .Padding(PaddingMode::NONE)
4989 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4990 out_params.Clear();
4991 ciphertext = EncryptMessage(message, params, &out_params);
4992
4993 // Decrypt with correct nonce.
4994 plaintext = DecryptMessage(ciphertext, params);
4995 EXPECT_EQ(message, plaintext);
4996
4997 // Try with wrong nonce.
4998 params = AuthorizationSetBuilder()
4999 .BlockMode(BlockMode::CBC)
5000 .Padding(PaddingMode::NONE)
5001 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
5002 plaintext = DecryptMessage(ciphertext, params);
5003 EXPECT_NE(message, plaintext);
5004}
5005
5006/*
5007 * EncryptionOperationsTest.AesCallerNonceProhibited
5008 *
5009 * Verifies that caller-provided nonces are not permitted when not specified in the key
5010 * authorizations.
5011 */
5012TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
5013 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5014 .Authorization(TAG_NO_AUTH_REQUIRED)
5015 .AesEncryptionKey(128)
5016 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5017 .Padding(PaddingMode::NONE)));
5018
5019 string message = "12345678901234567890123456789012";
5020
5021 // Don't specify nonce, should get a random one.
5022 AuthorizationSetBuilder params =
5023 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5024 AuthorizationSet out_params;
5025 string ciphertext = EncryptMessage(message, params, &out_params);
5026 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005027 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005028
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005029 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005030 string plaintext = DecryptMessage(ciphertext, params);
5031 EXPECT_EQ(message, plaintext);
5032
5033 // Now specify a nonce, should fail
5034 params = AuthorizationSetBuilder()
5035 .BlockMode(BlockMode::CBC)
5036 .Padding(PaddingMode::NONE)
5037 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5038 out_params.Clear();
5039 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5040}
5041
5042/*
5043 * EncryptionOperationsTest.AesGcmRoundTripSuccess
5044 *
5045 * Verifies that AES GCM mode works.
5046 */
5047TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
5048 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5049 .Authorization(TAG_NO_AUTH_REQUIRED)
5050 .AesEncryptionKey(128)
5051 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5052 .Padding(PaddingMode::NONE)
5053 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5054
5055 string aad = "foobar";
5056 string message = "123456789012345678901234567890123456";
5057
5058 auto begin_params = AuthorizationSetBuilder()
5059 .BlockMode(BlockMode::GCM)
5060 .Padding(PaddingMode::NONE)
5061 .Authorization(TAG_MAC_LENGTH, 128);
5062
Selene Huang31ab4042020-04-29 04:22:39 -07005063 // Encrypt
5064 AuthorizationSet begin_out_params;
5065 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5066 << "Begin encrypt";
5067 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005068 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5069 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005070 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5071
5072 // Grab nonce
5073 begin_params.push_back(begin_out_params);
5074
5075 // Decrypt.
5076 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07005077 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005078 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005079 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005080 EXPECT_EQ(message.length(), plaintext.length());
5081 EXPECT_EQ(message, plaintext);
5082}
5083
5084/*
5085 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
5086 *
5087 * Verifies that AES GCM mode works, even when there's a long delay
5088 * between operations.
5089 */
5090TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
5091 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5092 .Authorization(TAG_NO_AUTH_REQUIRED)
5093 .AesEncryptionKey(128)
5094 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5095 .Padding(PaddingMode::NONE)
5096 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5097
5098 string aad = "foobar";
5099 string message = "123456789012345678901234567890123456";
5100
5101 auto begin_params = AuthorizationSetBuilder()
5102 .BlockMode(BlockMode::GCM)
5103 .Padding(PaddingMode::NONE)
5104 .Authorization(TAG_MAC_LENGTH, 128);
5105
Selene Huang31ab4042020-04-29 04:22:39 -07005106 // Encrypt
5107 AuthorizationSet begin_out_params;
5108 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5109 << "Begin encrypt";
5110 string ciphertext;
5111 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005112 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005113 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005114 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005115
5116 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5117
5118 // Grab nonce
5119 begin_params.push_back(begin_out_params);
5120
5121 // Decrypt.
5122 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5123 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005124 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005125 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005126 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005127 sleep(5);
5128 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5129 EXPECT_EQ(message.length(), plaintext.length());
5130 EXPECT_EQ(message, plaintext);
5131}
5132
5133/*
5134 * EncryptionOperationsTest.AesGcmDifferentNonces
5135 *
5136 * Verifies that encrypting the same data with different nonces produces different outputs.
5137 */
5138TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
5139 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5140 .Authorization(TAG_NO_AUTH_REQUIRED)
5141 .AesEncryptionKey(128)
5142 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5143 .Padding(PaddingMode::NONE)
5144 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5145 .Authorization(TAG_CALLER_NONCE)));
5146
5147 string aad = "foobar";
5148 string message = "123456789012345678901234567890123456";
5149 string nonce1 = "000000000000";
5150 string nonce2 = "111111111111";
5151 string nonce3 = "222222222222";
5152
5153 string ciphertext1 =
5154 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
5155 string ciphertext2 =
5156 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
5157 string ciphertext3 =
5158 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
5159
5160 ASSERT_NE(ciphertext1, ciphertext2);
5161 ASSERT_NE(ciphertext1, ciphertext3);
5162 ASSERT_NE(ciphertext2, ciphertext3);
5163}
5164
5165/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005166 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
5167 *
5168 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
5169 */
5170TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
5171 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5172 .Authorization(TAG_NO_AUTH_REQUIRED)
5173 .AesEncryptionKey(128)
5174 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5175 .Padding(PaddingMode::NONE)
5176 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5177
5178 string aad = "foobar";
5179 string message = "123456789012345678901234567890123456";
5180
5181 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5182 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5183 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5184
5185 ASSERT_NE(ciphertext1, ciphertext2);
5186 ASSERT_NE(ciphertext1, ciphertext3);
5187 ASSERT_NE(ciphertext2, ciphertext3);
5188}
5189
5190/*
Selene Huang31ab4042020-04-29 04:22:39 -07005191 * EncryptionOperationsTest.AesGcmTooShortTag
5192 *
5193 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
5194 */
5195TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
5196 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5197 .Authorization(TAG_NO_AUTH_REQUIRED)
5198 .AesEncryptionKey(128)
5199 .BlockMode(BlockMode::GCM)
5200 .Padding(PaddingMode::NONE)
5201 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5202 string message = "123456789012345678901234567890123456";
5203 auto params = AuthorizationSetBuilder()
5204 .BlockMode(BlockMode::GCM)
5205 .Padding(PaddingMode::NONE)
5206 .Authorization(TAG_MAC_LENGTH, 96);
5207
5208 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
5209}
5210
5211/*
5212 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
5213 *
5214 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
5215 */
5216TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
5217 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5218 .Authorization(TAG_NO_AUTH_REQUIRED)
5219 .AesEncryptionKey(128)
5220 .BlockMode(BlockMode::GCM)
5221 .Padding(PaddingMode::NONE)
5222 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5223 string aad = "foobar";
5224 string message = "123456789012345678901234567890123456";
5225 auto params = AuthorizationSetBuilder()
5226 .BlockMode(BlockMode::GCM)
5227 .Padding(PaddingMode::NONE)
5228 .Authorization(TAG_MAC_LENGTH, 128);
5229
Selene Huang31ab4042020-04-29 04:22:39 -07005230 // Encrypt
5231 AuthorizationSet begin_out_params;
5232 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5233 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005234 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005235
5236 AuthorizationSet finish_out_params;
5237 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005238 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5239 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005240
5241 params = AuthorizationSetBuilder()
5242 .Authorizations(begin_out_params)
5243 .BlockMode(BlockMode::GCM)
5244 .Padding(PaddingMode::NONE)
5245 .Authorization(TAG_MAC_LENGTH, 96);
5246
5247 // Decrypt.
5248 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5249}
5250
5251/*
5252 * EncryptionOperationsTest.AesGcmCorruptKey
5253 *
5254 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5255 */
5256TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5257 const uint8_t nonce_bytes[] = {
5258 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5259 };
5260 string nonce = make_string(nonce_bytes);
5261 const uint8_t ciphertext_bytes[] = {
5262 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5263 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5264 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5265 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5266 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5267 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5268 };
5269 string ciphertext = make_string(ciphertext_bytes);
5270
5271 auto params = AuthorizationSetBuilder()
5272 .BlockMode(BlockMode::GCM)
5273 .Padding(PaddingMode::NONE)
5274 .Authorization(TAG_MAC_LENGTH, 128)
5275 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5276
5277 auto import_params = AuthorizationSetBuilder()
5278 .Authorization(TAG_NO_AUTH_REQUIRED)
5279 .AesEncryptionKey(128)
5280 .BlockMode(BlockMode::GCM)
5281 .Padding(PaddingMode::NONE)
5282 .Authorization(TAG_CALLER_NONCE)
5283 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5284
5285 // Import correct key and decrypt
5286 const uint8_t key_bytes[] = {
5287 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5288 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5289 };
5290 string key = make_string(key_bytes);
5291 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5292 string plaintext = DecryptMessage(ciphertext, params);
5293 CheckedDeleteKey();
5294
5295 // Corrupt key and attempt to decrypt
5296 key[0] = 0;
5297 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5298 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5299 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5300 CheckedDeleteKey();
5301}
5302
5303/*
5304 * EncryptionOperationsTest.AesGcmAadNoData
5305 *
5306 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5307 * encrypt.
5308 */
5309TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5310 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5311 .Authorization(TAG_NO_AUTH_REQUIRED)
5312 .AesEncryptionKey(128)
5313 .BlockMode(BlockMode::GCM)
5314 .Padding(PaddingMode::NONE)
5315 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5316
5317 string aad = "1234567890123456";
5318 auto params = AuthorizationSetBuilder()
5319 .BlockMode(BlockMode::GCM)
5320 .Padding(PaddingMode::NONE)
5321 .Authorization(TAG_MAC_LENGTH, 128);
5322
Selene Huang31ab4042020-04-29 04:22:39 -07005323 // Encrypt
5324 AuthorizationSet begin_out_params;
5325 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5326 string ciphertext;
5327 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005328 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5329 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005330 EXPECT_TRUE(finish_out_params.empty());
5331
5332 // Grab nonce
5333 params.push_back(begin_out_params);
5334
5335 // Decrypt.
5336 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005337 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005338 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005339 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005340
5341 EXPECT_TRUE(finish_out_params.empty());
5342
5343 EXPECT_EQ("", plaintext);
5344}
5345
5346/*
5347 * EncryptionOperationsTest.AesGcmMultiPartAad
5348 *
5349 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5350 * chunks.
5351 */
5352TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5353 const size_t tag_bits = 128;
5354 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5355 .Authorization(TAG_NO_AUTH_REQUIRED)
5356 .AesEncryptionKey(128)
5357 .BlockMode(BlockMode::GCM)
5358 .Padding(PaddingMode::NONE)
5359 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5360
5361 string message = "123456789012345678901234567890123456";
5362 auto begin_params = AuthorizationSetBuilder()
5363 .BlockMode(BlockMode::GCM)
5364 .Padding(PaddingMode::NONE)
5365 .Authorization(TAG_MAC_LENGTH, tag_bits);
5366 AuthorizationSet begin_out_params;
5367
Selene Huang31ab4042020-04-29 04:22:39 -07005368 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5369
5370 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005371 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5372 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005373 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005374 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5375 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005376
Selene Huang31ab4042020-04-29 04:22:39 -07005377 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005378 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005379
5380 // Grab nonce.
5381 begin_params.push_back(begin_out_params);
5382
5383 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005384 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005385 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005386 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005387 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005388 EXPECT_EQ(message, plaintext);
5389}
5390
5391/*
5392 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5393 *
5394 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5395 */
5396TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5397 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5398 .Authorization(TAG_NO_AUTH_REQUIRED)
5399 .AesEncryptionKey(128)
5400 .BlockMode(BlockMode::GCM)
5401 .Padding(PaddingMode::NONE)
5402 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5403
5404 string message = "123456789012345678901234567890123456";
5405 auto begin_params = AuthorizationSetBuilder()
5406 .BlockMode(BlockMode::GCM)
5407 .Padding(PaddingMode::NONE)
5408 .Authorization(TAG_MAC_LENGTH, 128);
5409 AuthorizationSet begin_out_params;
5410
Selene Huang31ab4042020-04-29 04:22:39 -07005411 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5412
Shawn Willden92d79c02021-02-19 07:31:55 -07005413 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005414 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005415 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5416 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005417
David Drysdaled2cc8c22021-04-15 13:29:45 +01005418 // The failure should have already cancelled the operation.
5419 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5420
Shawn Willden92d79c02021-02-19 07:31:55 -07005421 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005422}
5423
5424/*
5425 * EncryptionOperationsTest.AesGcmBadAad
5426 *
5427 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5428 */
5429TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5430 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5431 .Authorization(TAG_NO_AUTH_REQUIRED)
5432 .AesEncryptionKey(128)
5433 .BlockMode(BlockMode::GCM)
5434 .Padding(PaddingMode::NONE)
5435 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5436
5437 string message = "12345678901234567890123456789012";
5438 auto begin_params = AuthorizationSetBuilder()
5439 .BlockMode(BlockMode::GCM)
5440 .Padding(PaddingMode::NONE)
5441 .Authorization(TAG_MAC_LENGTH, 128);
5442
Selene Huang31ab4042020-04-29 04:22:39 -07005443 // Encrypt
5444 AuthorizationSet begin_out_params;
5445 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005446 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005447 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005448 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005449
5450 // Grab nonce
5451 begin_params.push_back(begin_out_params);
5452
Selene Huang31ab4042020-04-29 04:22:39 -07005453 // Decrypt.
5454 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005455 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005456 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005457 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005458}
5459
5460/*
5461 * EncryptionOperationsTest.AesGcmWrongNonce
5462 *
5463 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5464 */
5465TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5466 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5467 .Authorization(TAG_NO_AUTH_REQUIRED)
5468 .AesEncryptionKey(128)
5469 .BlockMode(BlockMode::GCM)
5470 .Padding(PaddingMode::NONE)
5471 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5472
5473 string message = "12345678901234567890123456789012";
5474 auto begin_params = AuthorizationSetBuilder()
5475 .BlockMode(BlockMode::GCM)
5476 .Padding(PaddingMode::NONE)
5477 .Authorization(TAG_MAC_LENGTH, 128);
5478
Selene Huang31ab4042020-04-29 04:22:39 -07005479 // Encrypt
5480 AuthorizationSet begin_out_params;
5481 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005482 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005483 string ciphertext;
5484 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005485 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005486
5487 // Wrong nonce
5488 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5489
5490 // Decrypt.
5491 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005492 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005493 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005494 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005495
5496 // With wrong nonce, should have gotten garbage plaintext (or none).
5497 EXPECT_NE(message, plaintext);
5498}
5499
5500/*
5501 * EncryptionOperationsTest.AesGcmCorruptTag
5502 *
5503 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5504 */
5505TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5506 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5507 .Authorization(TAG_NO_AUTH_REQUIRED)
5508 .AesEncryptionKey(128)
5509 .BlockMode(BlockMode::GCM)
5510 .Padding(PaddingMode::NONE)
5511 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5512
5513 string aad = "1234567890123456";
5514 string message = "123456789012345678901234567890123456";
5515
5516 auto params = AuthorizationSetBuilder()
5517 .BlockMode(BlockMode::GCM)
5518 .Padding(PaddingMode::NONE)
5519 .Authorization(TAG_MAC_LENGTH, 128);
5520
Selene Huang31ab4042020-04-29 04:22:39 -07005521 // Encrypt
5522 AuthorizationSet begin_out_params;
5523 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005524 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005525 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005526 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005527
5528 // Corrupt tag
5529 ++(*ciphertext.rbegin());
5530
5531 // Grab nonce
5532 params.push_back(begin_out_params);
5533
5534 // Decrypt.
5535 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005536 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005537 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005538 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005539}
5540
5541/*
5542 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5543 *
5544 * Verifies that 3DES is basically functional.
5545 */
5546TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5547 auto auths = AuthorizationSetBuilder()
5548 .TripleDesEncryptionKey(168)
5549 .BlockMode(BlockMode::ECB)
5550 .Authorization(TAG_NO_AUTH_REQUIRED)
5551 .Padding(PaddingMode::NONE);
5552
5553 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5554 // Two-block message.
5555 string message = "1234567890123456";
5556 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5557 string ciphertext1 = EncryptMessage(message, inParams);
5558 EXPECT_EQ(message.size(), ciphertext1.size());
5559
5560 string ciphertext2 = EncryptMessage(string(message), inParams);
5561 EXPECT_EQ(message.size(), ciphertext2.size());
5562
5563 // ECB is deterministic.
5564 EXPECT_EQ(ciphertext1, ciphertext2);
5565
5566 string plaintext = DecryptMessage(ciphertext1, inParams);
5567 EXPECT_EQ(message, plaintext);
5568}
5569
5570/*
5571 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5572 *
5573 * Verifies that CBC keys reject ECB usage.
5574 */
5575TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5576 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5577 .TripleDesEncryptionKey(168)
5578 .BlockMode(BlockMode::CBC)
5579 .Authorization(TAG_NO_AUTH_REQUIRED)
5580 .Padding(PaddingMode::NONE)));
5581
5582 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5583 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5584}
5585
5586/*
5587 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5588 *
5589 * Tests ECB mode with PKCS#7 padding, various message sizes.
5590 */
5591TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5592 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5593 .TripleDesEncryptionKey(168)
5594 .BlockMode(BlockMode::ECB)
5595 .Authorization(TAG_NO_AUTH_REQUIRED)
5596 .Padding(PaddingMode::PKCS7)));
5597
5598 for (size_t i = 0; i < 32; ++i) {
5599 string message(i, 'a');
5600 auto inParams =
5601 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5602 string ciphertext = EncryptMessage(message, inParams);
5603 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5604 string plaintext = DecryptMessage(ciphertext, inParams);
5605 EXPECT_EQ(message, plaintext);
5606 }
5607}
5608
5609/*
5610 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5611 *
5612 * Verifies that keys configured for no padding reject PKCS7 padding
5613 */
5614TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5615 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5616 .TripleDesEncryptionKey(168)
5617 .BlockMode(BlockMode::ECB)
5618 .Authorization(TAG_NO_AUTH_REQUIRED)
5619 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005620 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5621 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005622}
5623
5624/*
5625 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5626 *
5627 * Verifies that corrupted padding is detected.
5628 */
5629TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5630 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5631 .TripleDesEncryptionKey(168)
5632 .BlockMode(BlockMode::ECB)
5633 .Authorization(TAG_NO_AUTH_REQUIRED)
5634 .Padding(PaddingMode::PKCS7)));
5635
5636 string message = "a";
5637 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5638 EXPECT_EQ(8U, ciphertext.size());
5639 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005640
5641 AuthorizationSetBuilder begin_params;
5642 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5643 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07005644
5645 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5646 ++ciphertext[ciphertext.size() / 2];
5647
5648 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5649 string plaintext;
5650 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5651 ErrorCode error = Finish(&plaintext);
5652 if (error == ErrorCode::INVALID_ARGUMENT) {
5653 // This is the expected error, we can exit the test now.
5654 return;
5655 } else {
5656 // Very small chance we got valid decryption, so try again.
5657 ASSERT_EQ(error, ErrorCode::OK);
5658 }
5659 }
5660 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005661}
5662
5663struct TripleDesTestVector {
5664 const char* name;
5665 const KeyPurpose purpose;
5666 const BlockMode block_mode;
5667 const PaddingMode padding_mode;
5668 const char* key;
5669 const char* iv;
5670 const char* input;
5671 const char* output;
5672};
5673
5674// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5675// of the NIST vectors are multiples of the block size.
5676static const TripleDesTestVector kTripleDesTestVectors[] = {
5677 {
5678 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5679 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5680 "", // IV
5681 "329d86bdf1bc5af4", // input
5682 "d946c2756d78633f", // output
5683 },
5684 {
5685 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5686 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5687 "", // IV
5688 "6b1540781b01ce1997adae102dbf3c5b", // input
5689 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5690 },
5691 {
5692 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5693 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5694 "", // IV
5695 "6daad94ce08acfe7", // input
5696 "660e7d32dcc90e79", // output
5697 },
5698 {
5699 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5700 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5701 "", // IV
5702 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5703 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5704 },
5705 {
5706 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5707 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5708 "43f791134c5647ba", // IV
5709 "dcc153cef81d6f24", // input
5710 "92538bd8af18d3ba", // output
5711 },
5712 {
5713 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5714 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5715 "c2e999cb6249023c", // IV
5716 "c689aee38a301bb316da75db36f110b5", // input
5717 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5718 },
5719 {
5720 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5721 PaddingMode::PKCS7,
5722 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5723 "c2e999cb6249023c", // IV
5724 "c689aee38a301bb316da75db36f110b500", // input
5725 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5726 },
5727 {
5728 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5729 PaddingMode::PKCS7,
5730 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5731 "c2e999cb6249023c", // IV
5732 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5733 "c689aee38a301bb316da75db36f110b500", // output
5734 },
5735 {
5736 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5737 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5738 "41746c7e442d3681", // IV
5739 "c53a7b0ec40600fe", // input
5740 "d4f00eb455de1034", // output
5741 },
5742 {
5743 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5744 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5745 "3982bc02c3727d45", // IV
5746 "6006f10adef52991fcc777a1238bbb65", // input
5747 "edae09288e9e3bc05746d872b48e3b29", // output
5748 },
5749};
5750
5751/*
5752 * EncryptionOperationsTest.TripleDesTestVector
5753 *
5754 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5755 */
5756TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5757 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5758 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5759 SCOPED_TRACE(test->name);
5760 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5761 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5762 hex2str(test->output));
5763 }
5764}
5765
5766/*
5767 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5768 *
5769 * Validates CBC mode functionality.
5770 */
5771TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5772 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5773 .TripleDesEncryptionKey(168)
5774 .BlockMode(BlockMode::CBC)
5775 .Authorization(TAG_NO_AUTH_REQUIRED)
5776 .Padding(PaddingMode::NONE)));
5777
5778 ASSERT_GT(key_blob_.size(), 0U);
5779
Brian J Murray734c8412022-01-13 14:55:30 -08005780 // Four-block message.
5781 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07005782 vector<uint8_t> iv1;
5783 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5784 EXPECT_EQ(message.size(), ciphertext1.size());
5785
5786 vector<uint8_t> iv2;
5787 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5788 EXPECT_EQ(message.size(), ciphertext2.size());
5789
5790 // IVs should be random, so ciphertexts should differ.
5791 EXPECT_NE(iv1, iv2);
5792 EXPECT_NE(ciphertext1, ciphertext2);
5793
5794 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5795 EXPECT_EQ(message, plaintext);
5796}
5797
5798/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005799 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5800 *
5801 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5802 */
5803TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5804 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5805 .TripleDesEncryptionKey(168)
5806 .BlockMode(BlockMode::CBC)
5807 .Authorization(TAG_NO_AUTH_REQUIRED)
5808 .Authorization(TAG_CALLER_NONCE)
5809 .Padding(PaddingMode::NONE)));
5810 auto params = AuthorizationSetBuilder()
5811 .BlockMode(BlockMode::CBC)
5812 .Padding(PaddingMode::NONE)
5813 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5814 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5815}
5816
5817/*
Selene Huang31ab4042020-04-29 04:22:39 -07005818 * EncryptionOperationsTest.TripleDesCallerIv
5819 *
5820 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5821 */
5822TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5823 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5824 .TripleDesEncryptionKey(168)
5825 .BlockMode(BlockMode::CBC)
5826 .Authorization(TAG_NO_AUTH_REQUIRED)
5827 .Authorization(TAG_CALLER_NONCE)
5828 .Padding(PaddingMode::NONE)));
5829 string message = "1234567890123456";
5830 vector<uint8_t> iv;
5831 // Don't specify IV, should get a random one.
5832 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5833 EXPECT_EQ(message.size(), ciphertext1.size());
5834 EXPECT_EQ(8U, iv.size());
5835
5836 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5837 EXPECT_EQ(message, plaintext);
5838
5839 // Now specify an IV, should also work.
5840 iv = AidlBuf("abcdefgh");
5841 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5842
5843 // Decrypt with correct IV.
5844 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5845 EXPECT_EQ(message, plaintext);
5846
5847 // Now try with wrong IV.
5848 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5849 EXPECT_NE(message, plaintext);
5850}
5851
5852/*
5853 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5854 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005855 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005856 */
5857TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5858 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5859 .TripleDesEncryptionKey(168)
5860 .BlockMode(BlockMode::CBC)
5861 .Authorization(TAG_NO_AUTH_REQUIRED)
5862 .Padding(PaddingMode::NONE)));
5863
5864 string message = "12345678901234567890123456789012";
5865 vector<uint8_t> iv;
5866 // Don't specify nonce, should get a random one.
5867 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5868 EXPECT_EQ(message.size(), ciphertext1.size());
5869 EXPECT_EQ(8U, iv.size());
5870
5871 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5872 EXPECT_EQ(message, plaintext);
5873
5874 // Now specify a nonce, should fail.
5875 auto input_params = AuthorizationSetBuilder()
5876 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5877 .BlockMode(BlockMode::CBC)
5878 .Padding(PaddingMode::NONE);
5879 AuthorizationSet output_params;
5880 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5881 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5882}
5883
5884/*
5885 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5886 *
5887 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5888 */
5889TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5890 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5891 .TripleDesEncryptionKey(168)
5892 .BlockMode(BlockMode::ECB)
5893 .Authorization(TAG_NO_AUTH_REQUIRED)
5894 .Padding(PaddingMode::NONE)));
5895 // Two-block message.
5896 string message = "1234567890123456";
5897 auto begin_params =
5898 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5899 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5900}
5901
5902/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005903 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005904 *
5905 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5906 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005907TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5908 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5909 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5910 .TripleDesEncryptionKey(168)
5911 .BlockMode(blockMode)
5912 .Authorization(TAG_NO_AUTH_REQUIRED)
5913 .Padding(PaddingMode::NONE)));
5914 // Message is slightly shorter than two blocks.
5915 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005916
David Drysdaled2cc8c22021-04-15 13:29:45 +01005917 auto begin_params =
5918 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5919 AuthorizationSet output_params;
5920 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5921 string ciphertext;
5922 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5923
5924 CheckedDeleteKey();
5925 }
Selene Huang31ab4042020-04-29 04:22:39 -07005926}
5927
5928/*
5929 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5930 *
5931 * Verifies that PKCS7 padding works correctly in CBC mode.
5932 */
5933TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5934 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5935 .TripleDesEncryptionKey(168)
5936 .BlockMode(BlockMode::CBC)
5937 .Authorization(TAG_NO_AUTH_REQUIRED)
5938 .Padding(PaddingMode::PKCS7)));
5939
5940 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005941 for (size_t i = 0; i <= 32; i++) {
5942 SCOPED_TRACE(testing::Message() << "i = " << i);
5943 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
5944 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005945 vector<uint8_t> iv;
5946 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5947 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5948 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5949 EXPECT_EQ(message, plaintext);
5950 }
5951}
5952
5953/*
5954 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5955 *
5956 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5957 */
5958TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5959 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5960 .TripleDesEncryptionKey(168)
5961 .BlockMode(BlockMode::CBC)
5962 .Authorization(TAG_NO_AUTH_REQUIRED)
5963 .Padding(PaddingMode::NONE)));
5964
5965 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08005966 for (size_t i = 0; i <= 32; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005967 auto begin_params =
5968 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5969 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5970 }
5971}
5972
5973/*
5974 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5975 *
5976 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5977 */
5978TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5979 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5980 .TripleDesEncryptionKey(168)
5981 .BlockMode(BlockMode::CBC)
5982 .Authorization(TAG_NO_AUTH_REQUIRED)
5983 .Padding(PaddingMode::PKCS7)));
5984
5985 string message = "a";
5986 vector<uint8_t> iv;
5987 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5988 EXPECT_EQ(8U, ciphertext.size());
5989 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005990
5991 auto begin_params = AuthorizationSetBuilder()
5992 .BlockMode(BlockMode::CBC)
5993 .Padding(PaddingMode::PKCS7)
5994 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07005995
5996 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08005997 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07005998 ++ciphertext[ciphertext.size() / 2];
5999 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6000 string plaintext;
6001 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6002 ErrorCode error = Finish(&plaintext);
6003 if (error == ErrorCode::INVALID_ARGUMENT) {
6004 // This is the expected error, we can exit the test now.
6005 return;
6006 } else {
6007 // Very small chance we got valid decryption, so try again.
6008 ASSERT_EQ(error, ErrorCode::OK);
6009 }
6010 }
6011 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006012}
6013
6014/*
6015 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
6016 *
6017 * Verifies that 3DES CBC works with many different input sizes.
6018 */
6019TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
6020 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6021 .TripleDesEncryptionKey(168)
6022 .BlockMode(BlockMode::CBC)
6023 .Authorization(TAG_NO_AUTH_REQUIRED)
6024 .Padding(PaddingMode::NONE)));
6025
6026 int increment = 7;
6027 string message(240, 'a');
6028 AuthorizationSet input_params =
6029 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6030 AuthorizationSet output_params;
6031 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6032
6033 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07006034 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006035 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006036 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
6037 EXPECT_EQ(message.size(), ciphertext.size());
6038
6039 // Move TAG_NONCE into input_params
6040 input_params = output_params;
6041 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
6042 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
6043 output_params.Clear();
6044
6045 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
6046 string plaintext;
6047 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006048 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006049 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
6050 EXPECT_EQ(ciphertext.size(), plaintext.size());
6051 EXPECT_EQ(message, plaintext);
6052}
6053
6054INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
6055
6056typedef KeyMintAidlTestBase MaxOperationsTest;
6057
6058/*
6059 * MaxOperationsTest.TestLimitAes
6060 *
6061 * Verifies that the max uses per boot tag works correctly with AES keys.
6062 */
6063TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006064 if (SecLevel() == SecurityLevel::STRONGBOX) {
6065 GTEST_SKIP() << "Test not applicable to StrongBox device";
6066 }
Selene Huang31ab4042020-04-29 04:22:39 -07006067
6068 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6069 .Authorization(TAG_NO_AUTH_REQUIRED)
6070 .AesEncryptionKey(128)
6071 .EcbMode()
6072 .Padding(PaddingMode::NONE)
6073 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
6074
6075 string message = "1234567890123456";
6076
6077 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6078
6079 EncryptMessage(message, params);
6080 EncryptMessage(message, params);
6081 EncryptMessage(message, params);
6082
6083 // Fourth time should fail.
6084 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
6085}
6086
6087/*
Qi Wud22ec842020-11-26 13:27:53 +08006088 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07006089 *
6090 * Verifies that the max uses per boot tag works correctly with RSA keys.
6091 */
6092TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006093 if (SecLevel() == SecurityLevel::STRONGBOX) {
6094 GTEST_SKIP() << "Test not applicable to StrongBox device";
6095 }
Selene Huang31ab4042020-04-29 04:22:39 -07006096
6097 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6098 .Authorization(TAG_NO_AUTH_REQUIRED)
6099 .RsaSigningKey(1024, 65537)
6100 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006101 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
6102 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006103
6104 string message = "1234567890123456";
6105
6106 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6107
6108 SignMessage(message, params);
6109 SignMessage(message, params);
6110 SignMessage(message, params);
6111
6112 // Fourth time should fail.
6113 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6114}
6115
6116INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6117
Qi Wud22ec842020-11-26 13:27:53 +08006118typedef KeyMintAidlTestBase UsageCountLimitTest;
6119
6120/*
Qi Wubeefae42021-01-28 23:16:37 +08006121 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006122 *
Qi Wubeefae42021-01-28 23:16:37 +08006123 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006124 */
Qi Wubeefae42021-01-28 23:16:37 +08006125TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006126 if (SecLevel() == SecurityLevel::STRONGBOX) {
6127 GTEST_SKIP() << "Test not applicable to StrongBox device";
6128 }
Qi Wud22ec842020-11-26 13:27:53 +08006129
6130 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6131 .Authorization(TAG_NO_AUTH_REQUIRED)
6132 .AesEncryptionKey(128)
6133 .EcbMode()
6134 .Padding(PaddingMode::NONE)
6135 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
6136
6137 // Check the usage count limit tag appears in the authorizations.
6138 AuthorizationSet auths;
6139 for (auto& entry : key_characteristics_) {
6140 auths.push_back(AuthorizationSet(entry.authorizations));
6141 }
6142 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6143 << "key usage count limit " << 1U << " missing";
6144
6145 string message = "1234567890123456";
6146 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6147
Qi Wubeefae42021-01-28 23:16:37 +08006148 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6149 AuthorizationSet keystore_auths =
6150 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6151
Qi Wud22ec842020-11-26 13:27:53 +08006152 // First usage of AES key should work.
6153 EncryptMessage(message, params);
6154
Qi Wud22ec842020-11-26 13:27:53 +08006155 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6156 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6157 // must be invalidated from secure storage (such as RPMB partition).
6158 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6159 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006160 // Usage count limit tag is enforced by keystore, keymint does nothing.
6161 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08006162 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6163 }
6164}
6165
6166/*
Qi Wubeefae42021-01-28 23:16:37 +08006167 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006168 *
Qi Wubeefae42021-01-28 23:16:37 +08006169 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006170 */
Qi Wubeefae42021-01-28 23:16:37 +08006171TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006172 if (SecLevel() == SecurityLevel::STRONGBOX) {
6173 GTEST_SKIP() << "Test not applicable to StrongBox device";
6174 }
Qi Wubeefae42021-01-28 23:16:37 +08006175
6176 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6177 .Authorization(TAG_NO_AUTH_REQUIRED)
6178 .AesEncryptionKey(128)
6179 .EcbMode()
6180 .Padding(PaddingMode::NONE)
6181 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
6182
6183 // Check the usage count limit tag appears in the authorizations.
6184 AuthorizationSet auths;
6185 for (auto& entry : key_characteristics_) {
6186 auths.push_back(AuthorizationSet(entry.authorizations));
6187 }
6188 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6189 << "key usage count limit " << 3U << " missing";
6190
6191 string message = "1234567890123456";
6192 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6193
6194 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6195 AuthorizationSet keystore_auths =
6196 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6197
6198 EncryptMessage(message, params);
6199 EncryptMessage(message, params);
6200 EncryptMessage(message, params);
6201
6202 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6203 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6204 // must be invalidated from secure storage (such as RPMB partition).
6205 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6206 } else {
6207 // Usage count limit tag is enforced by keystore, keymint does nothing.
6208 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
6209 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6210 }
6211}
6212
6213/*
6214 * UsageCountLimitTest.TestSingleUseRsa
6215 *
6216 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
6217 */
6218TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006219 if (SecLevel() == SecurityLevel::STRONGBOX) {
6220 GTEST_SKIP() << "Test not applicable to StrongBox device";
6221 }
Qi Wud22ec842020-11-26 13:27:53 +08006222
6223 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6224 .Authorization(TAG_NO_AUTH_REQUIRED)
6225 .RsaSigningKey(1024, 65537)
6226 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006227 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6228 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08006229
6230 // Check the usage count limit tag appears in the authorizations.
6231 AuthorizationSet auths;
6232 for (auto& entry : key_characteristics_) {
6233 auths.push_back(AuthorizationSet(entry.authorizations));
6234 }
6235 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6236 << "key usage count limit " << 1U << " missing";
6237
6238 string message = "1234567890123456";
6239 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6240
Qi Wubeefae42021-01-28 23:16:37 +08006241 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6242 AuthorizationSet keystore_auths =
6243 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6244
Qi Wud22ec842020-11-26 13:27:53 +08006245 // First usage of RSA key should work.
6246 SignMessage(message, params);
6247
Qi Wud22ec842020-11-26 13:27:53 +08006248 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6249 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6250 // must be invalidated from secure storage (such as RPMB partition).
6251 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6252 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006253 // Usage count limit tag is enforced by keystore, keymint does nothing.
6254 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
6255 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6256 }
6257}
6258
6259/*
6260 * UsageCountLimitTest.TestLimitUseRsa
6261 *
6262 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
6263 */
6264TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006265 if (SecLevel() == SecurityLevel::STRONGBOX) {
6266 GTEST_SKIP() << "Test not applicable to StrongBox device";
6267 }
Qi Wubeefae42021-01-28 23:16:37 +08006268
6269 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6270 .Authorization(TAG_NO_AUTH_REQUIRED)
6271 .RsaSigningKey(1024, 65537)
6272 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006273 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6274 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006275
6276 // Check the usage count limit tag appears in the authorizations.
6277 AuthorizationSet auths;
6278 for (auto& entry : key_characteristics_) {
6279 auths.push_back(AuthorizationSet(entry.authorizations));
6280 }
6281 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6282 << "key usage count limit " << 3U << " missing";
6283
6284 string message = "1234567890123456";
6285 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6286
6287 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6288 AuthorizationSet keystore_auths =
6289 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6290
6291 SignMessage(message, params);
6292 SignMessage(message, params);
6293 SignMessage(message, params);
6294
6295 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6296 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6297 // must be invalidated from secure storage (such as RPMB partition).
6298 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6299 } else {
6300 // Usage count limit tag is enforced by keystore, keymint does nothing.
6301 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006302 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6303 }
6304}
6305
Qi Wu8e727f72021-02-11 02:49:33 +08006306/*
6307 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6308 *
6309 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6310 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6311 * in hardware.
6312 */
6313TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01006314 if (SecLevel() == SecurityLevel::STRONGBOX) {
6315 GTEST_SKIP() << "Test not applicable to StrongBox device";
6316 }
Qi Wu8e727f72021-02-11 02:49:33 +08006317
6318 auto error = GenerateKey(AuthorizationSetBuilder()
6319 .RsaSigningKey(2048, 65537)
6320 .Digest(Digest::NONE)
6321 .Padding(PaddingMode::NONE)
6322 .Authorization(TAG_NO_AUTH_REQUIRED)
6323 .Authorization(TAG_ROLLBACK_RESISTANCE)
6324 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006325 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6326 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08006327 }
David Drysdale513bf122021-10-06 11:53:13 +01006328
6329 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6330 ASSERT_EQ(ErrorCode::OK, error);
6331 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6332 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6333 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6334
6335 // The KeyMint should also enforce single use key in hardware when it supports rollback
6336 // resistance.
6337 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6338 .Authorization(TAG_NO_AUTH_REQUIRED)
6339 .RsaSigningKey(1024, 65537)
6340 .NoDigestOrPadding()
6341 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6342 .SetDefaultValidity()));
6343
6344 // Check the usage count limit tag appears in the hardware authorizations.
6345 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6346 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6347 << "key usage count limit " << 1U << " missing";
6348
6349 string message = "1234567890123456";
6350 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6351
6352 // First usage of RSA key should work.
6353 SignMessage(message, params);
6354
6355 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6356 // must be invalidated from secure storage (such as RPMB partition).
6357 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08006358}
6359
Qi Wud22ec842020-11-26 13:27:53 +08006360INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6361
David Drysdale7de9feb2021-03-05 14:56:19 +00006362typedef KeyMintAidlTestBase GetHardwareInfoTest;
6363
6364TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6365 // Retrieving hardware info should give the same result each time.
6366 KeyMintHardwareInfo info;
6367 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6368 KeyMintHardwareInfo info2;
6369 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6370 EXPECT_EQ(info, info2);
6371}
6372
6373INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6374
Selene Huang31ab4042020-04-29 04:22:39 -07006375typedef KeyMintAidlTestBase AddEntropyTest;
6376
6377/*
6378 * AddEntropyTest.AddEntropy
6379 *
6380 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6381 * is actually added.
6382 */
6383TEST_P(AddEntropyTest, AddEntropy) {
6384 string data = "foo";
6385 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6386}
6387
6388/*
6389 * AddEntropyTest.AddEmptyEntropy
6390 *
6391 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6392 */
6393TEST_P(AddEntropyTest, AddEmptyEntropy) {
6394 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6395}
6396
6397/*
6398 * AddEntropyTest.AddLargeEntropy
6399 *
6400 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6401 */
6402TEST_P(AddEntropyTest, AddLargeEntropy) {
6403 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6404}
6405
David Drysdalebb3d85e2021-04-13 11:15:51 +01006406/*
6407 * AddEntropyTest.AddTooLargeEntropy
6408 *
6409 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6410 */
6411TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6412 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6413 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6414}
6415
Selene Huang31ab4042020-04-29 04:22:39 -07006416INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6417
Selene Huang31ab4042020-04-29 04:22:39 -07006418typedef KeyMintAidlTestBase KeyDeletionTest;
6419
6420/**
6421 * KeyDeletionTest.DeleteKey
6422 *
6423 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6424 * valid key blob.
6425 */
6426TEST_P(KeyDeletionTest, DeleteKey) {
6427 auto error = GenerateKey(AuthorizationSetBuilder()
6428 .RsaSigningKey(2048, 65537)
6429 .Digest(Digest::NONE)
6430 .Padding(PaddingMode::NONE)
6431 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006432 .Authorization(TAG_ROLLBACK_RESISTANCE)
6433 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006434 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6435 GTEST_SKIP() << "Rollback resistance not supported";
6436 }
Selene Huang31ab4042020-04-29 04:22:39 -07006437
6438 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006439 ASSERT_EQ(ErrorCode::OK, error);
6440 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6441 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006442
David Drysdale513bf122021-10-06 11:53:13 +01006443 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07006444
David Drysdale513bf122021-10-06 11:53:13 +01006445 string message = "12345678901234567890123456789012";
6446 AuthorizationSet begin_out_params;
6447 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6448 Begin(KeyPurpose::SIGN, key_blob_,
6449 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6450 &begin_out_params));
6451 AbortIfNeeded();
6452 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006453}
6454
6455/**
6456 * KeyDeletionTest.DeleteInvalidKey
6457 *
6458 * This test checks that the HAL excepts invalid key blobs..
6459 */
6460TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6461 // Generate key just to check if rollback protection is implemented
6462 auto error = GenerateKey(AuthorizationSetBuilder()
6463 .RsaSigningKey(2048, 65537)
6464 .Digest(Digest::NONE)
6465 .Padding(PaddingMode::NONE)
6466 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006467 .Authorization(TAG_ROLLBACK_RESISTANCE)
6468 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006469 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6470 GTEST_SKIP() << "Rollback resistance not supported";
6471 }
Selene Huang31ab4042020-04-29 04:22:39 -07006472
6473 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006474 ASSERT_EQ(ErrorCode::OK, error);
6475 AuthorizationSet enforced(SecLevelAuthorizations());
6476 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006477
David Drysdale513bf122021-10-06 11:53:13 +01006478 // Delete the key we don't care about the result at this point.
6479 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07006480
David Drysdale513bf122021-10-06 11:53:13 +01006481 // Now create an invalid key blob and delete it.
6482 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07006483
David Drysdale513bf122021-10-06 11:53:13 +01006484 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07006485}
6486
6487/**
6488 * KeyDeletionTest.DeleteAllKeys
6489 *
6490 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6491 *
6492 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6493 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6494 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6495 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6496 * credentials stored in Keystore/Keymint.
6497 */
6498TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01006499 if (!arm_deleteAllKeys) {
6500 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
6501 return;
6502 }
Selene Huang31ab4042020-04-29 04:22:39 -07006503 auto error = GenerateKey(AuthorizationSetBuilder()
6504 .RsaSigningKey(2048, 65537)
6505 .Digest(Digest::NONE)
6506 .Padding(PaddingMode::NONE)
6507 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06006508 .Authorization(TAG_ROLLBACK_RESISTANCE)
6509 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006510 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6511 GTEST_SKIP() << "Rollback resistance not supported";
6512 }
Selene Huang31ab4042020-04-29 04:22:39 -07006513
6514 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006515 ASSERT_EQ(ErrorCode::OK, error);
6516 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6517 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006518
David Drysdale513bf122021-10-06 11:53:13 +01006519 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07006520
David Drysdale513bf122021-10-06 11:53:13 +01006521 string message = "12345678901234567890123456789012";
6522 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07006523
David Drysdale513bf122021-10-06 11:53:13 +01006524 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6525 Begin(KeyPurpose::SIGN, key_blob_,
6526 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6527 &begin_out_params));
6528 AbortIfNeeded();
6529 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006530}
6531
6532INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6533
David Drysdaled2cc8c22021-04-15 13:29:45 +01006534typedef KeyMintAidlTestBase KeyUpgradeTest;
6535
6536/**
6537 * KeyUpgradeTest.UpgradeInvalidKey
6538 *
6539 * This test checks that the HAL excepts invalid key blobs..
6540 */
6541TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6542 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6543
6544 std::vector<uint8_t> new_blob;
6545 Status result = keymint_->upgradeKey(key_blob,
6546 AuthorizationSetBuilder()
6547 .Authorization(TAG_APPLICATION_ID, "clientid")
6548 .Authorization(TAG_APPLICATION_DATA, "appdata")
6549 .vector_data(),
6550 &new_blob);
6551 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6552}
6553
6554INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6555
Selene Huang31ab4042020-04-29 04:22:39 -07006556using UpgradeKeyTest = KeyMintAidlTestBase;
6557
6558/*
6559 * UpgradeKeyTest.UpgradeKey
6560 *
6561 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6562 */
6563TEST_P(UpgradeKeyTest, UpgradeKey) {
6564 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6565 .AesEncryptionKey(128)
6566 .Padding(PaddingMode::NONE)
6567 .Authorization(TAG_NO_AUTH_REQUIRED)));
6568
6569 auto result = UpgradeKey(key_blob_);
6570
6571 // Key doesn't need upgrading. Should get okay, but no new key blob.
6572 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6573}
6574
6575INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6576
6577using ClearOperationsTest = KeyMintAidlTestBase;
6578
6579/*
6580 * ClearSlotsTest.TooManyOperations
6581 *
6582 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6583 * operations are started without being finished or aborted. Also verifies
6584 * that aborting the operations clears the operations.
6585 *
6586 */
6587TEST_P(ClearOperationsTest, TooManyOperations) {
6588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6589 .Authorization(TAG_NO_AUTH_REQUIRED)
6590 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006591 .Padding(PaddingMode::NONE)
6592 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006593
6594 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6595 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006596 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006597 AuthorizationSet out_params;
6598 ErrorCode result;
6599 size_t i;
6600
6601 for (i = 0; i < max_operations; i++) {
6602 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6603 if (ErrorCode::OK != result) {
6604 break;
6605 }
6606 }
6607 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6608 // Try again just in case there's a weird overflow bug
6609 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6610 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6611 for (size_t j = 0; j < i; j++) {
6612 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6613 << "Aboort failed for i = " << j << std::endl;
6614 }
6615 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6616 AbortIfNeeded();
6617}
6618
6619INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6620
6621typedef KeyMintAidlTestBase TransportLimitTest;
6622
6623/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006624 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006625 *
6626 * Verifies that passing input data to finish succeeds as expected.
6627 */
6628TEST_P(TransportLimitTest, LargeFinishInput) {
6629 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6630 .Authorization(TAG_NO_AUTH_REQUIRED)
6631 .AesEncryptionKey(128)
6632 .BlockMode(BlockMode::ECB)
6633 .Padding(PaddingMode::NONE)));
6634
6635 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6636 auto cipher_params =
6637 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6638
6639 AuthorizationSet out_params;
6640 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6641
6642 string plain_message = std::string(1 << msg_size, 'x');
6643 string encrypted_message;
6644 auto rc = Finish(plain_message, &encrypted_message);
6645
6646 EXPECT_EQ(ErrorCode::OK, rc);
6647 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6648 << "Encrypt finish returned OK, but did not consume all of the given input";
6649 cipher_params.push_back(out_params);
6650
6651 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6652
6653 string decrypted_message;
6654 rc = Finish(encrypted_message, &decrypted_message);
6655 EXPECT_EQ(ErrorCode::OK, rc);
6656 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6657 << "Decrypt finish returned OK, did not consume all of the given input";
6658 }
6659}
6660
6661INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6662
David Zeuthene0c40892021-01-08 12:54:11 -05006663typedef KeyMintAidlTestBase KeyAgreementTest;
6664
Seth Moored79a0ec2021-12-13 20:03:33 +00006665static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05006666 switch (curve) {
6667 case EcCurve::P_224:
6668 return NID_secp224r1;
6669 case EcCurve::P_256:
6670 return NID_X9_62_prime256v1;
6671 case EcCurve::P_384:
6672 return NID_secp384r1;
6673 case EcCurve::P_521:
6674 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00006675 case EcCurve::CURVE_25519:
6676 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05006677 }
6678}
6679
6680/*
6681 * KeyAgreementTest.Ecdh
6682 *
6683 * Verifies that ECDH works for all curves
6684 */
6685TEST_P(KeyAgreementTest, Ecdh) {
6686 // Because it's possible to use this API with keys on different curves, we
6687 // check all N^2 combinations where N is the number of supported
6688 // curves.
6689 //
6690 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6691 // lot more curves we can be smart about things and just pick |otherCurve| so
6692 // it's not |curve| and that way we end up with only 2*N runs
6693 //
6694 for (auto curve : ValidCurves()) {
6695 for (auto localCurve : ValidCurves()) {
6696 // Generate EC key locally (with access to private key material)
6697 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
Seth Moored79a0ec2021-12-13 20:03:33 +00006698 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
David Zeuthene0c40892021-01-08 12:54:11 -05006699 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6700 ASSERT_NE(group, nullptr);
6701 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6702 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6703 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6704 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6705
6706 // Get encoded form of the public part of the locally generated key...
6707 unsigned char* p = nullptr;
6708 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6709 ASSERT_GT(encodedPublicKeySize, 0);
6710 vector<uint8_t> encodedPublicKey(
6711 reinterpret_cast<const uint8_t*>(p),
6712 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6713 OPENSSL_free(p);
6714
6715 // Generate EC key in KeyMint (only access to public key material)
6716 vector<uint8_t> challenge = {0x41, 0x42};
6717 EXPECT_EQ(
6718 ErrorCode::OK,
6719 GenerateKey(AuthorizationSetBuilder()
6720 .Authorization(TAG_NO_AUTH_REQUIRED)
6721 .Authorization(TAG_EC_CURVE, curve)
6722 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6723 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6724 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006725 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6726 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006727 << "Failed to generate key";
6728 ASSERT_GT(cert_chain_.size(), 0);
6729 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6730 ASSERT_NE(kmKeyCert, nullptr);
6731 // Check that keyAgreement (bit 4) is set in KeyUsage
6732 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6733 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6734 ASSERT_NE(kmPkey, nullptr);
6735 if (dump_Attestations) {
6736 for (size_t n = 0; n < cert_chain_.size(); n++) {
6737 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6738 }
6739 }
6740
6741 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6742 if (curve != localCurve) {
6743 // If the keys are using different curves KeyMint should fail with
6744 // ErrorCode:INVALID_ARGUMENT. Check that.
6745 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6746 string ZabFromKeyMintStr;
6747 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6748 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6749 &ZabFromKeyMintStr));
6750
6751 } else {
6752 // Otherwise if the keys are using the same curve, it should work.
6753 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6754 string ZabFromKeyMintStr;
6755 EXPECT_EQ(ErrorCode::OK,
6756 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6757 &ZabFromKeyMintStr));
6758 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6759
6760 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6761 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6762 ASSERT_NE(ctx, nullptr);
6763 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6764 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6765 size_t ZabFromTestLen = 0;
6766 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6767 vector<uint8_t> ZabFromTest;
6768 ZabFromTest.resize(ZabFromTestLen);
6769 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6770
6771 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6772 }
6773
6774 CheckedDeleteKey();
6775 }
6776 }
6777}
6778
6779INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6780
David Drysdaled2cc8c22021-04-15 13:29:45 +01006781using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6782
6783// This is a problematic test, as it can render the device under test permanently unusable.
6784// Re-enable and run at your own risk.
6785TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6786 auto result = DestroyAttestationIds();
6787 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6788}
6789
6790INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6791
Shawn Willdend659c7c2021-02-19 14:51:51 -07006792using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006793
David Drysdaledb0dcf52021-05-18 11:43:31 +01006794/*
6795 * EarlyBootKeyTest.CreateEarlyBootKeys
6796 *
6797 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6798 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006799TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01006800 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006801 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6802 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6803
David Drysdaleadfe6112021-05-27 12:00:53 +01006804 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6805 ASSERT_GT(keyData.blob.size(), 0U);
6806 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6807 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6808 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006809 CheckedDeleteKey(&aesKeyData.blob);
6810 CheckedDeleteKey(&hmacKeyData.blob);
6811 CheckedDeleteKey(&rsaKeyData.blob);
6812 CheckedDeleteKey(&ecdsaKeyData.blob);
6813}
6814
David Drysdaledb0dcf52021-05-18 11:43:31 +01006815/*
David Drysdaleadfe6112021-05-27 12:00:53 +01006816 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6817 *
6818 * Verifies that creating an early boot key with attestation succeeds.
6819 */
6820TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6821 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6822 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6823 builder->AttestationChallenge("challenge");
6824 builder->AttestationApplicationId("app_id");
6825 });
6826
6827 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6828 ASSERT_GT(keyData.blob.size(), 0U);
6829 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6830 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6831 }
6832 CheckedDeleteKey(&aesKeyData.blob);
6833 CheckedDeleteKey(&hmacKeyData.blob);
6834 CheckedDeleteKey(&rsaKeyData.blob);
6835 CheckedDeleteKey(&ecdsaKeyData.blob);
6836}
6837
6838/*
6839 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01006840 *
6841 * Verifies that using early boot keys at a later stage fails.
6842 */
6843TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6844 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6845 .Authorization(TAG_NO_AUTH_REQUIRED)
6846 .Authorization(TAG_EARLY_BOOT_ONLY)
6847 .HmacKey(128)
6848 .Digest(Digest::SHA_2_256)
6849 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6850 AuthorizationSet output_params;
6851 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6852 AuthorizationSetBuilder()
6853 .Digest(Digest::SHA_2_256)
6854 .Authorization(TAG_MAC_LENGTH, 256),
6855 &output_params));
6856}
6857
6858/*
6859 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6860 *
6861 * Verifies that importing early boot keys fails.
6862 */
6863TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6864 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6865 .Authorization(TAG_NO_AUTH_REQUIRED)
6866 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01006867 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01006868 .Digest(Digest::SHA_2_256)
6869 .SetDefaultValidity(),
6870 KeyFormat::PKCS8, ec_256_key));
6871}
6872
David Drysdaled2cc8c22021-04-15 13:29:45 +01006873// 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 +00006874// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6875// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6876// early boot, so you'll have to reboot between runs.
6877TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6878 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6879 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6880 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6881 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6882 EXPECT_TRUE(
6883 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6884 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6885 EXPECT_TRUE(
6886 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6887
6888 // Should be able to use keys, since early boot has not ended
6889 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6890 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6891 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6892 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6893
6894 // End early boot
6895 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6896 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6897
6898 // Should not be able to use already-created keys.
6899 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6900 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6901 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6902 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6903
6904 CheckedDeleteKey(&aesKeyData.blob);
6905 CheckedDeleteKey(&hmacKeyData.blob);
6906 CheckedDeleteKey(&rsaKeyData.blob);
6907 CheckedDeleteKey(&ecdsaKeyData.blob);
6908
6909 // Should not be able to create new keys
6910 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6911 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6912
6913 CheckedDeleteKey(&aesKeyData.blob);
6914 CheckedDeleteKey(&hmacKeyData.blob);
6915 CheckedDeleteKey(&rsaKeyData.blob);
6916 CheckedDeleteKey(&ecdsaKeyData.blob);
6917}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006918
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006919INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6920
Shawn Willdend659c7c2021-02-19 14:51:51 -07006921using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006922
6923// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6924// between runs... and on most test devices there are no enrolled credentials so it can't be
6925// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6926// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6927// a manual test process, which includes unlocking between runs, which is why it's included here.
6928// Well, that and the fact that it's the only test we can do without also making calls into the
6929// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6930// implications might be, so that may or may not be a solution.
6931TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6932 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6933 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6934
6935 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6936 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6937 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6938 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6939
6940 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006941 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006942 ASSERT_EQ(ErrorCode::OK, rc);
6943 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6944 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6945 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6946 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6947
6948 CheckedDeleteKey(&aesKeyData.blob);
6949 CheckedDeleteKey(&hmacKeyData.blob);
6950 CheckedDeleteKey(&rsaKeyData.blob);
6951 CheckedDeleteKey(&ecdsaKeyData.blob);
6952}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006953
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006954INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6955
Janis Danisevskis24c04702020-12-16 18:28:39 -08006956} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006957
6958int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006959 std::cout << "Testing ";
6960 auto halInstances =
6961 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6962 std::cout << "HAL instances:\n";
6963 for (auto& entry : halInstances) {
6964 std::cout << " " << entry << '\n';
6965 }
6966
Selene Huang31ab4042020-04-29 04:22:39 -07006967 ::testing::InitGoogleTest(&argc, argv);
6968 for (int i = 1; i < argc; ++i) {
6969 if (argv[i][0] == '-') {
6970 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006971 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6972 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006973 }
6974 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006975 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6976 dump_Attestations = true;
6977 } else {
6978 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006979 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00006980 if (std::string(argv[i]) == "--skip_boot_pl_check") {
6981 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
6982 // be run in emulated environments that don't have the normal bootloader
6983 // interactions.
6984 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
6985 }
Selene Huang31ab4042020-04-29 04:22:39 -07006986 }
6987 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006988 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006989}