blob: 161531d8f8f4fe4319b3c060b10ddf0b9fac17e2 [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);
945 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
946 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);
1096 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1097 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);
1318 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1319 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);
1447 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1448 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.
1526 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1527 SecLevel(), cert_chain_[0].encodedCertificate));
1528
1529 CheckedDeleteKey(&key_blob);
1530 }
1531
David Drysdalec53b7d92021-10-11 12:35:58 +01001532 // Collection of invalid attestation ID tags.
1533 auto invalid_tags =
1534 AuthorizationSetBuilder()
1535 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1536 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1537 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1538 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1539 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1540 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1541 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1542 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001543 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001544 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001545 vector<uint8_t> key_blob;
1546 vector<KeyCharacteristics> key_characteristics;
1547 AuthorizationSetBuilder builder =
1548 AuthorizationSetBuilder()
1549 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001550 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001551 .Digest(Digest::NONE)
1552 .AttestationChallenge(challenge)
1553 .AttestationApplicationId(app_id)
1554 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1555 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1556 .SetDefaultValidity();
1557 builder.push_back(tag);
1558 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1559 GenerateKey(builder, &key_blob, &key_characteristics));
1560 }
1561}
1562
1563/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001564 * NewKeyGenerationTest.EcdsaAttestationIdTags
1565 *
1566 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1567 * attestation extension.
1568 */
1569TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
1570 auto challenge = "hello";
1571 auto app_id = "foo";
1572 auto subject = "cert subj 2";
1573 vector<uint8_t> subject_der(make_name_from_str(subject));
1574 uint64_t serial_int = 0x1010;
1575 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1576 const AuthorizationSetBuilder base_builder =
1577 AuthorizationSetBuilder()
1578 .Authorization(TAG_NO_AUTH_REQUIRED)
1579 .EcdsaSigningKey(EcCurve::P_256)
1580 .Digest(Digest::NONE)
1581 .AttestationChallenge(challenge)
1582 .AttestationApplicationId(app_id)
1583 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1584 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1585 .SetDefaultValidity();
1586
1587 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1588 auto extra_tags = AuthorizationSetBuilder();
1589 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1590 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1591 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1592 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1593 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1594 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1595
1596 for (const KeyParameter& tag : extra_tags) {
1597 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1598 vector<uint8_t> key_blob;
1599 vector<KeyCharacteristics> key_characteristics;
1600 AuthorizationSetBuilder builder = base_builder;
1601 builder.push_back(tag);
1602 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1603 if (result == ErrorCode::CANNOT_ATTEST_IDS) {
1604 // Device ID attestation is optional; KeyMint may not support it at all.
1605 continue;
1606 }
1607 ASSERT_EQ(result, ErrorCode::OK);
1608 ASSERT_GT(key_blob.size(), 0U);
1609
1610 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1611 ASSERT_GT(cert_chain_.size(), 0);
1612 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1613
1614 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1615 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1616
1617 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
1618 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
1619 // attestation extension should contain them, so make sure the extra tag is added.
1620 hw_enforced.push_back(tag);
1621
1622 // Verifying the attestation record will check for the specific tag because
1623 // it's included in the authorizations.
1624 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1625 SecLevel(), cert_chain_[0].encodedCertificate));
1626
1627 CheckedDeleteKey(&key_blob);
1628 }
1629}
1630
1631/*
David Drysdale565ccc72021-10-11 12:49:50 +01001632 * NewKeyGenerationTest.EcdsaAttestationUniqueId
1633 *
1634 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
1635 */
1636TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
1637 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00001638 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01001639 auto challenge = "hello";
1640 auto subject = "cert subj 2";
1641 vector<uint8_t> subject_der(make_name_from_str(subject));
1642 uint64_t serial_int = 0x1010;
1643 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00001644 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01001645 AuthorizationSetBuilder()
1646 .Authorization(TAG_NO_AUTH_REQUIRED)
1647 .Authorization(TAG_INCLUDE_UNIQUE_ID)
1648 .EcdsaSigningKey(EcCurve::P_256)
1649 .Digest(Digest::NONE)
1650 .AttestationChallenge(challenge)
1651 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1652 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1653 .AttestationApplicationId(app_id)
1654 .Authorization(TAG_CREATION_DATETIME, datetime)
1655 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00001656 if (reset) {
1657 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
1658 }
David Drysdale565ccc72021-10-11 12:49:50 +01001659
1660 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
1661 ASSERT_GT(key_blob_.size(), 0U);
1662
1663 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1664 ASSERT_GT(cert_chain_.size(), 0);
1665 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1666
1667 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
1668 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
1669
1670 // Check that the unique ID field in the extension is non-empty.
1671 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1672 SecLevel(), cert_chain_[0].encodedCertificate,
1673 unique_id));
1674 EXPECT_GT(unique_id->size(), 0);
1675 CheckedDeleteKey();
1676 };
1677
1678 // Generate unique ID
1679 auto app_id = "foo";
1680 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
1681 vector<uint8_t> unique_id;
1682 get_unique_id(app_id, cert_date, &unique_id);
1683
1684 // Generating a new key with the same parameters should give the same unique ID.
1685 vector<uint8_t> unique_id2;
1686 get_unique_id(app_id, cert_date, &unique_id2);
1687 EXPECT_EQ(unique_id, unique_id2);
1688
1689 // Generating a new key with a slightly different date should give the same unique ID.
1690 uint64_t rounded_date = cert_date / 2592000000LLU;
1691 uint64_t min_date = rounded_date * 2592000000LLU;
1692 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
1693
1694 vector<uint8_t> unique_id3;
1695 get_unique_id(app_id, min_date, &unique_id3);
1696 EXPECT_EQ(unique_id, unique_id3);
1697
1698 vector<uint8_t> unique_id4;
1699 get_unique_id(app_id, max_date, &unique_id4);
1700 EXPECT_EQ(unique_id, unique_id4);
1701
1702 // A different attestation application ID should yield a different unique ID.
1703 auto app_id2 = "different_foo";
1704 vector<uint8_t> unique_id5;
1705 get_unique_id(app_id2, cert_date, &unique_id5);
1706 EXPECT_NE(unique_id, unique_id5);
1707
1708 // A radically different date should yield a different unique ID.
1709 vector<uint8_t> unique_id6;
1710 get_unique_id(app_id, 1611621648000, &unique_id6);
1711 EXPECT_NE(unique_id, unique_id6);
1712
1713 vector<uint8_t> unique_id7;
1714 get_unique_id(app_id, max_date + 1, &unique_id7);
1715 EXPECT_NE(unique_id, unique_id7);
1716
1717 vector<uint8_t> unique_id8;
1718 get_unique_id(app_id, min_date - 1, &unique_id8);
1719 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00001720
1721 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
1722 vector<uint8_t> unique_id9;
1723 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
1724 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01001725}
1726
1727/*
David Drysdale37af4b32021-05-14 16:46:59 +01001728 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1729 *
1730 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1731 */
1732TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1733 auto challenge = "hello";
1734 auto attest_app_id = "foo";
1735 auto subject = "cert subj 2";
1736 vector<uint8_t> subject_der(make_name_from_str(subject));
1737 uint64_t serial_int = 0x1010;
1738 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1739
1740 // Earlier versions of the attestation extension schema included a slot:
1741 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1742 // This should never have been included, and should never be filled in.
1743 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1744 // to confirm that this field never makes it into the attestation extension.
1745 vector<uint8_t> key_blob;
1746 vector<KeyCharacteristics> key_characteristics;
1747 auto result = GenerateKey(AuthorizationSetBuilder()
1748 .Authorization(TAG_NO_AUTH_REQUIRED)
1749 .EcdsaSigningKey(EcCurve::P_256)
1750 .Digest(Digest::NONE)
1751 .AttestationChallenge(challenge)
1752 .AttestationApplicationId(attest_app_id)
1753 .Authorization(TAG_APPLICATION_ID, "client_id")
1754 .Authorization(TAG_APPLICATION_DATA, "appdata")
1755 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1756 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1757 .SetDefaultValidity(),
1758 &key_blob, &key_characteristics);
1759 ASSERT_EQ(result, ErrorCode::OK);
1760 ASSERT_GT(key_blob.size(), 0U);
1761
1762 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1763 ASSERT_GT(cert_chain_.size(), 0);
1764 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1765
1766 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1767 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1768 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1769 SecLevel(), cert_chain_[0].encodedCertificate));
1770
1771 // Check that the app id is not in the cert.
1772 string app_id = "clientid";
1773 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1774 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1775 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1776 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1777 cert_chain_[0].encodedCertificate.end());
1778
1779 CheckedDeleteKey(&key_blob);
1780}
1781
1782/*
Selene Huang4f64c222021-04-13 19:54:36 -07001783 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1784 *
1785 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1786 * the key will generate a self signed attestation.
1787 */
1788TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001789 auto subject = "cert subj 2";
1790 vector<uint8_t> subject_der(make_name_from_str(subject));
1791
1792 uint64_t serial_int = 0x123456FFF1234;
1793 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1794
David Drysdaledf09e542021-06-08 15:46:11 +01001795 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001796 vector<uint8_t> key_blob;
1797 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001798 ASSERT_EQ(ErrorCode::OK,
1799 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001800 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001801 .Digest(Digest::NONE)
1802 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1803 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1804 .SetDefaultValidity(),
1805 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001806 ASSERT_GT(key_blob.size(), 0U);
1807 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001808 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001809
1810 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1811
1812 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001813 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001814
1815 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001816 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001817 ASSERT_EQ(cert_chain_.size(), 1);
1818
1819 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1820 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1821
1822 CheckedDeleteKey(&key_blob);
1823 }
1824}
1825
1826/*
1827 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1828 *
1829 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1830 * app id must also be provided or else it will fail.
1831 */
1832TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1833 auto challenge = "hello";
1834 vector<uint8_t> key_blob;
1835 vector<KeyCharacteristics> key_characteristics;
1836
1837 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1838 GenerateKey(AuthorizationSetBuilder()
1839 .EcdsaSigningKey(EcCurve::P_256)
1840 .Digest(Digest::NONE)
1841 .AttestationChallenge(challenge)
1842 .SetDefaultValidity(),
1843 &key_blob, &key_characteristics));
1844}
1845
1846/*
1847 * NewKeyGenerationTest.EcdsaIgnoreAppId
1848 *
1849 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1850 * any appid will be ignored, and keymint will generate a self sign certificate.
1851 */
1852TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1853 auto app_id = "foo";
1854
David Drysdaledf09e542021-06-08 15:46:11 +01001855 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001856 vector<uint8_t> key_blob;
1857 vector<KeyCharacteristics> key_characteristics;
1858 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001859 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001860 .Digest(Digest::NONE)
1861 .AttestationApplicationId(app_id)
1862 .SetDefaultValidity(),
1863 &key_blob, &key_characteristics));
1864
1865 ASSERT_GT(key_blob.size(), 0U);
1866 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001867 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001868
1869 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1870
1871 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001872 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001873
1874 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1875 ASSERT_EQ(cert_chain_.size(), 1);
1876
1877 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1878 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1879
1880 CheckedDeleteKey(&key_blob);
1881 }
1882}
1883
1884/*
1885 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1886 *
1887 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1888 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1889 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1890 * to specify how many following bytes will be used to encode the length.
1891 */
1892TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1893 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001894 std::vector<uint32_t> app_id_lengths{143, 258};
1895
1896 for (uint32_t length : app_id_lengths) {
1897 const string app_id(length, 'a');
1898 vector<uint8_t> key_blob;
1899 vector<KeyCharacteristics> key_characteristics;
1900 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1901 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001902 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001903 .Digest(Digest::NONE)
1904 .AttestationChallenge(challenge)
1905 .AttestationApplicationId(app_id)
1906 .SetDefaultValidity(),
1907 &key_blob, &key_characteristics));
1908 ASSERT_GT(key_blob.size(), 0U);
1909 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001910 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001911
1912 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1913
1914 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001915 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001916
1917 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1918 ASSERT_GT(cert_chain_.size(), 0);
1919
1920 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1921 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1922 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1923 sw_enforced, hw_enforced, SecLevel(),
1924 cert_chain_[0].encodedCertificate));
1925
1926 CheckedDeleteKey(&key_blob);
1927 }
1928}
1929
1930/*
Qi Wud22ec842020-11-26 13:27:53 +08001931 * NewKeyGenerationTest.LimitedUsageEcdsa
1932 *
1933 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1934 * resulting keys have correct characteristics.
1935 */
1936TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001937 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001938 vector<uint8_t> key_blob;
1939 vector<KeyCharacteristics> key_characteristics;
1940 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001941 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001942 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001943 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1944 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001945 &key_blob, &key_characteristics));
1946
1947 ASSERT_GT(key_blob.size(), 0U);
1948 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001949 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001950
1951 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1952
1953 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001954 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001955
1956 // Check the usage count limit tag appears in the authorizations.
1957 AuthorizationSet auths;
1958 for (auto& entry : key_characteristics) {
1959 auths.push_back(AuthorizationSet(entry.authorizations));
1960 }
1961 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1962 << "key usage count limit " << 1U << " missing";
1963
1964 CheckedDeleteKey(&key_blob);
1965 }
1966}
1967
1968/*
Selene Huang31ab4042020-04-29 04:22:39 -07001969 * NewKeyGenerationTest.EcdsaDefaultSize
1970 *
David Drysdaledf09e542021-06-08 15:46:11 +01001971 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001972 * UNSUPPORTED_KEY_SIZE.
1973 */
1974TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1975 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1976 GenerateKey(AuthorizationSetBuilder()
1977 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1978 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001979 .Digest(Digest::NONE)
1980 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001981}
1982
1983/*
1984 * NewKeyGenerationTest.EcdsaInvalidSize
1985 *
1986 * Verifies that specifying an invalid key size for EC key generation returns
1987 * UNSUPPORTED_KEY_SIZE.
1988 */
1989TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdaledf09e542021-06-08 15:46:11 +01001990 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001991 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001992 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001993 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001994 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001995 .Digest(Digest::NONE)
1996 .SetDefaultValidity(),
1997 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001998 }
1999
David Drysdaledf09e542021-06-08 15:46:11 +01002000 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2001 GenerateKey(AuthorizationSetBuilder()
2002 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2003 .Authorization(TAG_KEY_SIZE, 190)
2004 .SigningKey()
2005 .Digest(Digest::NONE)
2006 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002007}
2008
2009/*
2010 * NewKeyGenerationTest.EcdsaMismatchKeySize
2011 *
2012 * Verifies that specifying mismatched key size and curve for EC key generation returns
2013 * INVALID_ARGUMENT.
2014 */
2015TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002016 if (SecLevel() == SecurityLevel::STRONGBOX) {
2017 GTEST_SKIP() << "Test not applicable to StrongBox device";
2018 }
Selene Huang31ab4042020-04-29 04:22:39 -07002019
David Drysdaledf09e542021-06-08 15:46:11 +01002020 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002021 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002022 .Authorization(TAG_KEY_SIZE, 224)
2023 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002024 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002025 .Digest(Digest::NONE)
2026 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002027 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002028}
2029
2030/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002031 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002032 *
2033 * Verifies that keymint does not support any curve designated as unsupported.
2034 */
2035TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2036 Digest digest;
2037 if (SecLevel() == SecurityLevel::STRONGBOX) {
2038 digest = Digest::SHA_2_256;
2039 } else {
2040 digest = Digest::SHA_2_512;
2041 }
2042 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002043 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2044 .EcdsaSigningKey(curve)
2045 .Digest(digest)
2046 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002047 << "Failed to generate key on curve: " << curve;
2048 CheckedDeleteKey();
2049 }
2050}
2051
2052/*
2053 * NewKeyGenerationTest.Hmac
2054 *
2055 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2056 * characteristics.
2057 */
2058TEST_P(NewKeyGenerationTest, Hmac) {
2059 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2060 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002061 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002062 constexpr size_t key_size = 128;
2063 ASSERT_EQ(ErrorCode::OK,
2064 GenerateKey(
2065 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2066 TAG_MIN_MAC_LENGTH, 128),
2067 &key_blob, &key_characteristics));
2068
2069 ASSERT_GT(key_blob.size(), 0U);
2070 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002071 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002072
Shawn Willden7f424372021-01-10 18:06:50 -07002073 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2074 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2075 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2076 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002077
2078 CheckedDeleteKey(&key_blob);
2079 }
2080}
2081
2082/*
Selene Huang4f64c222021-04-13 19:54:36 -07002083 * NewKeyGenerationTest.HmacNoAttestation
2084 *
2085 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2086 * and app id are provided.
2087 */
2088TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2089 auto challenge = "hello";
2090 auto app_id = "foo";
2091
2092 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2093 vector<uint8_t> key_blob;
2094 vector<KeyCharacteristics> key_characteristics;
2095 constexpr size_t key_size = 128;
2096 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2097 .HmacKey(key_size)
2098 .Digest(digest)
2099 .AttestationChallenge(challenge)
2100 .AttestationApplicationId(app_id)
2101 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2102 &key_blob, &key_characteristics));
2103
2104 ASSERT_GT(key_blob.size(), 0U);
2105 ASSERT_EQ(cert_chain_.size(), 0);
2106 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002107 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002108
2109 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2110 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2111 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2112 << "Key size " << key_size << "missing";
2113
2114 CheckedDeleteKey(&key_blob);
2115 }
2116}
2117
2118/*
Qi Wud22ec842020-11-26 13:27:53 +08002119 * NewKeyGenerationTest.LimitedUsageHmac
2120 *
2121 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2122 * resulting keys have correct characteristics.
2123 */
2124TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2125 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2126 vector<uint8_t> key_blob;
2127 vector<KeyCharacteristics> key_characteristics;
2128 constexpr size_t key_size = 128;
2129 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2130 .HmacKey(key_size)
2131 .Digest(digest)
2132 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2133 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2134 &key_blob, &key_characteristics));
2135
2136 ASSERT_GT(key_blob.size(), 0U);
2137 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002138 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002139
2140 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2141 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2142 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2143 << "Key size " << key_size << "missing";
2144
2145 // Check the usage count limit tag appears in the authorizations.
2146 AuthorizationSet auths;
2147 for (auto& entry : key_characteristics) {
2148 auths.push_back(AuthorizationSet(entry.authorizations));
2149 }
2150 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2151 << "key usage count limit " << 1U << " missing";
2152
2153 CheckedDeleteKey(&key_blob);
2154 }
2155}
2156
2157/*
Selene Huang31ab4042020-04-29 04:22:39 -07002158 * NewKeyGenerationTest.HmacCheckKeySizes
2159 *
2160 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2161 */
2162TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2163 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2164 if (key_size < 64 || key_size % 8 != 0) {
2165 // To keep this test from being very slow, we only test a random fraction of
2166 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2167 // them, we expect to run ~40 of them in each run.
2168 if (key_size % 8 == 0 || random() % 10 == 0) {
2169 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2170 GenerateKey(AuthorizationSetBuilder()
2171 .HmacKey(key_size)
2172 .Digest(Digest::SHA_2_256)
2173 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2174 << "HMAC key size " << key_size << " invalid";
2175 }
2176 } else {
2177 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2178 .HmacKey(key_size)
2179 .Digest(Digest::SHA_2_256)
2180 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2181 << "Failed to generate HMAC key of size " << key_size;
2182 CheckedDeleteKey();
2183 }
2184 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002185 if (SecLevel() == SecurityLevel::STRONGBOX) {
2186 // STRONGBOX devices must not support keys larger than 512 bits.
2187 size_t key_size = 520;
2188 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2189 GenerateKey(AuthorizationSetBuilder()
2190 .HmacKey(key_size)
2191 .Digest(Digest::SHA_2_256)
2192 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2193 << "HMAC key size " << key_size << " unexpectedly valid";
2194 }
Selene Huang31ab4042020-04-29 04:22:39 -07002195}
2196
2197/*
2198 * NewKeyGenerationTest.HmacCheckMinMacLengths
2199 *
2200 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2201 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2202 * specific MAC length that failed, so reproducing a failed run will be easy.
2203 */
2204TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2205 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2206 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2207 // To keep this test from being very long, we only test a random fraction of
2208 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2209 // we expect to run ~17 of them in each run.
2210 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2211 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2212 GenerateKey(AuthorizationSetBuilder()
2213 .HmacKey(128)
2214 .Digest(Digest::SHA_2_256)
2215 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2216 << "HMAC min mac length " << min_mac_length << " invalid.";
2217 }
2218 } else {
2219 EXPECT_EQ(ErrorCode::OK,
2220 GenerateKey(AuthorizationSetBuilder()
2221 .HmacKey(128)
2222 .Digest(Digest::SHA_2_256)
2223 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2224 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2225 CheckedDeleteKey();
2226 }
2227 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002228
2229 // Minimum MAC length must be no more than 512 bits.
2230 size_t min_mac_length = 520;
2231 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2232 GenerateKey(AuthorizationSetBuilder()
2233 .HmacKey(128)
2234 .Digest(Digest::SHA_2_256)
2235 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2236 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002237}
2238
2239/*
2240 * NewKeyGenerationTest.HmacMultipleDigests
2241 *
2242 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2243 */
2244TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002245 if (SecLevel() == SecurityLevel::STRONGBOX) {
2246 GTEST_SKIP() << "Test not applicable to StrongBox device";
2247 }
Selene Huang31ab4042020-04-29 04:22:39 -07002248
2249 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2250 GenerateKey(AuthorizationSetBuilder()
2251 .HmacKey(128)
2252 .Digest(Digest::SHA1)
2253 .Digest(Digest::SHA_2_256)
2254 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2255}
2256
2257/*
2258 * NewKeyGenerationTest.HmacDigestNone
2259 *
2260 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2261 */
2262TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2263 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2264 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2265 128)));
2266
2267 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2268 GenerateKey(AuthorizationSetBuilder()
2269 .HmacKey(128)
2270 .Digest(Digest::NONE)
2271 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2272}
2273
Selene Huang4f64c222021-04-13 19:54:36 -07002274/*
2275 * NewKeyGenerationTest.AesNoAttestation
2276 *
2277 * Verifies that attestation parameters to AES keys are ignored and generateKey
2278 * will succeed.
2279 */
2280TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2281 auto challenge = "hello";
2282 auto app_id = "foo";
2283
2284 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2285 .Authorization(TAG_NO_AUTH_REQUIRED)
2286 .AesEncryptionKey(128)
2287 .EcbMode()
2288 .Padding(PaddingMode::PKCS7)
2289 .AttestationChallenge(challenge)
2290 .AttestationApplicationId(app_id)));
2291
2292 ASSERT_EQ(cert_chain_.size(), 0);
2293}
2294
2295/*
2296 * NewKeyGenerationTest.TripleDesNoAttestation
2297 *
2298 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2299 * will be successful. No attestation should be generated.
2300 */
2301TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2302 auto challenge = "hello";
2303 auto app_id = "foo";
2304
2305 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2306 .TripleDesEncryptionKey(168)
2307 .BlockMode(BlockMode::ECB)
2308 .Authorization(TAG_NO_AUTH_REQUIRED)
2309 .Padding(PaddingMode::NONE)
2310 .AttestationChallenge(challenge)
2311 .AttestationApplicationId(app_id)));
2312 ASSERT_EQ(cert_chain_.size(), 0);
2313}
2314
Selene Huang31ab4042020-04-29 04:22:39 -07002315INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2316
2317typedef KeyMintAidlTestBase SigningOperationsTest;
2318
2319/*
2320 * SigningOperationsTest.RsaSuccess
2321 *
2322 * Verifies that raw RSA signature operations succeed.
2323 */
2324TEST_P(SigningOperationsTest, RsaSuccess) {
2325 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2326 .RsaSigningKey(2048, 65537)
2327 .Digest(Digest::NONE)
2328 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002329 .Authorization(TAG_NO_AUTH_REQUIRED)
2330 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002331 string message = "12345678901234567890123456789012";
2332 string signature = SignMessage(
2333 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002334 LocalVerifyMessage(message, signature,
2335 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2336}
2337
2338/*
2339 * SigningOperationsTest.RsaAllPaddingsAndDigests
2340 *
2341 * Verifies RSA signature/verification for all padding modes and digests.
2342 */
2343TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2344 auto authorizations = AuthorizationSetBuilder()
2345 .Authorization(TAG_NO_AUTH_REQUIRED)
2346 .RsaSigningKey(2048, 65537)
2347 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2348 .Padding(PaddingMode::NONE)
2349 .Padding(PaddingMode::RSA_PSS)
2350 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2351 .SetDefaultValidity();
2352
2353 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2354
2355 string message(128, 'a');
2356 string corrupt_message(message);
2357 ++corrupt_message[corrupt_message.size() / 2];
2358
2359 for (auto padding :
2360 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2361 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2362 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2363 // Digesting only makes sense with padding.
2364 continue;
2365 }
2366
2367 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2368 // PSS requires digesting.
2369 continue;
2370 }
2371
2372 string signature =
2373 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2374 LocalVerifyMessage(message, signature,
2375 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2376 }
2377 }
Selene Huang31ab4042020-04-29 04:22:39 -07002378}
2379
2380/*
2381 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2382 *
Shawn Willden7f424372021-01-10 18:06:50 -07002383 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002384 */
2385TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2386 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2387 .Authorization(TAG_NO_AUTH_REQUIRED)
2388 .RsaSigningKey(2048, 65537)
2389 .Digest(Digest::NONE)
2390 .Padding(PaddingMode::NONE)
2391 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002392 .Authorization(TAG_APPLICATION_DATA, "appdata")
2393 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002394
2395 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2396
Selene Huang31ab4042020-04-29 04:22:39 -07002397 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2398 Begin(KeyPurpose::SIGN,
2399 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2400 AbortIfNeeded();
2401 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2402 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2403 .Digest(Digest::NONE)
2404 .Padding(PaddingMode::NONE)
2405 .Authorization(TAG_APPLICATION_ID, "clientid")));
2406 AbortIfNeeded();
2407 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2408 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2409 .Digest(Digest::NONE)
2410 .Padding(PaddingMode::NONE)
2411 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2412 AbortIfNeeded();
2413 EXPECT_EQ(ErrorCode::OK,
2414 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2415 .Digest(Digest::NONE)
2416 .Padding(PaddingMode::NONE)
2417 .Authorization(TAG_APPLICATION_DATA, "appdata")
2418 .Authorization(TAG_APPLICATION_ID, "clientid")));
2419 AbortIfNeeded();
2420}
2421
2422/*
2423 * SigningOperationsTest.RsaPssSha256Success
2424 *
2425 * Verifies that RSA-PSS signature operations succeed.
2426 */
2427TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2428 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2429 .RsaSigningKey(2048, 65537)
2430 .Digest(Digest::SHA_2_256)
2431 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002432 .Authorization(TAG_NO_AUTH_REQUIRED)
2433 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002434 // Use large message, which won't work without digesting.
2435 string message(1024, 'a');
2436 string signature = SignMessage(
2437 message,
2438 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2439}
2440
2441/*
2442 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2443 *
2444 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2445 * supports only unpadded operations.
2446 */
2447TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2448 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2449 .RsaSigningKey(2048, 65537)
2450 .Digest(Digest::NONE)
2451 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002452 .Padding(PaddingMode::NONE)
2453 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002454 string message = "12345678901234567890123456789012";
2455 string signature;
2456
2457 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2458 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2459 .Digest(Digest::NONE)
2460 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2461}
2462
2463/*
2464 * SigningOperationsTest.NoUserConfirmation
2465 *
2466 * Verifies that keymint rejects signing operations for keys with
2467 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2468 * presented.
2469 */
2470TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002471 if (SecLevel() == SecurityLevel::STRONGBOX) {
2472 GTEST_SKIP() << "Test not applicable to StrongBox device";
2473 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002474 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2475 .RsaSigningKey(1024, 65537)
2476 .Digest(Digest::NONE)
2477 .Padding(PaddingMode::NONE)
2478 .Authorization(TAG_NO_AUTH_REQUIRED)
2479 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2480 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002481
2482 const string message = "12345678901234567890123456789012";
2483 EXPECT_EQ(ErrorCode::OK,
2484 Begin(KeyPurpose::SIGN,
2485 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2486 string signature;
2487 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2488}
2489
2490/*
2491 * SigningOperationsTest.RsaPkcs1Sha256Success
2492 *
2493 * Verifies that digested RSA-PKCS1 signature operations succeed.
2494 */
2495TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2496 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2497 .RsaSigningKey(2048, 65537)
2498 .Digest(Digest::SHA_2_256)
2499 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002500 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2501 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002502 string message(1024, 'a');
2503 string signature = SignMessage(message, AuthorizationSetBuilder()
2504 .Digest(Digest::SHA_2_256)
2505 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2506}
2507
2508/*
2509 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2510 *
2511 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2512 */
2513TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2514 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2515 .RsaSigningKey(2048, 65537)
2516 .Digest(Digest::NONE)
2517 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002518 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2519 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002520 string message(53, 'a');
2521 string signature = SignMessage(message, AuthorizationSetBuilder()
2522 .Digest(Digest::NONE)
2523 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2524}
2525
2526/*
2527 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2528 *
2529 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2530 * given a too-long message.
2531 */
2532TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2533 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2534 .RsaSigningKey(2048, 65537)
2535 .Digest(Digest::NONE)
2536 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002537 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2538 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002539 string message(257, 'a');
2540
2541 EXPECT_EQ(ErrorCode::OK,
2542 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2543 .Digest(Digest::NONE)
2544 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2545 string signature;
2546 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2547}
2548
2549/*
2550 * SigningOperationsTest.RsaPssSha512TooSmallKey
2551 *
2552 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2553 * used with a key that is too small for the message.
2554 *
2555 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2556 * keymint specification requires that salt_size == digest_size, so the message will be
2557 * digest_size * 2 +
2558 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2559 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2560 * for a 1024-bit key.
2561 */
2562TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01002563 if (SecLevel() == SecurityLevel::STRONGBOX) {
2564 GTEST_SKIP() << "Test not applicable to StrongBox device";
2565 }
Selene Huang31ab4042020-04-29 04:22:39 -07002566 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2567 .RsaSigningKey(1024, 65537)
2568 .Digest(Digest::SHA_2_512)
2569 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002570 .Padding(PaddingMode::RSA_PSS)
2571 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002572 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2573 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2574 .Digest(Digest::SHA_2_512)
2575 .Padding(PaddingMode::RSA_PSS)));
2576}
2577
2578/*
2579 * SigningOperationsTest.RsaNoPaddingTooLong
2580 *
2581 * Verifies that raw RSA signature operations fail with the correct error code when
2582 * given a too-long message.
2583 */
2584TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2585 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2586 .RsaSigningKey(2048, 65537)
2587 .Digest(Digest::NONE)
2588 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002589 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2590 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002591 // One byte too long
2592 string message(2048 / 8 + 1, 'a');
2593 ASSERT_EQ(ErrorCode::OK,
2594 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2595 .Digest(Digest::NONE)
2596 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2597 string result;
2598 ErrorCode finish_error_code = Finish(message, &result);
2599 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2600 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2601
2602 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2603 message = string(128 * 1024, 'a');
2604 ASSERT_EQ(ErrorCode::OK,
2605 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2606 .Digest(Digest::NONE)
2607 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2608 finish_error_code = Finish(message, &result);
2609 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2610 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2611}
2612
2613/*
2614 * SigningOperationsTest.RsaAbort
2615 *
2616 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2617 * test, but the behavior should be algorithm and purpose-independent.
2618 */
2619TEST_P(SigningOperationsTest, RsaAbort) {
2620 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2621 .RsaSigningKey(2048, 65537)
2622 .Digest(Digest::NONE)
2623 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002624 .Padding(PaddingMode::NONE)
2625 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002626
2627 ASSERT_EQ(ErrorCode::OK,
2628 Begin(KeyPurpose::SIGN,
2629 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2630 EXPECT_EQ(ErrorCode::OK, Abort());
2631
2632 // Another abort should fail
2633 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2634
2635 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002636 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002637}
2638
2639/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002640 * SigningOperationsTest.RsaNonUniqueParams
2641 *
2642 * Verifies that an operation with multiple padding modes is rejected.
2643 */
2644TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2645 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2646 .RsaSigningKey(2048, 65537)
2647 .Digest(Digest::NONE)
2648 .Digest(Digest::SHA1)
2649 .Authorization(TAG_NO_AUTH_REQUIRED)
2650 .Padding(PaddingMode::NONE)
2651 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2652 .SetDefaultValidity()));
2653
2654 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2655 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2656 .Digest(Digest::NONE)
2657 .Padding(PaddingMode::NONE)
2658 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2659
Tommy Chiuc93c4392021-05-11 18:36:50 +08002660 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2661 .Digest(Digest::NONE)
2662 .Digest(Digest::SHA1)
2663 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2664 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002665
2666 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2667 Begin(KeyPurpose::SIGN,
2668 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2669}
2670
2671/*
Selene Huang31ab4042020-04-29 04:22:39 -07002672 * SigningOperationsTest.RsaUnsupportedPadding
2673 *
2674 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2675 * with a padding mode inappropriate for RSA.
2676 */
2677TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2678 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2679 .RsaSigningKey(2048, 65537)
2680 .Authorization(TAG_NO_AUTH_REQUIRED)
2681 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002682 .Padding(PaddingMode::PKCS7)
2683 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002684 ASSERT_EQ(
2685 ErrorCode::UNSUPPORTED_PADDING_MODE,
2686 Begin(KeyPurpose::SIGN,
2687 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002688 CheckedDeleteKey();
2689
2690 ASSERT_EQ(ErrorCode::OK,
2691 GenerateKey(
2692 AuthorizationSetBuilder()
2693 .RsaSigningKey(2048, 65537)
2694 .Authorization(TAG_NO_AUTH_REQUIRED)
2695 .Digest(Digest::SHA_2_256 /* supported digest */)
2696 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2697 .SetDefaultValidity()));
2698 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2699 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2700 .Digest(Digest::SHA_2_256)
2701 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002702}
2703
2704/*
2705 * SigningOperationsTest.RsaPssNoDigest
2706 *
2707 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2708 */
2709TEST_P(SigningOperationsTest, RsaNoDigest) {
2710 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2711 .RsaSigningKey(2048, 65537)
2712 .Authorization(TAG_NO_AUTH_REQUIRED)
2713 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002714 .Padding(PaddingMode::RSA_PSS)
2715 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002716 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2717 Begin(KeyPurpose::SIGN,
2718 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2719
2720 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2721 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2722}
2723
2724/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002725 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002726 *
2727 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2728 * supported in some cases (as validated in other tests), but a mode must be specified.
2729 */
2730TEST_P(SigningOperationsTest, RsaNoPadding) {
2731 // Padding must be specified
2732 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2733 .RsaKey(2048, 65537)
2734 .Authorization(TAG_NO_AUTH_REQUIRED)
2735 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002736 .Digest(Digest::NONE)
2737 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002738 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2739 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2740}
2741
2742/*
2743 * SigningOperationsTest.RsaShortMessage
2744 *
2745 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2746 */
2747TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2748 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2749 .Authorization(TAG_NO_AUTH_REQUIRED)
2750 .RsaSigningKey(2048, 65537)
2751 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002752 .Padding(PaddingMode::NONE)
2753 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002754
2755 // Barely shorter
2756 string message(2048 / 8 - 1, 'a');
2757 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2758
2759 // Much shorter
2760 message = "a";
2761 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2762}
2763
2764/*
2765 * SigningOperationsTest.RsaSignWithEncryptionKey
2766 *
2767 * Verifies that RSA encryption keys cannot be used to sign.
2768 */
2769TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2770 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2771 .Authorization(TAG_NO_AUTH_REQUIRED)
2772 .RsaEncryptionKey(2048, 65537)
2773 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002774 .Padding(PaddingMode::NONE)
2775 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002776 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2777 Begin(KeyPurpose::SIGN,
2778 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2779}
2780
2781/*
2782 * SigningOperationsTest.RsaSignTooLargeMessage
2783 *
2784 * Verifies that attempting a raw signature of a message which is the same length as the key,
2785 * but numerically larger than the public modulus, fails with the correct error.
2786 */
2787TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2788 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2789 .Authorization(TAG_NO_AUTH_REQUIRED)
2790 .RsaSigningKey(2048, 65537)
2791 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002792 .Padding(PaddingMode::NONE)
2793 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002794
2795 // Largest possible message will always be larger than the public modulus.
2796 string message(2048 / 8, static_cast<char>(0xff));
2797 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2798 .Authorization(TAG_NO_AUTH_REQUIRED)
2799 .Digest(Digest::NONE)
2800 .Padding(PaddingMode::NONE)));
2801 string signature;
2802 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2803}
2804
2805/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01002806 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2807 *
2808 * Verifies ECDSA signature/verification for all digests and curves.
2809 */
2810TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2811 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2812
2813 string message = "1234567890";
2814 string corrupt_message = "2234567890";
2815 for (auto curve : ValidCurves()) {
2816 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2817 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2818 .Authorization(TAG_NO_AUTH_REQUIRED)
2819 .EcdsaSigningKey(curve)
2820 .Digest(digests)
2821 .SetDefaultValidity());
2822 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2823 if (error != ErrorCode::OK) {
2824 continue;
2825 }
2826
2827 for (auto digest : digests) {
2828 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2829 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2830 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2831 }
2832
2833 auto rc = DeleteKey();
2834 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2835 }
2836}
2837
2838/*
Selene Huang31ab4042020-04-29 04:22:39 -07002839 * SigningOperationsTest.EcdsaAllCurves
2840 *
2841 * Verifies that ECDSA operations succeed with all possible curves.
2842 */
2843TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2844 for (auto curve : ValidCurves()) {
2845 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2846 .Authorization(TAG_NO_AUTH_REQUIRED)
2847 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002848 .Digest(Digest::SHA_2_256)
2849 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002850 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2851 if (error != ErrorCode::OK) continue;
2852
2853 string message(1024, 'a');
2854 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2855 CheckedDeleteKey();
2856 }
2857}
2858
2859/*
2860 * SigningOperationsTest.EcdsaNoDigestHugeData
2861 *
2862 * Verifies that ECDSA operations support very large messages, even without digesting. This
2863 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2864 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2865 * the framework.
2866 */
2867TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2868 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2869 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002870 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002871 .Digest(Digest::NONE)
2872 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002873 string message(1 * 1024, 'a');
2874 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2875}
2876
2877/*
2878 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2879 *
2880 * Verifies that using an EC key requires the correct app ID/data.
2881 */
2882TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2883 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2884 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002885 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002886 .Digest(Digest::NONE)
2887 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002888 .Authorization(TAG_APPLICATION_DATA, "appdata")
2889 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002890
2891 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2892
Selene Huang31ab4042020-04-29 04:22:39 -07002893 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2894 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2895 AbortIfNeeded();
2896 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2897 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2898 .Digest(Digest::NONE)
2899 .Authorization(TAG_APPLICATION_ID, "clientid")));
2900 AbortIfNeeded();
2901 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2902 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2903 .Digest(Digest::NONE)
2904 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2905 AbortIfNeeded();
2906 EXPECT_EQ(ErrorCode::OK,
2907 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2908 .Digest(Digest::NONE)
2909 .Authorization(TAG_APPLICATION_DATA, "appdata")
2910 .Authorization(TAG_APPLICATION_ID, "clientid")));
2911 AbortIfNeeded();
2912}
2913
2914/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002915 * SigningOperationsTest.EcdsaIncompatibleDigest
2916 *
2917 * Verifies that using an EC key requires compatible digest.
2918 */
2919TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2920 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2921 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002922 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002923 .Digest(Digest::NONE)
2924 .Digest(Digest::SHA1)
2925 .SetDefaultValidity()));
2926 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2927 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2928 AbortIfNeeded();
2929}
2930
2931/*
Selene Huang31ab4042020-04-29 04:22:39 -07002932 * SigningOperationsTest.AesEcbSign
2933 *
2934 * Verifies that attempts to use AES keys to sign fail in the correct way.
2935 */
2936TEST_P(SigningOperationsTest, AesEcbSign) {
2937 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2938 .Authorization(TAG_NO_AUTH_REQUIRED)
2939 .SigningKey()
2940 .AesEncryptionKey(128)
2941 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2942
2943 AuthorizationSet out_params;
2944 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2945 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2946 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2947 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2948}
2949
2950/*
2951 * SigningOperationsTest.HmacAllDigests
2952 *
2953 * Verifies that HMAC works with all digests.
2954 */
2955TEST_P(SigningOperationsTest, HmacAllDigests) {
2956 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2957 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2958 .Authorization(TAG_NO_AUTH_REQUIRED)
2959 .HmacKey(128)
2960 .Digest(digest)
2961 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2962 << "Failed to create HMAC key with digest " << digest;
2963 string message = "12345678901234567890123456789012";
2964 string signature = MacMessage(message, digest, 160);
2965 EXPECT_EQ(160U / 8U, signature.size())
2966 << "Failed to sign with HMAC key with digest " << digest;
2967 CheckedDeleteKey();
2968 }
2969}
2970
2971/*
2972 * SigningOperationsTest.HmacSha256TooLargeMacLength
2973 *
2974 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2975 * digest size.
2976 */
2977TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2978 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2979 .Authorization(TAG_NO_AUTH_REQUIRED)
2980 .HmacKey(128)
2981 .Digest(Digest::SHA_2_256)
2982 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2983 AuthorizationSet output_params;
2984 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2985 AuthorizationSetBuilder()
2986 .Digest(Digest::SHA_2_256)
2987 .Authorization(TAG_MAC_LENGTH, 264),
2988 &output_params));
2989}
2990
2991/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002992 * SigningOperationsTest.HmacSha256InvalidMacLength
2993 *
2994 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2995 * not a multiple of 8.
2996 */
2997TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2998 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2999 .Authorization(TAG_NO_AUTH_REQUIRED)
3000 .HmacKey(128)
3001 .Digest(Digest::SHA_2_256)
3002 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3003 AuthorizationSet output_params;
3004 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3005 AuthorizationSetBuilder()
3006 .Digest(Digest::SHA_2_256)
3007 .Authorization(TAG_MAC_LENGTH, 161),
3008 &output_params));
3009}
3010
3011/*
Selene Huang31ab4042020-04-29 04:22:39 -07003012 * SigningOperationsTest.HmacSha256TooSmallMacLength
3013 *
3014 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3015 * specified minimum MAC length.
3016 */
3017TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3018 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3019 .Authorization(TAG_NO_AUTH_REQUIRED)
3020 .HmacKey(128)
3021 .Digest(Digest::SHA_2_256)
3022 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3023 AuthorizationSet output_params;
3024 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3025 AuthorizationSetBuilder()
3026 .Digest(Digest::SHA_2_256)
3027 .Authorization(TAG_MAC_LENGTH, 120),
3028 &output_params));
3029}
3030
3031/*
3032 * SigningOperationsTest.HmacRfc4231TestCase3
3033 *
3034 * Validates against the test vectors from RFC 4231 test case 3.
3035 */
3036TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3037 string key(20, 0xaa);
3038 string message(50, 0xdd);
3039 uint8_t sha_224_expected[] = {
3040 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3041 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3042 };
3043 uint8_t sha_256_expected[] = {
3044 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3045 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3046 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3047 };
3048 uint8_t sha_384_expected[] = {
3049 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3050 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3051 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3052 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3053 };
3054 uint8_t sha_512_expected[] = {
3055 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3056 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3057 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3058 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3059 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3060 };
3061
3062 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3063 if (SecLevel() != SecurityLevel::STRONGBOX) {
3064 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3065 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3066 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3067 }
3068}
3069
3070/*
3071 * SigningOperationsTest.HmacRfc4231TestCase5
3072 *
3073 * Validates against the test vectors from RFC 4231 test case 5.
3074 */
3075TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3076 string key(20, 0x0c);
3077 string message = "Test With Truncation";
3078
3079 uint8_t sha_224_expected[] = {
3080 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3081 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3082 };
3083 uint8_t sha_256_expected[] = {
3084 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3085 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3086 };
3087 uint8_t sha_384_expected[] = {
3088 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3089 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3090 };
3091 uint8_t sha_512_expected[] = {
3092 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3093 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3094 };
3095
3096 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3097 if (SecLevel() != SecurityLevel::STRONGBOX) {
3098 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3099 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3100 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3101 }
3102}
3103
3104INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3105
3106typedef KeyMintAidlTestBase VerificationOperationsTest;
3107
3108/*
Selene Huang31ab4042020-04-29 04:22:39 -07003109 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3110 *
3111 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3112 */
3113TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3114 string key_material = "HelloThisIsAKey";
3115
3116 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003117 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003118 EXPECT_EQ(ErrorCode::OK,
3119 ImportKey(AuthorizationSetBuilder()
3120 .Authorization(TAG_NO_AUTH_REQUIRED)
3121 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3122 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3123 .Digest(Digest::SHA_2_256)
3124 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3125 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3126 EXPECT_EQ(ErrorCode::OK,
3127 ImportKey(AuthorizationSetBuilder()
3128 .Authorization(TAG_NO_AUTH_REQUIRED)
3129 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3130 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3131 .Digest(Digest::SHA_2_256)
3132 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3133 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3134
3135 string message = "This is a message.";
3136 string signature = SignMessage(
3137 signing_key, message,
3138 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3139
3140 // Signing key should not work.
3141 AuthorizationSet out_params;
3142 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3143 Begin(KeyPurpose::VERIFY, signing_key,
3144 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3145
3146 // Verification key should work.
3147 VerifyMessage(verification_key, message, signature,
3148 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3149
3150 CheckedDeleteKey(&signing_key);
3151 CheckedDeleteKey(&verification_key);
3152}
3153
Prashant Patildec9fdc2021-12-08 15:25:47 +00003154/*
3155 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3156 *
3157 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3158 */
3159TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3160 string key_material = "HelloThisIsAKey";
3161
3162 vector<uint8_t> signing_key, verification_key;
3163 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3164 EXPECT_EQ(ErrorCode::OK,
3165 ImportKey(AuthorizationSetBuilder()
3166 .Authorization(TAG_NO_AUTH_REQUIRED)
3167 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3168 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3169 .Digest(Digest::SHA_2_256)
3170 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3171 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3172 EXPECT_EQ(ErrorCode::OK,
3173 ImportKey(AuthorizationSetBuilder()
3174 .Authorization(TAG_NO_AUTH_REQUIRED)
3175 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3176 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3177 .Digest(Digest::SHA_2_256)
3178 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3179 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3180
3181 string message = "This is a message.";
3182 string signature = SignMessage(
3183 signing_key, message,
3184 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3185
3186 AuthorizationSet begin_out_params;
3187 ASSERT_EQ(ErrorCode::OK,
3188 Begin(KeyPurpose::VERIFY, verification_key,
3189 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3190
3191 string corruptMessage = "This is b message."; // Corrupted message
3192 string output;
3193 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3194
3195 ASSERT_EQ(ErrorCode::OK,
3196 Begin(KeyPurpose::VERIFY, verification_key,
3197 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3198
3199 signature[0] += 1; // Corrupt a signature
3200 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3201
3202 CheckedDeleteKey(&signing_key);
3203 CheckedDeleteKey(&verification_key);
3204}
3205
Selene Huang31ab4042020-04-29 04:22:39 -07003206INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3207
3208typedef KeyMintAidlTestBase ExportKeyTest;
3209
3210/*
3211 * ExportKeyTest.RsaUnsupportedKeyFormat
3212 *
3213 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3214 */
3215// TODO(seleneh) add ExportKey to GenerateKey
3216// check result
3217
3218class ImportKeyTest : public KeyMintAidlTestBase {
3219 public:
3220 template <TagType tag_type, Tag tag, typename ValueT>
3221 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3222 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003223 for (auto& entry : key_characteristics_) {
3224 if (entry.securityLevel == SecLevel()) {
3225 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3226 << "Tag " << tag << " with value " << expected
3227 << " not found at security level" << entry.securityLevel;
3228 } else {
3229 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3230 << "Tag " << tag << " found at security level " << entry.securityLevel;
3231 }
Selene Huang31ab4042020-04-29 04:22:39 -07003232 }
3233 }
3234
3235 void CheckOrigin() {
3236 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003237 // Origin isn't a crypto param, but it always lives with them.
3238 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003239 }
3240};
3241
3242/*
3243 * ImportKeyTest.RsaSuccess
3244 *
3245 * Verifies that importing and using an RSA key pair works correctly.
3246 */
3247TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003248 uint32_t key_size;
3249 string key;
3250
3251 if (SecLevel() == SecurityLevel::STRONGBOX) {
3252 key_size = 2048;
3253 key = rsa_2048_key;
3254 } else {
3255 key_size = 1024;
3256 key = rsa_key;
3257 }
3258
Selene Huang31ab4042020-04-29 04:22:39 -07003259 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3260 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003261 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003262 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003263 .Padding(PaddingMode::RSA_PSS)
3264 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003265 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003266
3267 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003268 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003269 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3270 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3271 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3272 CheckOrigin();
3273
3274 string message(1024 / 8, 'a');
3275 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3276 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003277 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003278}
3279
3280/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003281 * ImportKeyTest.RsaSuccessWithoutParams
3282 *
3283 * Verifies that importing and using an RSA key pair without specifying parameters
3284 * works correctly.
3285 */
3286TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3287 uint32_t key_size;
3288 string key;
3289
3290 if (SecLevel() == SecurityLevel::STRONGBOX) {
3291 key_size = 2048;
3292 key = rsa_2048_key;
3293 } else {
3294 key_size = 1024;
3295 key = rsa_key;
3296 }
3297
3298 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3299 .Authorization(TAG_NO_AUTH_REQUIRED)
3300 .SigningKey()
3301 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3302 .Digest(Digest::SHA_2_256)
3303 .Padding(PaddingMode::RSA_PSS)
3304 .SetDefaultValidity(),
3305 KeyFormat::PKCS8, key));
3306
3307 // Key size and public exponent are determined from the imported key material.
3308 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3309 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3310
3311 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3312 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3313 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3314 CheckOrigin();
3315
3316 string message(1024 / 8, 'a');
3317 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3318 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003319 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003320}
3321
3322/*
Selene Huang31ab4042020-04-29 04:22:39 -07003323 * ImportKeyTest.RsaKeySizeMismatch
3324 *
3325 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3326 * correct way.
3327 */
3328TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3329 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3330 ImportKey(AuthorizationSetBuilder()
3331 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3332 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003333 .Padding(PaddingMode::NONE)
3334 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003335 KeyFormat::PKCS8, rsa_key));
3336}
3337
3338/*
3339 * ImportKeyTest.RsaPublicExponentMismatch
3340 *
3341 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3342 * fails in the correct way.
3343 */
3344TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3345 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3346 ImportKey(AuthorizationSetBuilder()
3347 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3348 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003349 .Padding(PaddingMode::NONE)
3350 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003351 KeyFormat::PKCS8, rsa_key));
3352}
3353
3354/*
3355 * ImportKeyTest.EcdsaSuccess
3356 *
3357 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3358 */
3359TEST_P(ImportKeyTest, EcdsaSuccess) {
3360 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3361 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003362 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003363 .Digest(Digest::SHA_2_256)
3364 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003365 KeyFormat::PKCS8, ec_256_key));
3366
3367 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003368 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3369 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3370
3371 CheckOrigin();
3372
3373 string message(32, 'a');
3374 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3375 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003376 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003377}
3378
3379/*
3380 * ImportKeyTest.EcdsaP256RFC5915Success
3381 *
3382 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3383 * correctly.
3384 */
3385TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3386 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3387 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003388 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003389 .Digest(Digest::SHA_2_256)
3390 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003391 KeyFormat::PKCS8, ec_256_key_rfc5915));
3392
3393 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003394 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3395 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3396
3397 CheckOrigin();
3398
3399 string message(32, 'a');
3400 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3401 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003402 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003403}
3404
3405/*
3406 * ImportKeyTest.EcdsaP256SEC1Success
3407 *
3408 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3409 */
3410TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3411 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3412 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003413 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003414 .Digest(Digest::SHA_2_256)
3415 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003416 KeyFormat::PKCS8, ec_256_key_sec1));
3417
3418 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003419 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3420 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3421
3422 CheckOrigin();
3423
3424 string message(32, 'a');
3425 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3426 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003427 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003428}
3429
3430/*
3431 * ImportKeyTest.Ecdsa521Success
3432 *
3433 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3434 */
3435TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01003436 if (SecLevel() == SecurityLevel::STRONGBOX) {
3437 GTEST_SKIP() << "Test not applicable to StrongBox device";
3438 }
Selene Huang31ab4042020-04-29 04:22:39 -07003439 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3440 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003441 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003442 .Digest(Digest::SHA_2_256)
3443 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003444 KeyFormat::PKCS8, ec_521_key));
3445
3446 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003447 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3448 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3449 CheckOrigin();
3450
3451 string message(32, 'a');
3452 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3453 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003454 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003455}
3456
3457/*
Selene Huang31ab4042020-04-29 04:22:39 -07003458 * ImportKeyTest.EcdsaCurveMismatch
3459 *
3460 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3461 * the correct way.
3462 */
3463TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3464 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3465 ImportKey(AuthorizationSetBuilder()
3466 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003467 .Digest(Digest::NONE)
3468 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003469 KeyFormat::PKCS8, ec_256_key));
3470}
3471
3472/*
3473 * ImportKeyTest.AesSuccess
3474 *
3475 * Verifies that importing and using an AES key works.
3476 */
3477TEST_P(ImportKeyTest, AesSuccess) {
3478 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3479 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3480 .Authorization(TAG_NO_AUTH_REQUIRED)
3481 .AesEncryptionKey(key.size() * 8)
3482 .EcbMode()
3483 .Padding(PaddingMode::PKCS7),
3484 KeyFormat::RAW, key));
3485
3486 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3487 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3488 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3489 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3490 CheckOrigin();
3491
3492 string message = "Hello World!";
3493 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3494 string ciphertext = EncryptMessage(message, params);
3495 string plaintext = DecryptMessage(ciphertext, params);
3496 EXPECT_EQ(message, plaintext);
3497}
3498
3499/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003500 * ImportKeyTest.AesFailure
3501 *
3502 * Verifies that importing an invalid AES key fails.
3503 */
3504TEST_P(ImportKeyTest, AesFailure) {
3505 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3506 uint32_t bitlen = key.size() * 8;
3507 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003508 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003509 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003510 .Authorization(TAG_NO_AUTH_REQUIRED)
3511 .AesEncryptionKey(key_size)
3512 .EcbMode()
3513 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003514 KeyFormat::RAW, key);
3515 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003516 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3517 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003518 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003519
3520 // Explicit key size matches that of the provided key, but it's not a valid size.
3521 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3522 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3523 ImportKey(AuthorizationSetBuilder()
3524 .Authorization(TAG_NO_AUTH_REQUIRED)
3525 .AesEncryptionKey(long_key.size() * 8)
3526 .EcbMode()
3527 .Padding(PaddingMode::PKCS7),
3528 KeyFormat::RAW, long_key));
3529 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3530 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3531 ImportKey(AuthorizationSetBuilder()
3532 .Authorization(TAG_NO_AUTH_REQUIRED)
3533 .AesEncryptionKey(short_key.size() * 8)
3534 .EcbMode()
3535 .Padding(PaddingMode::PKCS7),
3536 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003537}
3538
3539/*
3540 * ImportKeyTest.TripleDesSuccess
3541 *
3542 * Verifies that importing and using a 3DES key works.
3543 */
3544TEST_P(ImportKeyTest, TripleDesSuccess) {
3545 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3546 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3547 .Authorization(TAG_NO_AUTH_REQUIRED)
3548 .TripleDesEncryptionKey(168)
3549 .EcbMode()
3550 .Padding(PaddingMode::PKCS7),
3551 KeyFormat::RAW, key));
3552
3553 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3554 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3555 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3556 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3557 CheckOrigin();
3558
3559 string message = "Hello World!";
3560 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3561 string ciphertext = EncryptMessage(message, params);
3562 string plaintext = DecryptMessage(ciphertext, params);
3563 EXPECT_EQ(message, plaintext);
3564}
3565
3566/*
3567 * ImportKeyTest.TripleDesFailure
3568 *
3569 * Verifies that importing an invalid 3DES key fails.
3570 */
3571TEST_P(ImportKeyTest, TripleDesFailure) {
3572 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003573 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003574 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003575 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003576 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003577 .Authorization(TAG_NO_AUTH_REQUIRED)
3578 .TripleDesEncryptionKey(key_size)
3579 .EcbMode()
3580 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003581 KeyFormat::RAW, key);
3582 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003583 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3584 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003585 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003586 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003587 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003588 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3589 ImportKey(AuthorizationSetBuilder()
3590 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003591 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003592 .EcbMode()
3593 .Padding(PaddingMode::PKCS7),
3594 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003595 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003596 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3597 ImportKey(AuthorizationSetBuilder()
3598 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003599 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003600 .EcbMode()
3601 .Padding(PaddingMode::PKCS7),
3602 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003603}
3604
3605/*
3606 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003607 *
3608 * Verifies that importing and using an HMAC key works.
3609 */
3610TEST_P(ImportKeyTest, HmacKeySuccess) {
3611 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3612 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3613 .Authorization(TAG_NO_AUTH_REQUIRED)
3614 .HmacKey(key.size() * 8)
3615 .Digest(Digest::SHA_2_256)
3616 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3617 KeyFormat::RAW, key));
3618
3619 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3620 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3621 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3622 CheckOrigin();
3623
3624 string message = "Hello World!";
3625 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3626 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3627}
3628
3629INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3630
3631auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003632 // IKeyMintDevice.aidl
3633 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3634 "020100" // INTEGER length 1 value 0x00 (version)
3635 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3636 "934bf94e2aa28a3f83c9f79297250262"
3637 "fbe3276b5a1c91159bbfa3ef8957aac8"
3638 "4b59b30b455a79c2973480823d8b3863"
3639 "c3deef4a8e243590268d80e18751a0e1"
3640 "30f67ce6a1ace9f79b95e097474febc9"
3641 "81195b1d13a69086c0863f66a7b7fdb4"
3642 "8792227b1ac5e2489febdf087ab54864"
3643 "83033a6f001ca5d1ec1e27f5c30f4cec"
3644 "2642074a39ae68aee552e196627a8e3d"
3645 "867e67a8c01b11e75f13cca0a97ab668"
3646 "b50cda07a8ecb7cd8e3dd7009c963653"
3647 "4f6f239cffe1fc8daa466f78b676c711"
3648 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3649 "99b801597d5220e307eaa5bee507fb94"
3650 "d1fa69f9e519b2de315bac92c36f2ea1"
3651 "fa1df4478c0ddedeae8c70e0233cd098"
3652 "040c" // OCTET STRING length 0x0c (initializationVector)
3653 "d796b02c370f1fa4cc0124f1"
3654 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3655 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3656 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3657 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3658 "3106" // SET length 0x06
3659 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3660 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3661 // } end SET
3662 // } end [1]
3663 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3664 "020120" // INTEGER length 1 value 0x20 (AES)
3665 // } end [2]
3666 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3667 "02020100" // INTEGER length 2 value 0x100
3668 // } end [3]
3669 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3670 "3103" // SET length 0x03 {
3671 "020101" // INTEGER length 1 value 0x01 (ECB)
3672 // } end SET
3673 // } end [4]
3674 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3675 "3103" // SET length 0x03 {
3676 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3677 // } end SET
3678 // } end [5]
3679 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3680 // (noAuthRequired)
3681 "0500" // NULL
3682 // } end [503]
3683 // } end SEQUENCE (AuthorizationList)
3684 // } end SEQUENCE (KeyDescription)
3685 "0420" // OCTET STRING length 0x20 (encryptedKey)
3686 "ccd540855f833a5e1480bfd2d36faf3a"
3687 "eee15df5beabe2691bc82dde2a7aa910"
3688 "0410" // OCTET STRING length 0x10 (tag)
3689 "64c9f689c60ff6223ab6e6999e0eb6e5"
3690 // } SEQUENCE (SecureKeyWrapper)
3691);
Selene Huang31ab4042020-04-29 04:22:39 -07003692
3693auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003694 // IKeyMintDevice.aidl
3695 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3696 "020100" // INTEGER length 1 value 0x00 (version)
3697 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3698 "aad93ed5924f283b4bb5526fbe7a1412"
3699 "f9d9749ec30db9062b29e574a8546f33"
3700 "c88732452f5b8e6a391ee76c39ed1712"
3701 "c61d8df6213dec1cffbc17a8c6d04c7b"
3702 "30893d8daa9b2015213e219468215532"
3703 "07f8f9931c4caba23ed3bee28b36947e"
3704 "47f10e0a5c3dc51c988a628daad3e5e1"
3705 "f4005e79c2d5a96c284b4b8d7e4948f3"
3706 "31e5b85dd5a236f85579f3ea1d1b8484"
3707 "87470bdb0ab4f81a12bee42c99fe0df4"
3708 "bee3759453e69ad1d68a809ce06b949f"
3709 "7694a990429b2fe81e066ff43e56a216"
3710 "02db70757922a4bcc23ab89f1e35da77"
3711 "586775f423e519c2ea394caf48a28d0c"
3712 "8020f1dcf6b3a68ec246f615ae96dae9"
3713 "a079b1f6eb959033c1af5c125fd94168"
3714 "040c" // OCTET STRING length 0x0c (initializationVector)
3715 "6d9721d08589581ab49204a3"
3716 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3717 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3718 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3719 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3720 "3106" // SET length 0x06
3721 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3722 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3723 // } end SET
3724 // } end [1]
3725 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3726 "020120" // INTEGER length 1 value 0x20 (AES)
3727 // } end [2]
3728 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3729 "02020100" // INTEGER length 2 value 0x100
3730 // } end [3]
3731 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3732 "3103" // SET length 0x03 {
3733 "020101" // INTEGER length 1 value 0x01 (ECB)
3734 // } end SET
3735 // } end [4]
3736 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3737 "3103" // SET length 0x03 {
3738 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3739 // } end SET
3740 // } end [5]
3741 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3742 // (noAuthRequired)
3743 "0500" // NULL
3744 // } end [503]
3745 // } end SEQUENCE (AuthorizationList)
3746 // } end SEQUENCE (KeyDescription)
3747 "0420" // OCTET STRING length 0x20 (encryptedKey)
3748 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3749 "c20d1f99a9a024a76f35c8e2cab9b68d"
3750 "0410" // OCTET STRING length 0x10 (tag)
3751 "2560c70109ae67c030f00b98b512a670"
3752 // } SEQUENCE (SecureKeyWrapper)
3753);
Selene Huang31ab4042020-04-29 04:22:39 -07003754
3755auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003756 // RFC 5208 s5
3757 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3758 "020100" // INTEGER length 1 value 0x00 (version)
3759 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3760 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3761 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3762 "0500" // NULL (parameters)
3763 // } SEQUENCE (AlgorithmIdentifier)
3764 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3765 // RFC 8017 A.1.2
3766 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3767 "020100" // INTEGER length 1 value 0x00 (version)
3768 "02820101" // INTEGER length 0x0101 (modulus) value...
3769 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3770 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3771 "7b06e673a837313d56b1c725150a3fef" // 0x30
3772 "86acbddc41bb759c2854eae32d35841e" // 0x40
3773 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3774 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3775 "312d7bd5921ffaea1347c157406fef71" // 0x70
3776 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3777 "f4645c11f5c1374c3886427411c44979" // 0x90
3778 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3779 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3780 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3781 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3782 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3783 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3784 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3785 "55" // 0x101
3786 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3787 "02820100" // INTEGER length 0x100 (privateExponent) value...
3788 "431447b6251908112b1ee76f99f3711a" // 0x10
3789 "52b6630960046c2de70de188d833f8b8" // 0x20
3790 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3791 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3792 "e710b630a03adc683b5d2c43080e52be" // 0x50
3793 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3794 "822bccff087d63c940ba8a45f670feb2" // 0x70
3795 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3796 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3797 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3798 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3799 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3800 "52659d5a5ba05b663737a8696281865b" // 0xd0
3801 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3802 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3803 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3804 "028181" // INTEGER length 0x81 (prime1) value...
3805 "00de392e18d682c829266cc3454e1d61" // 0x10
3806 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3807 "ff841be5bac82a164c5970007047b8c5" // 0x30
3808 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3809 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3810 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3811 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3812 "9e91346130748a6e3c124f9149d71c74" // 0x80
3813 "35"
3814 "028181" // INTEGER length 0x81 (prime2) value...
3815 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3816 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3817 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3818 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3819 "9ed39a2d934c880440aed8832f984316" // 0x50
3820 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3821 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3822 "b880677c068e1be936e81288815252a8" // 0x80
3823 "a1"
3824 "028180" // INTEGER length 0x80 (exponent1) value...
3825 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3826 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3827 "5a063212a4f105a3764743e53281988a" // 0x30
3828 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3829 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3830 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3831 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3832 "4719d6e2b9439823719cd08bcd031781" // 0x80
3833 "028181" // INTEGER length 0x81 (exponent2) value...
3834 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3835 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3836 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3837 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3838 "1254186af30b22c10582a8a43e34fe94" // 0x50
3839 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3840 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3841 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3842 "61"
3843 "028181" // INTEGER length 0x81 (coefficient) value...
3844 "00c931617c77829dfb1270502be9195c" // 0x10
3845 "8f2830885f57dba869536811e6864236" // 0x20
3846 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3847 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3848 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3849 "959356210723287b0affcc9f727044d4" // 0x60
3850 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3851 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3852 "22"
3853 // } SEQUENCE
3854 // } SEQUENCE ()
3855);
Selene Huang31ab4042020-04-29 04:22:39 -07003856
3857string zero_masking_key =
3858 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3859string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3860
3861class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3862
3863TEST_P(ImportWrappedKeyTest, Success) {
3864 auto wrapping_key_desc = AuthorizationSetBuilder()
3865 .RsaEncryptionKey(2048, 65537)
3866 .Digest(Digest::SHA_2_256)
3867 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003868 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3869 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003870
3871 ASSERT_EQ(ErrorCode::OK,
3872 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3873 AuthorizationSetBuilder()
3874 .Digest(Digest::SHA_2_256)
3875 .Padding(PaddingMode::RSA_OAEP)));
3876
3877 string message = "Hello World!";
3878 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3879 string ciphertext = EncryptMessage(message, params);
3880 string plaintext = DecryptMessage(ciphertext, params);
3881 EXPECT_EQ(message, plaintext);
3882}
3883
David Drysdaled2cc8c22021-04-15 13:29:45 +01003884/*
3885 * ImportWrappedKeyTest.SuccessSidsIgnored
3886 *
3887 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3888 * include Tag:USER_SECURE_ID.
3889 */
3890TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3891 auto wrapping_key_desc = AuthorizationSetBuilder()
3892 .RsaEncryptionKey(2048, 65537)
3893 .Digest(Digest::SHA_2_256)
3894 .Padding(PaddingMode::RSA_OAEP)
3895 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3896 .SetDefaultValidity();
3897
3898 int64_t password_sid = 42;
3899 int64_t biometric_sid = 24;
3900 ASSERT_EQ(ErrorCode::OK,
3901 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3902 AuthorizationSetBuilder()
3903 .Digest(Digest::SHA_2_256)
3904 .Padding(PaddingMode::RSA_OAEP),
3905 password_sid, biometric_sid));
3906
3907 string message = "Hello World!";
3908 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3909 string ciphertext = EncryptMessage(message, params);
3910 string plaintext = DecryptMessage(ciphertext, params);
3911 EXPECT_EQ(message, plaintext);
3912}
3913
Selene Huang31ab4042020-04-29 04:22:39 -07003914TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3915 auto wrapping_key_desc = AuthorizationSetBuilder()
3916 .RsaEncryptionKey(2048, 65537)
3917 .Digest(Digest::SHA_2_256)
3918 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003919 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3920 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003921
3922 ASSERT_EQ(ErrorCode::OK,
3923 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3924 AuthorizationSetBuilder()
3925 .Digest(Digest::SHA_2_256)
3926 .Padding(PaddingMode::RSA_OAEP)));
3927}
3928
3929TEST_P(ImportWrappedKeyTest, WrongMask) {
3930 auto wrapping_key_desc = AuthorizationSetBuilder()
3931 .RsaEncryptionKey(2048, 65537)
3932 .Digest(Digest::SHA_2_256)
3933 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003934 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3935 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003936
3937 ASSERT_EQ(
3938 ErrorCode::VERIFICATION_FAILED,
3939 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3940 AuthorizationSetBuilder()
3941 .Digest(Digest::SHA_2_256)
3942 .Padding(PaddingMode::RSA_OAEP)));
3943}
3944
3945TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3946 auto wrapping_key_desc = AuthorizationSetBuilder()
3947 .RsaEncryptionKey(2048, 65537)
3948 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003949 .Padding(PaddingMode::RSA_OAEP)
3950 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003951
3952 ASSERT_EQ(
3953 ErrorCode::INCOMPATIBLE_PURPOSE,
3954 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3955 AuthorizationSetBuilder()
3956 .Digest(Digest::SHA_2_256)
3957 .Padding(PaddingMode::RSA_OAEP)));
3958}
3959
David Drysdaled2cc8c22021-04-15 13:29:45 +01003960TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3961 auto wrapping_key_desc = AuthorizationSetBuilder()
3962 .RsaEncryptionKey(2048, 65537)
3963 .Digest(Digest::SHA_2_256)
3964 .Padding(PaddingMode::RSA_PSS)
3965 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3966 .SetDefaultValidity();
3967
3968 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3969 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3970 AuthorizationSetBuilder()
3971 .Digest(Digest::SHA_2_256)
3972 .Padding(PaddingMode::RSA_OAEP)));
3973}
3974
3975TEST_P(ImportWrappedKeyTest, WrongDigest) {
3976 auto wrapping_key_desc = AuthorizationSetBuilder()
3977 .RsaEncryptionKey(2048, 65537)
3978 .Digest(Digest::SHA_2_512)
3979 .Padding(PaddingMode::RSA_OAEP)
3980 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3981 .SetDefaultValidity();
3982
3983 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3984 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3985 AuthorizationSetBuilder()
3986 .Digest(Digest::SHA_2_256)
3987 .Padding(PaddingMode::RSA_OAEP)));
3988}
3989
Selene Huang31ab4042020-04-29 04:22:39 -07003990INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3991
3992typedef KeyMintAidlTestBase EncryptionOperationsTest;
3993
3994/*
3995 * EncryptionOperationsTest.RsaNoPaddingSuccess
3996 *
David Drysdale59cae642021-05-12 13:52:03 +01003997 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003998 */
3999TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01004000 for (uint64_t exponent : {3, 65537}) {
4001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4002 .Authorization(TAG_NO_AUTH_REQUIRED)
4003 .RsaEncryptionKey(2048, exponent)
4004 .Padding(PaddingMode::NONE)
4005 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004006
David Drysdaled2cc8c22021-04-15 13:29:45 +01004007 string message = string(2048 / 8, 'a');
4008 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004009 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004010 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004011
David Drysdale59cae642021-05-12 13:52:03 +01004012 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004013 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004014
David Drysdaled2cc8c22021-04-15 13:29:45 +01004015 // Unpadded RSA is deterministic
4016 EXPECT_EQ(ciphertext1, ciphertext2);
4017
4018 CheckedDeleteKey();
4019 }
Selene Huang31ab4042020-04-29 04:22:39 -07004020}
4021
4022/*
4023 * EncryptionOperationsTest.RsaNoPaddingShortMessage
4024 *
David Drysdale59cae642021-05-12 13:52:03 +01004025 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07004026 */
4027TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
4028 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4029 .Authorization(TAG_NO_AUTH_REQUIRED)
4030 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004031 .Padding(PaddingMode::NONE)
4032 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004033
4034 string message = "1";
4035 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4036
David Drysdale59cae642021-05-12 13:52:03 +01004037 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004038 EXPECT_EQ(2048U / 8, ciphertext.size());
4039
4040 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
4041 string plaintext = DecryptMessage(ciphertext, params);
4042
4043 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07004044}
4045
4046/*
Selene Huang31ab4042020-04-29 04:22:39 -07004047 * EncryptionOperationsTest.RsaOaepSuccess
4048 *
David Drysdale59cae642021-05-12 13:52:03 +01004049 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07004050 */
4051TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4052 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4053
4054 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01004055 ASSERT_EQ(ErrorCode::OK,
4056 GenerateKey(AuthorizationSetBuilder()
4057 .Authorization(TAG_NO_AUTH_REQUIRED)
4058 .RsaEncryptionKey(key_size, 65537)
4059 .Padding(PaddingMode::RSA_OAEP)
4060 .Digest(digests)
4061 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
4062 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004063
4064 string message = "Hello";
4065
4066 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01004067 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4068
4069 auto params = AuthorizationSetBuilder()
4070 .Digest(digest)
4071 .Padding(PaddingMode::RSA_OAEP)
4072 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
4073 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004074 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4075 EXPECT_EQ(key_size / 8, ciphertext1.size());
4076
David Drysdale59cae642021-05-12 13:52:03 +01004077 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004078 EXPECT_EQ(key_size / 8, ciphertext2.size());
4079
4080 // OAEP randomizes padding so every result should be different (with astronomically high
4081 // probability).
4082 EXPECT_NE(ciphertext1, ciphertext2);
4083
4084 string plaintext1 = DecryptMessage(ciphertext1, params);
4085 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4086 string plaintext2 = DecryptMessage(ciphertext2, params);
4087 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4088
4089 // Decrypting corrupted ciphertext should fail.
4090 size_t offset_to_corrupt = random() % ciphertext1.size();
4091 char corrupt_byte;
4092 do {
4093 corrupt_byte = static_cast<char>(random() % 256);
4094 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4095 ciphertext1[offset_to_corrupt] = corrupt_byte;
4096
4097 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4098 string result;
4099 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4100 EXPECT_EQ(0U, result.size());
4101 }
4102}
4103
4104/*
4105 * EncryptionOperationsTest.RsaOaepInvalidDigest
4106 *
David Drysdale59cae642021-05-12 13:52:03 +01004107 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07004108 * without a digest.
4109 */
4110TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
4111 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4112 .Authorization(TAG_NO_AUTH_REQUIRED)
4113 .RsaEncryptionKey(2048, 65537)
4114 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004115 .Digest(Digest::NONE)
4116 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004117
4118 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004119 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07004120}
4121
4122/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004123 * EncryptionOperationsTest.RsaOaepInvalidPadding
4124 *
David Drysdale59cae642021-05-12 13:52:03 +01004125 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01004126 * with a padding value that is only suitable for signing/verifying.
4127 */
4128TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
4129 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4130 .Authorization(TAG_NO_AUTH_REQUIRED)
4131 .RsaEncryptionKey(2048, 65537)
4132 .Padding(PaddingMode::RSA_PSS)
4133 .Digest(Digest::NONE)
4134 .SetDefaultValidity()));
4135
4136 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004137 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01004138}
4139
4140/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004141 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07004142 *
David Drysdale59cae642021-05-12 13:52:03 +01004143 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004144 * with a different digest than was used to encrypt.
4145 */
4146TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01004147 if (SecLevel() == SecurityLevel::STRONGBOX) {
4148 GTEST_SKIP() << "Test not applicable to StrongBox device";
4149 }
Selene Huang31ab4042020-04-29 04:22:39 -07004150
4151 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4152 .Authorization(TAG_NO_AUTH_REQUIRED)
4153 .RsaEncryptionKey(1024, 65537)
4154 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004155 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
4156 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004157 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01004158 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07004159 message,
4160 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
4161
4162 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4163 .Digest(Digest::SHA_2_256)
4164 .Padding(PaddingMode::RSA_OAEP)));
4165 string result;
4166 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
4167 EXPECT_EQ(0U, result.size());
4168}
4169
4170/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004171 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
4172 *
David Drysdale59cae642021-05-12 13:52:03 +01004173 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004174 * digests.
4175 */
4176TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
4177 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4178
4179 size_t key_size = 2048; // Need largish key for SHA-512 test.
4180 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4181 .OaepMGFDigest(digests)
4182 .Authorization(TAG_NO_AUTH_REQUIRED)
4183 .RsaEncryptionKey(key_size, 65537)
4184 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004185 .Digest(Digest::SHA_2_256)
4186 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004187
4188 string message = "Hello";
4189
4190 for (auto digest : digests) {
4191 auto params = AuthorizationSetBuilder()
4192 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4193 .Digest(Digest::SHA_2_256)
4194 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01004195 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004196 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4197 EXPECT_EQ(key_size / 8, ciphertext1.size());
4198
David Drysdale59cae642021-05-12 13:52:03 +01004199 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004200 EXPECT_EQ(key_size / 8, ciphertext2.size());
4201
4202 // OAEP randomizes padding so every result should be different (with astronomically high
4203 // probability).
4204 EXPECT_NE(ciphertext1, ciphertext2);
4205
4206 string plaintext1 = DecryptMessage(ciphertext1, params);
4207 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4208 string plaintext2 = DecryptMessage(ciphertext2, params);
4209 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4210
4211 // Decrypting corrupted ciphertext should fail.
4212 size_t offset_to_corrupt = random() % ciphertext1.size();
4213 char corrupt_byte;
4214 do {
4215 corrupt_byte = static_cast<char>(random() % 256);
4216 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4217 ciphertext1[offset_to_corrupt] = corrupt_byte;
4218
4219 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4220 string result;
4221 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4222 EXPECT_EQ(0U, result.size());
4223 }
4224}
4225
4226/*
4227 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4228 *
David Drysdale59cae642021-05-12 13:52:03 +01004229 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004230 * with incompatible MGF digest.
4231 */
4232TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4233 ASSERT_EQ(ErrorCode::OK,
4234 GenerateKey(AuthorizationSetBuilder()
4235 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4236 .Authorization(TAG_NO_AUTH_REQUIRED)
4237 .RsaEncryptionKey(2048, 65537)
4238 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004239 .Digest(Digest::SHA_2_256)
4240 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004241 string message = "Hello World!";
4242
4243 auto params = AuthorizationSetBuilder()
4244 .Padding(PaddingMode::RSA_OAEP)
4245 .Digest(Digest::SHA_2_256)
4246 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004247 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004248}
4249
4250/*
4251 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4252 *
4253 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4254 * with unsupported MGF digest.
4255 */
4256TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4257 ASSERT_EQ(ErrorCode::OK,
4258 GenerateKey(AuthorizationSetBuilder()
4259 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4260 .Authorization(TAG_NO_AUTH_REQUIRED)
4261 .RsaEncryptionKey(2048, 65537)
4262 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004263 .Digest(Digest::SHA_2_256)
4264 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004265 string message = "Hello World!";
4266
4267 auto params = AuthorizationSetBuilder()
4268 .Padding(PaddingMode::RSA_OAEP)
4269 .Digest(Digest::SHA_2_256)
4270 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004271 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004272}
4273
4274/*
Selene Huang31ab4042020-04-29 04:22:39 -07004275 * EncryptionOperationsTest.RsaPkcs1Success
4276 *
4277 * Verifies that RSA PKCS encryption/decrypts works.
4278 */
4279TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4280 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4281 .Authorization(TAG_NO_AUTH_REQUIRED)
4282 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004283 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4284 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004285
4286 string message = "Hello World!";
4287 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004288 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004289 EXPECT_EQ(2048U / 8, ciphertext1.size());
4290
David Drysdale59cae642021-05-12 13:52:03 +01004291 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004292 EXPECT_EQ(2048U / 8, ciphertext2.size());
4293
4294 // PKCS1 v1.5 randomizes padding so every result should be different.
4295 EXPECT_NE(ciphertext1, ciphertext2);
4296
4297 string plaintext = DecryptMessage(ciphertext1, params);
4298 EXPECT_EQ(message, plaintext);
4299
4300 // Decrypting corrupted ciphertext should fail.
4301 size_t offset_to_corrupt = random() % ciphertext1.size();
4302 char corrupt_byte;
4303 do {
4304 corrupt_byte = static_cast<char>(random() % 256);
4305 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4306 ciphertext1[offset_to_corrupt] = corrupt_byte;
4307
4308 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4309 string result;
4310 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4311 EXPECT_EQ(0U, result.size());
4312}
4313
4314/*
Selene Huang31ab4042020-04-29 04:22:39 -07004315 * EncryptionOperationsTest.EcdsaEncrypt
4316 *
4317 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4318 */
4319TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4320 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4321 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004322 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004323 .Digest(Digest::NONE)
4324 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004325 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4326 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4327 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4328}
4329
4330/*
4331 * EncryptionOperationsTest.HmacEncrypt
4332 *
4333 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4334 */
4335TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4336 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4337 .Authorization(TAG_NO_AUTH_REQUIRED)
4338 .HmacKey(128)
4339 .Digest(Digest::SHA_2_256)
4340 .Padding(PaddingMode::NONE)
4341 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4342 auto params = AuthorizationSetBuilder()
4343 .Digest(Digest::SHA_2_256)
4344 .Padding(PaddingMode::NONE)
4345 .Authorization(TAG_MAC_LENGTH, 128);
4346 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4347 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4348}
4349
4350/*
4351 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4352 *
4353 * Verifies that AES ECB mode works.
4354 */
4355TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4356 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4357 .Authorization(TAG_NO_AUTH_REQUIRED)
4358 .AesEncryptionKey(128)
4359 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4360 .Padding(PaddingMode::NONE)));
4361
4362 ASSERT_GT(key_blob_.size(), 0U);
4363 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4364
4365 // Two-block message.
4366 string message = "12345678901234567890123456789012";
4367 string ciphertext1 = EncryptMessage(message, params);
4368 EXPECT_EQ(message.size(), ciphertext1.size());
4369
4370 string ciphertext2 = EncryptMessage(string(message), params);
4371 EXPECT_EQ(message.size(), ciphertext2.size());
4372
4373 // ECB is deterministic.
4374 EXPECT_EQ(ciphertext1, ciphertext2);
4375
4376 string plaintext = DecryptMessage(ciphertext1, params);
4377 EXPECT_EQ(message, plaintext);
4378}
4379
4380/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004381 * EncryptionOperationsTest.AesEcbUnknownTag
4382 *
4383 * Verifies that AES ECB operations ignore unknown tags.
4384 */
4385TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4386 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4387 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4388 KeyParameter unknown_param;
4389 unknown_param.tag = unknown_tag;
4390
4391 vector<KeyCharacteristics> key_characteristics;
4392 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4393 .Authorization(TAG_NO_AUTH_REQUIRED)
4394 .AesEncryptionKey(128)
4395 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4396 .Padding(PaddingMode::NONE)
4397 .Authorization(unknown_param),
4398 &key_blob_, &key_characteristics));
4399 ASSERT_GT(key_blob_.size(), 0U);
4400
4401 // Unknown tags should not be returned in key characteristics.
4402 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4403 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4404 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4405 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4406
4407 // Encrypt without mentioning the unknown parameter.
4408 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4409 string message = "12345678901234567890123456789012";
4410 string ciphertext = EncryptMessage(message, params);
4411 EXPECT_EQ(message.size(), ciphertext.size());
4412
4413 // Decrypt including the unknown parameter.
4414 auto decrypt_params = AuthorizationSetBuilder()
4415 .BlockMode(BlockMode::ECB)
4416 .Padding(PaddingMode::NONE)
4417 .Authorization(unknown_param);
4418 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4419 EXPECT_EQ(message, plaintext);
4420}
4421
4422/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004423 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004424 *
4425 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4426 */
4427TEST_P(EncryptionOperationsTest, AesWrongMode) {
4428 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4429 .Authorization(TAG_NO_AUTH_REQUIRED)
4430 .AesEncryptionKey(128)
4431 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4432 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004433 ASSERT_GT(key_blob_.size(), 0U);
4434
Selene Huang31ab4042020-04-29 04:22:39 -07004435 EXPECT_EQ(
4436 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4437 Begin(KeyPurpose::ENCRYPT,
4438 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4439}
4440
4441/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004442 * EncryptionOperationsTest.AesWrongPadding
4443 *
4444 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4445 */
4446TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4447 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4448 .Authorization(TAG_NO_AUTH_REQUIRED)
4449 .AesEncryptionKey(128)
4450 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4451 .Padding(PaddingMode::NONE)));
4452 ASSERT_GT(key_blob_.size(), 0U);
4453
4454 EXPECT_EQ(
4455 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4456 Begin(KeyPurpose::ENCRYPT,
4457 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4458}
4459
4460/*
4461 * EncryptionOperationsTest.AesInvalidParams
4462 *
4463 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4464 */
4465TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4466 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4467 .Authorization(TAG_NO_AUTH_REQUIRED)
4468 .AesEncryptionKey(128)
4469 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4470 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4471 .Padding(PaddingMode::NONE)
4472 .Padding(PaddingMode::PKCS7)));
4473 ASSERT_GT(key_blob_.size(), 0U);
4474
4475 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4476 .BlockMode(BlockMode::CBC)
4477 .BlockMode(BlockMode::ECB)
4478 .Padding(PaddingMode::NONE));
4479 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4480 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4481
4482 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4483 .BlockMode(BlockMode::ECB)
4484 .Padding(PaddingMode::NONE)
4485 .Padding(PaddingMode::PKCS7));
4486 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4487 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4488}
4489
4490/*
Selene Huang31ab4042020-04-29 04:22:39 -07004491 * EncryptionOperationsTest.AesWrongPurpose
4492 *
4493 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4494 * specified.
4495 */
4496TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4497 auto err = GenerateKey(AuthorizationSetBuilder()
4498 .Authorization(TAG_NO_AUTH_REQUIRED)
4499 .AesKey(128)
4500 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4501 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4502 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4503 .Padding(PaddingMode::NONE));
4504 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4505 ASSERT_GT(key_blob_.size(), 0U);
4506
4507 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4508 .BlockMode(BlockMode::GCM)
4509 .Padding(PaddingMode::NONE)
4510 .Authorization(TAG_MAC_LENGTH, 128));
4511 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4512
4513 CheckedDeleteKey();
4514
4515 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4516 .Authorization(TAG_NO_AUTH_REQUIRED)
4517 .AesKey(128)
4518 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4519 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4520 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4521 .Padding(PaddingMode::NONE)));
4522
4523 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4524 .BlockMode(BlockMode::GCM)
4525 .Padding(PaddingMode::NONE)
4526 .Authorization(TAG_MAC_LENGTH, 128));
4527 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4528}
4529
4530/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004531 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004532 *
4533 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4534 * multiple of the block size and no padding is specified.
4535 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004536TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4537 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4538 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4539 .Authorization(TAG_NO_AUTH_REQUIRED)
4540 .AesEncryptionKey(128)
4541 .Authorization(TAG_BLOCK_MODE, blockMode)
4542 .Padding(PaddingMode::NONE)));
4543 // Message is slightly shorter than two blocks.
4544 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004545
David Drysdaled2cc8c22021-04-15 13:29:45 +01004546 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4547 AuthorizationSet out_params;
4548 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4549 string ciphertext;
4550 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4551 EXPECT_EQ(0U, ciphertext.size());
4552
4553 CheckedDeleteKey();
4554 }
Selene Huang31ab4042020-04-29 04:22:39 -07004555}
4556
4557/*
4558 * EncryptionOperationsTest.AesEcbPkcs7Padding
4559 *
4560 * Verifies that AES PKCS7 padding works for any message length.
4561 */
4562TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4563 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4564 .Authorization(TAG_NO_AUTH_REQUIRED)
4565 .AesEncryptionKey(128)
4566 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4567 .Padding(PaddingMode::PKCS7)));
4568
4569 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4570
4571 // Try various message lengths; all should work.
4572 for (size_t i = 0; i < 32; ++i) {
4573 string message(i, 'a');
4574 string ciphertext = EncryptMessage(message, params);
4575 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4576 string plaintext = DecryptMessage(ciphertext, params);
4577 EXPECT_EQ(message, plaintext);
4578 }
4579}
4580
4581/*
4582 * EncryptionOperationsTest.AesEcbWrongPadding
4583 *
4584 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4585 * specified.
4586 */
4587TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4589 .Authorization(TAG_NO_AUTH_REQUIRED)
4590 .AesEncryptionKey(128)
4591 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4592 .Padding(PaddingMode::NONE)));
4593
4594 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4595
4596 // Try various message lengths; all should fail
4597 for (size_t i = 0; i < 32; ++i) {
4598 string message(i, 'a');
4599 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4600 }
4601}
4602
4603/*
4604 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4605 *
4606 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4607 */
4608TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4609 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4610 .Authorization(TAG_NO_AUTH_REQUIRED)
4611 .AesEncryptionKey(128)
4612 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4613 .Padding(PaddingMode::PKCS7)));
4614
4615 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4616
4617 string message = "a";
4618 string ciphertext = EncryptMessage(message, params);
4619 EXPECT_EQ(16U, ciphertext.size());
4620 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07004621
Seth Moore7a55ae32021-06-23 14:28:11 -07004622 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
4623 ++ciphertext[ciphertext.size() / 2];
4624
4625 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4626 string plaintext;
4627 ErrorCode error = Finish(message, &plaintext);
4628 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
4629 // This is the expected error, we can exit the test now.
4630 return;
4631 } else {
4632 // Very small chance we got valid decryption, so try again.
4633 ASSERT_EQ(error, ErrorCode::OK);
4634 }
4635 }
4636 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07004637}
4638
4639vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4640 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004641 EXPECT_TRUE(iv);
4642 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004643}
4644
4645/*
4646 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4647 *
4648 * Verifies that AES CTR mode works.
4649 */
4650TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4651 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4652 .Authorization(TAG_NO_AUTH_REQUIRED)
4653 .AesEncryptionKey(128)
4654 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4655 .Padding(PaddingMode::NONE)));
4656
4657 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4658
4659 string message = "123";
4660 AuthorizationSet out_params;
4661 string ciphertext1 = EncryptMessage(message, params, &out_params);
4662 vector<uint8_t> iv1 = CopyIv(out_params);
4663 EXPECT_EQ(16U, iv1.size());
4664
4665 EXPECT_EQ(message.size(), ciphertext1.size());
4666
4667 out_params.Clear();
4668 string ciphertext2 = EncryptMessage(message, params, &out_params);
4669 vector<uint8_t> iv2 = CopyIv(out_params);
4670 EXPECT_EQ(16U, iv2.size());
4671
4672 // IVs should be random, so ciphertexts should differ.
4673 EXPECT_NE(ciphertext1, ciphertext2);
4674
4675 auto params_iv1 =
4676 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4677 auto params_iv2 =
4678 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4679
4680 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4681 EXPECT_EQ(message, plaintext);
4682 plaintext = DecryptMessage(ciphertext2, params_iv2);
4683 EXPECT_EQ(message, plaintext);
4684
4685 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4686 plaintext = DecryptMessage(ciphertext1, params_iv2);
4687 EXPECT_NE(message, plaintext);
4688 plaintext = DecryptMessage(ciphertext2, params_iv1);
4689 EXPECT_NE(message, plaintext);
4690}
4691
4692/*
4693 * EncryptionOperationsTest.AesIncremental
4694 *
4695 * Verifies that AES works, all modes, when provided data in various size increments.
4696 */
4697TEST_P(EncryptionOperationsTest, AesIncremental) {
4698 auto block_modes = {
4699 BlockMode::ECB,
4700 BlockMode::CBC,
4701 BlockMode::CTR,
4702 BlockMode::GCM,
4703 };
4704
4705 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4706 .Authorization(TAG_NO_AUTH_REQUIRED)
4707 .AesEncryptionKey(128)
4708 .BlockMode(block_modes)
4709 .Padding(PaddingMode::NONE)
4710 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4711
4712 for (int increment = 1; increment <= 240; ++increment) {
4713 for (auto block_mode : block_modes) {
4714 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004715 auto params =
4716 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4717 if (block_mode == BlockMode::GCM) {
4718 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4719 }
Selene Huang31ab4042020-04-29 04:22:39 -07004720
4721 AuthorizationSet output_params;
4722 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4723
4724 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004725 string to_send;
4726 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004727 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004728 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004729 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4730 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004731
4732 switch (block_mode) {
4733 case BlockMode::GCM:
4734 EXPECT_EQ(message.size() + 16, ciphertext.size());
4735 break;
4736 case BlockMode::CTR:
4737 EXPECT_EQ(message.size(), ciphertext.size());
4738 break;
4739 case BlockMode::CBC:
4740 case BlockMode::ECB:
4741 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4742 break;
4743 }
4744
4745 auto iv = output_params.GetTagValue(TAG_NONCE);
4746 switch (block_mode) {
4747 case BlockMode::CBC:
4748 case BlockMode::GCM:
4749 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004750 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4751 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4752 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004753 break;
4754
4755 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004756 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004757 break;
4758 }
4759
4760 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4761 << "Decrypt begin() failed for block mode " << block_mode;
4762
4763 string plaintext;
4764 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004765 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004766 }
4767 ErrorCode error = Finish(to_send, &plaintext);
4768 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4769 << " and increment " << increment;
4770 if (error == ErrorCode::OK) {
4771 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4772 << block_mode << " and increment " << increment;
4773 }
4774 }
4775 }
4776}
4777
4778struct AesCtrSp80038aTestVector {
4779 const char* key;
4780 const char* nonce;
4781 const char* plaintext;
4782 const char* ciphertext;
4783};
4784
4785// These test vectors are taken from
4786// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4787static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4788 // AES-128
4789 {
4790 "2b7e151628aed2a6abf7158809cf4f3c",
4791 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4792 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4793 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4794 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4795 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4796 },
4797 // AES-192
4798 {
4799 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4800 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4801 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4802 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4803 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4804 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4805 },
4806 // AES-256
4807 {
4808 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4809 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4810 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4811 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4812 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4813 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4814 },
4815};
4816
4817/*
4818 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4819 *
4820 * Verifies AES CTR implementation against SP800-38A test vectors.
4821 */
4822TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4823 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4824 for (size_t i = 0; i < 3; i++) {
4825 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4826 const string key = hex2str(test.key);
4827 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4828 InvalidSizes.end())
4829 continue;
4830 const string nonce = hex2str(test.nonce);
4831 const string plaintext = hex2str(test.plaintext);
4832 const string ciphertext = hex2str(test.ciphertext);
4833 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4834 }
4835}
4836
4837/*
4838 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4839 *
4840 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4841 */
4842TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4843 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4844 .Authorization(TAG_NO_AUTH_REQUIRED)
4845 .AesEncryptionKey(128)
4846 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4847 .Padding(PaddingMode::PKCS7)));
4848 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4849 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4850}
4851
4852/*
4853 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4854 *
4855 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4856 */
4857TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4858 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4859 .Authorization(TAG_NO_AUTH_REQUIRED)
4860 .AesEncryptionKey(128)
4861 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4862 .Authorization(TAG_CALLER_NONCE)
4863 .Padding(PaddingMode::NONE)));
4864
4865 auto params = AuthorizationSetBuilder()
4866 .BlockMode(BlockMode::CTR)
4867 .Padding(PaddingMode::NONE)
4868 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4869 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4870
4871 params = AuthorizationSetBuilder()
4872 .BlockMode(BlockMode::CTR)
4873 .Padding(PaddingMode::NONE)
4874 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4875 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4876
4877 params = AuthorizationSetBuilder()
4878 .BlockMode(BlockMode::CTR)
4879 .Padding(PaddingMode::NONE)
4880 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4881 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4882}
4883
4884/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004885 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004886 *
4887 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4888 */
4889TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4890 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4891 .Authorization(TAG_NO_AUTH_REQUIRED)
4892 .AesEncryptionKey(128)
4893 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4894 .Padding(PaddingMode::NONE)));
4895 // Two-block message.
4896 string message = "12345678901234567890123456789012";
4897 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4898 AuthorizationSet out_params;
4899 string ciphertext1 = EncryptMessage(message, params, &out_params);
4900 vector<uint8_t> iv1 = CopyIv(out_params);
4901 EXPECT_EQ(message.size(), ciphertext1.size());
4902
4903 out_params.Clear();
4904
4905 string ciphertext2 = EncryptMessage(message, params, &out_params);
4906 vector<uint8_t> iv2 = CopyIv(out_params);
4907 EXPECT_EQ(message.size(), ciphertext2.size());
4908
4909 // IVs should be random, so ciphertexts should differ.
4910 EXPECT_NE(ciphertext1, ciphertext2);
4911
4912 params.push_back(TAG_NONCE, iv1);
4913 string plaintext = DecryptMessage(ciphertext1, params);
4914 EXPECT_EQ(message, plaintext);
4915}
4916
4917/*
4918 * EncryptionOperationsTest.AesCallerNonce
4919 *
4920 * Verifies that AES caller-provided nonces work correctly.
4921 */
4922TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4923 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4924 .Authorization(TAG_NO_AUTH_REQUIRED)
4925 .AesEncryptionKey(128)
4926 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4927 .Authorization(TAG_CALLER_NONCE)
4928 .Padding(PaddingMode::NONE)));
4929
4930 string message = "12345678901234567890123456789012";
4931
4932 // Don't specify nonce, should get a random one.
4933 AuthorizationSetBuilder params =
4934 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4935 AuthorizationSet out_params;
4936 string ciphertext = EncryptMessage(message, params, &out_params);
4937 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004938 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004939
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004940 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004941 string plaintext = DecryptMessage(ciphertext, params);
4942 EXPECT_EQ(message, plaintext);
4943
4944 // Now specify a nonce, should also work.
4945 params = AuthorizationSetBuilder()
4946 .BlockMode(BlockMode::CBC)
4947 .Padding(PaddingMode::NONE)
4948 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4949 out_params.Clear();
4950 ciphertext = EncryptMessage(message, params, &out_params);
4951
4952 // Decrypt with correct nonce.
4953 plaintext = DecryptMessage(ciphertext, params);
4954 EXPECT_EQ(message, plaintext);
4955
4956 // Try with wrong nonce.
4957 params = AuthorizationSetBuilder()
4958 .BlockMode(BlockMode::CBC)
4959 .Padding(PaddingMode::NONE)
4960 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4961 plaintext = DecryptMessage(ciphertext, params);
4962 EXPECT_NE(message, plaintext);
4963}
4964
4965/*
4966 * EncryptionOperationsTest.AesCallerNonceProhibited
4967 *
4968 * Verifies that caller-provided nonces are not permitted when not specified in the key
4969 * authorizations.
4970 */
4971TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4972 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4973 .Authorization(TAG_NO_AUTH_REQUIRED)
4974 .AesEncryptionKey(128)
4975 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4976 .Padding(PaddingMode::NONE)));
4977
4978 string message = "12345678901234567890123456789012";
4979
4980 // Don't specify nonce, should get a random one.
4981 AuthorizationSetBuilder params =
4982 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4983 AuthorizationSet out_params;
4984 string ciphertext = EncryptMessage(message, params, &out_params);
4985 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004986 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004987
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004988 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004989 string plaintext = DecryptMessage(ciphertext, params);
4990 EXPECT_EQ(message, plaintext);
4991
4992 // Now specify a nonce, should fail
4993 params = AuthorizationSetBuilder()
4994 .BlockMode(BlockMode::CBC)
4995 .Padding(PaddingMode::NONE)
4996 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4997 out_params.Clear();
4998 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4999}
5000
5001/*
5002 * EncryptionOperationsTest.AesGcmRoundTripSuccess
5003 *
5004 * Verifies that AES GCM mode works.
5005 */
5006TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
5007 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5008 .Authorization(TAG_NO_AUTH_REQUIRED)
5009 .AesEncryptionKey(128)
5010 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5011 .Padding(PaddingMode::NONE)
5012 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5013
5014 string aad = "foobar";
5015 string message = "123456789012345678901234567890123456";
5016
5017 auto begin_params = AuthorizationSetBuilder()
5018 .BlockMode(BlockMode::GCM)
5019 .Padding(PaddingMode::NONE)
5020 .Authorization(TAG_MAC_LENGTH, 128);
5021
Selene Huang31ab4042020-04-29 04:22:39 -07005022 // Encrypt
5023 AuthorizationSet begin_out_params;
5024 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5025 << "Begin encrypt";
5026 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005027 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5028 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005029 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5030
5031 // Grab nonce
5032 begin_params.push_back(begin_out_params);
5033
5034 // Decrypt.
5035 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07005036 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005037 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005038 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005039 EXPECT_EQ(message.length(), plaintext.length());
5040 EXPECT_EQ(message, plaintext);
5041}
5042
5043/*
5044 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
5045 *
5046 * Verifies that AES GCM mode works, even when there's a long delay
5047 * between operations.
5048 */
5049TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
5050 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5051 .Authorization(TAG_NO_AUTH_REQUIRED)
5052 .AesEncryptionKey(128)
5053 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5054 .Padding(PaddingMode::NONE)
5055 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5056
5057 string aad = "foobar";
5058 string message = "123456789012345678901234567890123456";
5059
5060 auto begin_params = AuthorizationSetBuilder()
5061 .BlockMode(BlockMode::GCM)
5062 .Padding(PaddingMode::NONE)
5063 .Authorization(TAG_MAC_LENGTH, 128);
5064
Selene Huang31ab4042020-04-29 04:22:39 -07005065 // Encrypt
5066 AuthorizationSet begin_out_params;
5067 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5068 << "Begin encrypt";
5069 string ciphertext;
5070 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005071 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005072 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005073 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005074
5075 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5076
5077 // Grab nonce
5078 begin_params.push_back(begin_out_params);
5079
5080 // Decrypt.
5081 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5082 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005083 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005084 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005085 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005086 sleep(5);
5087 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5088 EXPECT_EQ(message.length(), plaintext.length());
5089 EXPECT_EQ(message, plaintext);
5090}
5091
5092/*
5093 * EncryptionOperationsTest.AesGcmDifferentNonces
5094 *
5095 * Verifies that encrypting the same data with different nonces produces different outputs.
5096 */
5097TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
5098 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5099 .Authorization(TAG_NO_AUTH_REQUIRED)
5100 .AesEncryptionKey(128)
5101 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5102 .Padding(PaddingMode::NONE)
5103 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5104 .Authorization(TAG_CALLER_NONCE)));
5105
5106 string aad = "foobar";
5107 string message = "123456789012345678901234567890123456";
5108 string nonce1 = "000000000000";
5109 string nonce2 = "111111111111";
5110 string nonce3 = "222222222222";
5111
5112 string ciphertext1 =
5113 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
5114 string ciphertext2 =
5115 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
5116 string ciphertext3 =
5117 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
5118
5119 ASSERT_NE(ciphertext1, ciphertext2);
5120 ASSERT_NE(ciphertext1, ciphertext3);
5121 ASSERT_NE(ciphertext2, ciphertext3);
5122}
5123
5124/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005125 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
5126 *
5127 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
5128 */
5129TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
5130 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5131 .Authorization(TAG_NO_AUTH_REQUIRED)
5132 .AesEncryptionKey(128)
5133 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5134 .Padding(PaddingMode::NONE)
5135 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5136
5137 string aad = "foobar";
5138 string message = "123456789012345678901234567890123456";
5139
5140 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5141 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5142 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5143
5144 ASSERT_NE(ciphertext1, ciphertext2);
5145 ASSERT_NE(ciphertext1, ciphertext3);
5146 ASSERT_NE(ciphertext2, ciphertext3);
5147}
5148
5149/*
Selene Huang31ab4042020-04-29 04:22:39 -07005150 * EncryptionOperationsTest.AesGcmTooShortTag
5151 *
5152 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
5153 */
5154TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
5155 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5156 .Authorization(TAG_NO_AUTH_REQUIRED)
5157 .AesEncryptionKey(128)
5158 .BlockMode(BlockMode::GCM)
5159 .Padding(PaddingMode::NONE)
5160 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5161 string message = "123456789012345678901234567890123456";
5162 auto params = AuthorizationSetBuilder()
5163 .BlockMode(BlockMode::GCM)
5164 .Padding(PaddingMode::NONE)
5165 .Authorization(TAG_MAC_LENGTH, 96);
5166
5167 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
5168}
5169
5170/*
5171 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
5172 *
5173 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
5174 */
5175TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
5176 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5177 .Authorization(TAG_NO_AUTH_REQUIRED)
5178 .AesEncryptionKey(128)
5179 .BlockMode(BlockMode::GCM)
5180 .Padding(PaddingMode::NONE)
5181 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5182 string aad = "foobar";
5183 string message = "123456789012345678901234567890123456";
5184 auto params = AuthorizationSetBuilder()
5185 .BlockMode(BlockMode::GCM)
5186 .Padding(PaddingMode::NONE)
5187 .Authorization(TAG_MAC_LENGTH, 128);
5188
Selene Huang31ab4042020-04-29 04:22:39 -07005189 // Encrypt
5190 AuthorizationSet begin_out_params;
5191 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5192 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005193 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005194
5195 AuthorizationSet finish_out_params;
5196 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005197 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5198 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005199
5200 params = AuthorizationSetBuilder()
5201 .Authorizations(begin_out_params)
5202 .BlockMode(BlockMode::GCM)
5203 .Padding(PaddingMode::NONE)
5204 .Authorization(TAG_MAC_LENGTH, 96);
5205
5206 // Decrypt.
5207 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5208}
5209
5210/*
5211 * EncryptionOperationsTest.AesGcmCorruptKey
5212 *
5213 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5214 */
5215TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5216 const uint8_t nonce_bytes[] = {
5217 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5218 };
5219 string nonce = make_string(nonce_bytes);
5220 const uint8_t ciphertext_bytes[] = {
5221 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5222 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5223 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5224 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5225 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5226 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5227 };
5228 string ciphertext = make_string(ciphertext_bytes);
5229
5230 auto params = AuthorizationSetBuilder()
5231 .BlockMode(BlockMode::GCM)
5232 .Padding(PaddingMode::NONE)
5233 .Authorization(TAG_MAC_LENGTH, 128)
5234 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5235
5236 auto import_params = AuthorizationSetBuilder()
5237 .Authorization(TAG_NO_AUTH_REQUIRED)
5238 .AesEncryptionKey(128)
5239 .BlockMode(BlockMode::GCM)
5240 .Padding(PaddingMode::NONE)
5241 .Authorization(TAG_CALLER_NONCE)
5242 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5243
5244 // Import correct key and decrypt
5245 const uint8_t key_bytes[] = {
5246 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5247 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5248 };
5249 string key = make_string(key_bytes);
5250 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5251 string plaintext = DecryptMessage(ciphertext, params);
5252 CheckedDeleteKey();
5253
5254 // Corrupt key and attempt to decrypt
5255 key[0] = 0;
5256 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5257 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5258 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5259 CheckedDeleteKey();
5260}
5261
5262/*
5263 * EncryptionOperationsTest.AesGcmAadNoData
5264 *
5265 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5266 * encrypt.
5267 */
5268TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5269 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5270 .Authorization(TAG_NO_AUTH_REQUIRED)
5271 .AesEncryptionKey(128)
5272 .BlockMode(BlockMode::GCM)
5273 .Padding(PaddingMode::NONE)
5274 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5275
5276 string aad = "1234567890123456";
5277 auto params = AuthorizationSetBuilder()
5278 .BlockMode(BlockMode::GCM)
5279 .Padding(PaddingMode::NONE)
5280 .Authorization(TAG_MAC_LENGTH, 128);
5281
Selene Huang31ab4042020-04-29 04:22:39 -07005282 // Encrypt
5283 AuthorizationSet begin_out_params;
5284 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5285 string ciphertext;
5286 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005287 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5288 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005289 EXPECT_TRUE(finish_out_params.empty());
5290
5291 // Grab nonce
5292 params.push_back(begin_out_params);
5293
5294 // Decrypt.
5295 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005296 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005297 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005298 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005299
5300 EXPECT_TRUE(finish_out_params.empty());
5301
5302 EXPECT_EQ("", plaintext);
5303}
5304
5305/*
5306 * EncryptionOperationsTest.AesGcmMultiPartAad
5307 *
5308 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5309 * chunks.
5310 */
5311TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5312 const size_t tag_bits = 128;
5313 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5314 .Authorization(TAG_NO_AUTH_REQUIRED)
5315 .AesEncryptionKey(128)
5316 .BlockMode(BlockMode::GCM)
5317 .Padding(PaddingMode::NONE)
5318 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5319
5320 string message = "123456789012345678901234567890123456";
5321 auto begin_params = AuthorizationSetBuilder()
5322 .BlockMode(BlockMode::GCM)
5323 .Padding(PaddingMode::NONE)
5324 .Authorization(TAG_MAC_LENGTH, tag_bits);
5325 AuthorizationSet begin_out_params;
5326
Selene Huang31ab4042020-04-29 04:22:39 -07005327 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5328
5329 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005330 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5331 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005332 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005333 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5334 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005335
Selene Huang31ab4042020-04-29 04:22:39 -07005336 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005337 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005338
5339 // Grab nonce.
5340 begin_params.push_back(begin_out_params);
5341
5342 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005343 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005344 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005345 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005346 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005347 EXPECT_EQ(message, plaintext);
5348}
5349
5350/*
5351 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5352 *
5353 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5354 */
5355TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5356 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5357 .Authorization(TAG_NO_AUTH_REQUIRED)
5358 .AesEncryptionKey(128)
5359 .BlockMode(BlockMode::GCM)
5360 .Padding(PaddingMode::NONE)
5361 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5362
5363 string message = "123456789012345678901234567890123456";
5364 auto begin_params = AuthorizationSetBuilder()
5365 .BlockMode(BlockMode::GCM)
5366 .Padding(PaddingMode::NONE)
5367 .Authorization(TAG_MAC_LENGTH, 128);
5368 AuthorizationSet begin_out_params;
5369
Selene Huang31ab4042020-04-29 04:22:39 -07005370 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5371
Shawn Willden92d79c02021-02-19 07:31:55 -07005372 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::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005376
David Drysdaled2cc8c22021-04-15 13:29:45 +01005377 // The failure should have already cancelled the operation.
5378 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5379
Shawn Willden92d79c02021-02-19 07:31:55 -07005380 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005381}
5382
5383/*
5384 * EncryptionOperationsTest.AesGcmBadAad
5385 *
5386 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5387 */
5388TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5389 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5390 .Authorization(TAG_NO_AUTH_REQUIRED)
5391 .AesEncryptionKey(128)
5392 .BlockMode(BlockMode::GCM)
5393 .Padding(PaddingMode::NONE)
5394 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5395
5396 string message = "12345678901234567890123456789012";
5397 auto begin_params = AuthorizationSetBuilder()
5398 .BlockMode(BlockMode::GCM)
5399 .Padding(PaddingMode::NONE)
5400 .Authorization(TAG_MAC_LENGTH, 128);
5401
Selene Huang31ab4042020-04-29 04:22:39 -07005402 // Encrypt
5403 AuthorizationSet begin_out_params;
5404 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005405 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005406 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005407 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005408
5409 // Grab nonce
5410 begin_params.push_back(begin_out_params);
5411
Selene Huang31ab4042020-04-29 04:22:39 -07005412 // Decrypt.
5413 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005414 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005415 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005416 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005417}
5418
5419/*
5420 * EncryptionOperationsTest.AesGcmWrongNonce
5421 *
5422 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5423 */
5424TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5425 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5426 .Authorization(TAG_NO_AUTH_REQUIRED)
5427 .AesEncryptionKey(128)
5428 .BlockMode(BlockMode::GCM)
5429 .Padding(PaddingMode::NONE)
5430 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5431
5432 string message = "12345678901234567890123456789012";
5433 auto begin_params = AuthorizationSetBuilder()
5434 .BlockMode(BlockMode::GCM)
5435 .Padding(PaddingMode::NONE)
5436 .Authorization(TAG_MAC_LENGTH, 128);
5437
Selene Huang31ab4042020-04-29 04:22:39 -07005438 // Encrypt
5439 AuthorizationSet begin_out_params;
5440 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005441 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005442 string ciphertext;
5443 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005444 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005445
5446 // Wrong nonce
5447 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5448
5449 // Decrypt.
5450 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005451 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005452 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005453 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005454
5455 // With wrong nonce, should have gotten garbage plaintext (or none).
5456 EXPECT_NE(message, plaintext);
5457}
5458
5459/*
5460 * EncryptionOperationsTest.AesGcmCorruptTag
5461 *
5462 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5463 */
5464TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5465 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5466 .Authorization(TAG_NO_AUTH_REQUIRED)
5467 .AesEncryptionKey(128)
5468 .BlockMode(BlockMode::GCM)
5469 .Padding(PaddingMode::NONE)
5470 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5471
5472 string aad = "1234567890123456";
5473 string message = "123456789012345678901234567890123456";
5474
5475 auto params = AuthorizationSetBuilder()
5476 .BlockMode(BlockMode::GCM)
5477 .Padding(PaddingMode::NONE)
5478 .Authorization(TAG_MAC_LENGTH, 128);
5479
Selene Huang31ab4042020-04-29 04:22:39 -07005480 // Encrypt
5481 AuthorizationSet begin_out_params;
5482 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005483 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005484 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005485 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005486
5487 // Corrupt tag
5488 ++(*ciphertext.rbegin());
5489
5490 // Grab nonce
5491 params.push_back(begin_out_params);
5492
5493 // Decrypt.
5494 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005495 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005496 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005497 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005498}
5499
5500/*
5501 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5502 *
5503 * Verifies that 3DES is basically functional.
5504 */
5505TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5506 auto auths = AuthorizationSetBuilder()
5507 .TripleDesEncryptionKey(168)
5508 .BlockMode(BlockMode::ECB)
5509 .Authorization(TAG_NO_AUTH_REQUIRED)
5510 .Padding(PaddingMode::NONE);
5511
5512 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5513 // Two-block message.
5514 string message = "1234567890123456";
5515 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5516 string ciphertext1 = EncryptMessage(message, inParams);
5517 EXPECT_EQ(message.size(), ciphertext1.size());
5518
5519 string ciphertext2 = EncryptMessage(string(message), inParams);
5520 EXPECT_EQ(message.size(), ciphertext2.size());
5521
5522 // ECB is deterministic.
5523 EXPECT_EQ(ciphertext1, ciphertext2);
5524
5525 string plaintext = DecryptMessage(ciphertext1, inParams);
5526 EXPECT_EQ(message, plaintext);
5527}
5528
5529/*
5530 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5531 *
5532 * Verifies that CBC keys reject ECB usage.
5533 */
5534TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5535 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5536 .TripleDesEncryptionKey(168)
5537 .BlockMode(BlockMode::CBC)
5538 .Authorization(TAG_NO_AUTH_REQUIRED)
5539 .Padding(PaddingMode::NONE)));
5540
5541 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5542 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5543}
5544
5545/*
5546 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5547 *
5548 * Tests ECB mode with PKCS#7 padding, various message sizes.
5549 */
5550TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5551 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5552 .TripleDesEncryptionKey(168)
5553 .BlockMode(BlockMode::ECB)
5554 .Authorization(TAG_NO_AUTH_REQUIRED)
5555 .Padding(PaddingMode::PKCS7)));
5556
5557 for (size_t i = 0; i < 32; ++i) {
5558 string message(i, 'a');
5559 auto inParams =
5560 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5561 string ciphertext = EncryptMessage(message, inParams);
5562 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5563 string plaintext = DecryptMessage(ciphertext, inParams);
5564 EXPECT_EQ(message, plaintext);
5565 }
5566}
5567
5568/*
5569 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5570 *
5571 * Verifies that keys configured for no padding reject PKCS7 padding
5572 */
5573TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5574 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5575 .TripleDesEncryptionKey(168)
5576 .BlockMode(BlockMode::ECB)
5577 .Authorization(TAG_NO_AUTH_REQUIRED)
5578 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005579 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5580 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005581}
5582
5583/*
5584 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5585 *
5586 * Verifies that corrupted padding is detected.
5587 */
5588TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5589 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5590 .TripleDesEncryptionKey(168)
5591 .BlockMode(BlockMode::ECB)
5592 .Authorization(TAG_NO_AUTH_REQUIRED)
5593 .Padding(PaddingMode::PKCS7)));
5594
5595 string message = "a";
5596 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5597 EXPECT_EQ(8U, ciphertext.size());
5598 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005599
5600 AuthorizationSetBuilder begin_params;
5601 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5602 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07005603
5604 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5605 ++ciphertext[ciphertext.size() / 2];
5606
5607 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5608 string plaintext;
5609 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5610 ErrorCode error = Finish(&plaintext);
5611 if (error == ErrorCode::INVALID_ARGUMENT) {
5612 // This is the expected error, we can exit the test now.
5613 return;
5614 } else {
5615 // Very small chance we got valid decryption, so try again.
5616 ASSERT_EQ(error, ErrorCode::OK);
5617 }
5618 }
5619 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005620}
5621
5622struct TripleDesTestVector {
5623 const char* name;
5624 const KeyPurpose purpose;
5625 const BlockMode block_mode;
5626 const PaddingMode padding_mode;
5627 const char* key;
5628 const char* iv;
5629 const char* input;
5630 const char* output;
5631};
5632
5633// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5634// of the NIST vectors are multiples of the block size.
5635static const TripleDesTestVector kTripleDesTestVectors[] = {
5636 {
5637 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5638 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5639 "", // IV
5640 "329d86bdf1bc5af4", // input
5641 "d946c2756d78633f", // output
5642 },
5643 {
5644 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5645 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5646 "", // IV
5647 "6b1540781b01ce1997adae102dbf3c5b", // input
5648 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5649 },
5650 {
5651 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5652 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5653 "", // IV
5654 "6daad94ce08acfe7", // input
5655 "660e7d32dcc90e79", // output
5656 },
5657 {
5658 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5659 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5660 "", // IV
5661 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5662 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5663 },
5664 {
5665 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5666 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5667 "43f791134c5647ba", // IV
5668 "dcc153cef81d6f24", // input
5669 "92538bd8af18d3ba", // output
5670 },
5671 {
5672 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5673 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5674 "c2e999cb6249023c", // IV
5675 "c689aee38a301bb316da75db36f110b5", // input
5676 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5677 },
5678 {
5679 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5680 PaddingMode::PKCS7,
5681 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5682 "c2e999cb6249023c", // IV
5683 "c689aee38a301bb316da75db36f110b500", // input
5684 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5685 },
5686 {
5687 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5688 PaddingMode::PKCS7,
5689 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5690 "c2e999cb6249023c", // IV
5691 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5692 "c689aee38a301bb316da75db36f110b500", // output
5693 },
5694 {
5695 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5696 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5697 "41746c7e442d3681", // IV
5698 "c53a7b0ec40600fe", // input
5699 "d4f00eb455de1034", // output
5700 },
5701 {
5702 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5703 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5704 "3982bc02c3727d45", // IV
5705 "6006f10adef52991fcc777a1238bbb65", // input
5706 "edae09288e9e3bc05746d872b48e3b29", // output
5707 },
5708};
5709
5710/*
5711 * EncryptionOperationsTest.TripleDesTestVector
5712 *
5713 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5714 */
5715TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5716 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5717 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5718 SCOPED_TRACE(test->name);
5719 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5720 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5721 hex2str(test->output));
5722 }
5723}
5724
5725/*
5726 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5727 *
5728 * Validates CBC mode functionality.
5729 */
5730TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5731 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5732 .TripleDesEncryptionKey(168)
5733 .BlockMode(BlockMode::CBC)
5734 .Authorization(TAG_NO_AUTH_REQUIRED)
5735 .Padding(PaddingMode::NONE)));
5736
5737 ASSERT_GT(key_blob_.size(), 0U);
5738
5739 // Two-block message.
5740 string message = "1234567890123456";
5741 vector<uint8_t> iv1;
5742 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5743 EXPECT_EQ(message.size(), ciphertext1.size());
5744
5745 vector<uint8_t> iv2;
5746 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5747 EXPECT_EQ(message.size(), ciphertext2.size());
5748
5749 // IVs should be random, so ciphertexts should differ.
5750 EXPECT_NE(iv1, iv2);
5751 EXPECT_NE(ciphertext1, ciphertext2);
5752
5753 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5754 EXPECT_EQ(message, plaintext);
5755}
5756
5757/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005758 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5759 *
5760 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5761 */
5762TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5763 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5764 .TripleDesEncryptionKey(168)
5765 .BlockMode(BlockMode::CBC)
5766 .Authorization(TAG_NO_AUTH_REQUIRED)
5767 .Authorization(TAG_CALLER_NONCE)
5768 .Padding(PaddingMode::NONE)));
5769 auto params = AuthorizationSetBuilder()
5770 .BlockMode(BlockMode::CBC)
5771 .Padding(PaddingMode::NONE)
5772 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5773 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5774}
5775
5776/*
Selene Huang31ab4042020-04-29 04:22:39 -07005777 * EncryptionOperationsTest.TripleDesCallerIv
5778 *
5779 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5780 */
5781TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5782 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5783 .TripleDesEncryptionKey(168)
5784 .BlockMode(BlockMode::CBC)
5785 .Authorization(TAG_NO_AUTH_REQUIRED)
5786 .Authorization(TAG_CALLER_NONCE)
5787 .Padding(PaddingMode::NONE)));
5788 string message = "1234567890123456";
5789 vector<uint8_t> iv;
5790 // Don't specify IV, should get a random one.
5791 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5792 EXPECT_EQ(message.size(), ciphertext1.size());
5793 EXPECT_EQ(8U, iv.size());
5794
5795 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5796 EXPECT_EQ(message, plaintext);
5797
5798 // Now specify an IV, should also work.
5799 iv = AidlBuf("abcdefgh");
5800 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5801
5802 // Decrypt with correct IV.
5803 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5804 EXPECT_EQ(message, plaintext);
5805
5806 // Now try with wrong IV.
5807 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5808 EXPECT_NE(message, plaintext);
5809}
5810
5811/*
5812 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5813 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005814 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005815 */
5816TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5817 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5818 .TripleDesEncryptionKey(168)
5819 .BlockMode(BlockMode::CBC)
5820 .Authorization(TAG_NO_AUTH_REQUIRED)
5821 .Padding(PaddingMode::NONE)));
5822
5823 string message = "12345678901234567890123456789012";
5824 vector<uint8_t> iv;
5825 // Don't specify nonce, should get a random one.
5826 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5827 EXPECT_EQ(message.size(), ciphertext1.size());
5828 EXPECT_EQ(8U, iv.size());
5829
5830 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5831 EXPECT_EQ(message, plaintext);
5832
5833 // Now specify a nonce, should fail.
5834 auto input_params = AuthorizationSetBuilder()
5835 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5836 .BlockMode(BlockMode::CBC)
5837 .Padding(PaddingMode::NONE);
5838 AuthorizationSet output_params;
5839 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5840 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5841}
5842
5843/*
5844 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5845 *
5846 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5847 */
5848TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5849 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5850 .TripleDesEncryptionKey(168)
5851 .BlockMode(BlockMode::ECB)
5852 .Authorization(TAG_NO_AUTH_REQUIRED)
5853 .Padding(PaddingMode::NONE)));
5854 // Two-block message.
5855 string message = "1234567890123456";
5856 auto begin_params =
5857 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5858 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5859}
5860
5861/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005862 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005863 *
5864 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5865 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005866TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5867 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5868 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5869 .TripleDesEncryptionKey(168)
5870 .BlockMode(blockMode)
5871 .Authorization(TAG_NO_AUTH_REQUIRED)
5872 .Padding(PaddingMode::NONE)));
5873 // Message is slightly shorter than two blocks.
5874 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005875
David Drysdaled2cc8c22021-04-15 13:29:45 +01005876 auto begin_params =
5877 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5878 AuthorizationSet output_params;
5879 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5880 string ciphertext;
5881 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5882
5883 CheckedDeleteKey();
5884 }
Selene Huang31ab4042020-04-29 04:22:39 -07005885}
5886
5887/*
5888 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5889 *
5890 * Verifies that PKCS7 padding works correctly in CBC mode.
5891 */
5892TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5893 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5894 .TripleDesEncryptionKey(168)
5895 .BlockMode(BlockMode::CBC)
5896 .Authorization(TAG_NO_AUTH_REQUIRED)
5897 .Padding(PaddingMode::PKCS7)));
5898
5899 // Try various message lengths; all should work.
5900 for (size_t i = 0; i < 32; ++i) {
5901 string message(i, 'a');
5902 vector<uint8_t> iv;
5903 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5904 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5905 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5906 EXPECT_EQ(message, plaintext);
5907 }
5908}
5909
5910/*
5911 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5912 *
5913 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5914 */
5915TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5916 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5917 .TripleDesEncryptionKey(168)
5918 .BlockMode(BlockMode::CBC)
5919 .Authorization(TAG_NO_AUTH_REQUIRED)
5920 .Padding(PaddingMode::NONE)));
5921
5922 // Try various message lengths; all should fail.
5923 for (size_t i = 0; i < 32; ++i) {
5924 auto begin_params =
5925 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5926 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5927 }
5928}
5929
5930/*
5931 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5932 *
5933 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5934 */
5935TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5936 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5937 .TripleDesEncryptionKey(168)
5938 .BlockMode(BlockMode::CBC)
5939 .Authorization(TAG_NO_AUTH_REQUIRED)
5940 .Padding(PaddingMode::PKCS7)));
5941
5942 string message = "a";
5943 vector<uint8_t> iv;
5944 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5945 EXPECT_EQ(8U, ciphertext.size());
5946 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005947
5948 auto begin_params = AuthorizationSetBuilder()
5949 .BlockMode(BlockMode::CBC)
5950 .Padding(PaddingMode::PKCS7)
5951 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07005952
5953 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5954 ++ciphertext[ciphertext.size() / 2];
5955 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5956 string plaintext;
5957 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5958 ErrorCode error = Finish(&plaintext);
5959 if (error == ErrorCode::INVALID_ARGUMENT) {
5960 // This is the expected error, we can exit the test now.
5961 return;
5962 } else {
5963 // Very small chance we got valid decryption, so try again.
5964 ASSERT_EQ(error, ErrorCode::OK);
5965 }
5966 }
5967 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005968}
5969
5970/*
5971 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5972 *
5973 * Verifies that 3DES CBC works with many different input sizes.
5974 */
5975TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5976 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5977 .TripleDesEncryptionKey(168)
5978 .BlockMode(BlockMode::CBC)
5979 .Authorization(TAG_NO_AUTH_REQUIRED)
5980 .Padding(PaddingMode::NONE)));
5981
5982 int increment = 7;
5983 string message(240, 'a');
5984 AuthorizationSet input_params =
5985 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5986 AuthorizationSet output_params;
5987 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5988
5989 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005990 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005991 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005992 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5993 EXPECT_EQ(message.size(), ciphertext.size());
5994
5995 // Move TAG_NONCE into input_params
5996 input_params = output_params;
5997 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5998 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5999 output_params.Clear();
6000
6001 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
6002 string plaintext;
6003 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006004 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006005 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
6006 EXPECT_EQ(ciphertext.size(), plaintext.size());
6007 EXPECT_EQ(message, plaintext);
6008}
6009
6010INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
6011
6012typedef KeyMintAidlTestBase MaxOperationsTest;
6013
6014/*
6015 * MaxOperationsTest.TestLimitAes
6016 *
6017 * Verifies that the max uses per boot tag works correctly with AES keys.
6018 */
6019TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006020 if (SecLevel() == SecurityLevel::STRONGBOX) {
6021 GTEST_SKIP() << "Test not applicable to StrongBox device";
6022 }
Selene Huang31ab4042020-04-29 04:22:39 -07006023
6024 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6025 .Authorization(TAG_NO_AUTH_REQUIRED)
6026 .AesEncryptionKey(128)
6027 .EcbMode()
6028 .Padding(PaddingMode::NONE)
6029 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
6030
6031 string message = "1234567890123456";
6032
6033 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6034
6035 EncryptMessage(message, params);
6036 EncryptMessage(message, params);
6037 EncryptMessage(message, params);
6038
6039 // Fourth time should fail.
6040 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
6041}
6042
6043/*
Qi Wud22ec842020-11-26 13:27:53 +08006044 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07006045 *
6046 * Verifies that the max uses per boot tag works correctly with RSA keys.
6047 */
6048TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006049 if (SecLevel() == SecurityLevel::STRONGBOX) {
6050 GTEST_SKIP() << "Test not applicable to StrongBox device";
6051 }
Selene Huang31ab4042020-04-29 04:22:39 -07006052
6053 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6054 .Authorization(TAG_NO_AUTH_REQUIRED)
6055 .RsaSigningKey(1024, 65537)
6056 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006057 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
6058 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006059
6060 string message = "1234567890123456";
6061
6062 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6063
6064 SignMessage(message, params);
6065 SignMessage(message, params);
6066 SignMessage(message, params);
6067
6068 // Fourth time should fail.
6069 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6070}
6071
6072INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6073
Qi Wud22ec842020-11-26 13:27:53 +08006074typedef KeyMintAidlTestBase UsageCountLimitTest;
6075
6076/*
Qi Wubeefae42021-01-28 23:16:37 +08006077 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006078 *
Qi Wubeefae42021-01-28 23:16:37 +08006079 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006080 */
Qi Wubeefae42021-01-28 23:16:37 +08006081TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006082 if (SecLevel() == SecurityLevel::STRONGBOX) {
6083 GTEST_SKIP() << "Test not applicable to StrongBox device";
6084 }
Qi Wud22ec842020-11-26 13:27:53 +08006085
6086 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6087 .Authorization(TAG_NO_AUTH_REQUIRED)
6088 .AesEncryptionKey(128)
6089 .EcbMode()
6090 .Padding(PaddingMode::NONE)
6091 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
6092
6093 // Check the usage count limit tag appears in the authorizations.
6094 AuthorizationSet auths;
6095 for (auto& entry : key_characteristics_) {
6096 auths.push_back(AuthorizationSet(entry.authorizations));
6097 }
6098 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6099 << "key usage count limit " << 1U << " missing";
6100
6101 string message = "1234567890123456";
6102 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6103
Qi Wubeefae42021-01-28 23:16:37 +08006104 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6105 AuthorizationSet keystore_auths =
6106 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6107
Qi Wud22ec842020-11-26 13:27:53 +08006108 // First usage of AES key should work.
6109 EncryptMessage(message, params);
6110
Qi Wud22ec842020-11-26 13:27:53 +08006111 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6112 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6113 // must be invalidated from secure storage (such as RPMB partition).
6114 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6115 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006116 // Usage count limit tag is enforced by keystore, keymint does nothing.
6117 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08006118 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6119 }
6120}
6121
6122/*
Qi Wubeefae42021-01-28 23:16:37 +08006123 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006124 *
Qi Wubeefae42021-01-28 23:16:37 +08006125 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006126 */
Qi Wubeefae42021-01-28 23:16:37 +08006127TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006128 if (SecLevel() == SecurityLevel::STRONGBOX) {
6129 GTEST_SKIP() << "Test not applicable to StrongBox device";
6130 }
Qi Wubeefae42021-01-28 23:16:37 +08006131
6132 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6133 .Authorization(TAG_NO_AUTH_REQUIRED)
6134 .AesEncryptionKey(128)
6135 .EcbMode()
6136 .Padding(PaddingMode::NONE)
6137 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
6138
6139 // Check the usage count limit tag appears in the authorizations.
6140 AuthorizationSet auths;
6141 for (auto& entry : key_characteristics_) {
6142 auths.push_back(AuthorizationSet(entry.authorizations));
6143 }
6144 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6145 << "key usage count limit " << 3U << " missing";
6146
6147 string message = "1234567890123456";
6148 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6149
6150 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6151 AuthorizationSet keystore_auths =
6152 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6153
6154 EncryptMessage(message, params);
6155 EncryptMessage(message, params);
6156 EncryptMessage(message, params);
6157
6158 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6159 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6160 // must be invalidated from secure storage (such as RPMB partition).
6161 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6162 } else {
6163 // Usage count limit tag is enforced by keystore, keymint does nothing.
6164 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
6165 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6166 }
6167}
6168
6169/*
6170 * UsageCountLimitTest.TestSingleUseRsa
6171 *
6172 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
6173 */
6174TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006175 if (SecLevel() == SecurityLevel::STRONGBOX) {
6176 GTEST_SKIP() << "Test not applicable to StrongBox device";
6177 }
Qi Wud22ec842020-11-26 13:27:53 +08006178
6179 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6180 .Authorization(TAG_NO_AUTH_REQUIRED)
6181 .RsaSigningKey(1024, 65537)
6182 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006183 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6184 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08006185
6186 // Check the usage count limit tag appears in the authorizations.
6187 AuthorizationSet auths;
6188 for (auto& entry : key_characteristics_) {
6189 auths.push_back(AuthorizationSet(entry.authorizations));
6190 }
6191 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6192 << "key usage count limit " << 1U << " missing";
6193
6194 string message = "1234567890123456";
6195 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6196
Qi Wubeefae42021-01-28 23:16:37 +08006197 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6198 AuthorizationSet keystore_auths =
6199 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6200
Qi Wud22ec842020-11-26 13:27:53 +08006201 // First usage of RSA key should work.
6202 SignMessage(message, params);
6203
Qi Wud22ec842020-11-26 13:27:53 +08006204 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6205 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6206 // must be invalidated from secure storage (such as RPMB partition).
6207 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6208 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006209 // Usage count limit tag is enforced by keystore, keymint does nothing.
6210 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
6211 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6212 }
6213}
6214
6215/*
6216 * UsageCountLimitTest.TestLimitUseRsa
6217 *
6218 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
6219 */
6220TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006221 if (SecLevel() == SecurityLevel::STRONGBOX) {
6222 GTEST_SKIP() << "Test not applicable to StrongBox device";
6223 }
Qi Wubeefae42021-01-28 23:16:37 +08006224
6225 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6226 .Authorization(TAG_NO_AUTH_REQUIRED)
6227 .RsaSigningKey(1024, 65537)
6228 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006229 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6230 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006231
6232 // Check the usage count limit tag appears in the authorizations.
6233 AuthorizationSet auths;
6234 for (auto& entry : key_characteristics_) {
6235 auths.push_back(AuthorizationSet(entry.authorizations));
6236 }
6237 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6238 << "key usage count limit " << 3U << " missing";
6239
6240 string message = "1234567890123456";
6241 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6242
6243 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6244 AuthorizationSet keystore_auths =
6245 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6246
6247 SignMessage(message, params);
6248 SignMessage(message, params);
6249 SignMessage(message, params);
6250
6251 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6252 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6253 // must be invalidated from secure storage (such as RPMB partition).
6254 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6255 } else {
6256 // Usage count limit tag is enforced by keystore, keymint does nothing.
6257 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006258 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6259 }
6260}
6261
Qi Wu8e727f72021-02-11 02:49:33 +08006262/*
6263 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6264 *
6265 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6266 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6267 * in hardware.
6268 */
6269TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01006270 if (SecLevel() == SecurityLevel::STRONGBOX) {
6271 GTEST_SKIP() << "Test not applicable to StrongBox device";
6272 }
Qi Wu8e727f72021-02-11 02:49:33 +08006273
6274 auto error = GenerateKey(AuthorizationSetBuilder()
6275 .RsaSigningKey(2048, 65537)
6276 .Digest(Digest::NONE)
6277 .Padding(PaddingMode::NONE)
6278 .Authorization(TAG_NO_AUTH_REQUIRED)
6279 .Authorization(TAG_ROLLBACK_RESISTANCE)
6280 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006281 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6282 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08006283 }
David Drysdale513bf122021-10-06 11:53:13 +01006284
6285 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6286 ASSERT_EQ(ErrorCode::OK, error);
6287 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6288 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6289 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6290
6291 // The KeyMint should also enforce single use key in hardware when it supports rollback
6292 // resistance.
6293 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6294 .Authorization(TAG_NO_AUTH_REQUIRED)
6295 .RsaSigningKey(1024, 65537)
6296 .NoDigestOrPadding()
6297 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6298 .SetDefaultValidity()));
6299
6300 // Check the usage count limit tag appears in the hardware authorizations.
6301 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6302 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6303 << "key usage count limit " << 1U << " missing";
6304
6305 string message = "1234567890123456";
6306 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6307
6308 // First usage of RSA key should work.
6309 SignMessage(message, params);
6310
6311 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6312 // must be invalidated from secure storage (such as RPMB partition).
6313 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08006314}
6315
Qi Wud22ec842020-11-26 13:27:53 +08006316INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6317
David Drysdale7de9feb2021-03-05 14:56:19 +00006318typedef KeyMintAidlTestBase GetHardwareInfoTest;
6319
6320TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6321 // Retrieving hardware info should give the same result each time.
6322 KeyMintHardwareInfo info;
6323 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6324 KeyMintHardwareInfo info2;
6325 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6326 EXPECT_EQ(info, info2);
6327}
6328
6329INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6330
Selene Huang31ab4042020-04-29 04:22:39 -07006331typedef KeyMintAidlTestBase AddEntropyTest;
6332
6333/*
6334 * AddEntropyTest.AddEntropy
6335 *
6336 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6337 * is actually added.
6338 */
6339TEST_P(AddEntropyTest, AddEntropy) {
6340 string data = "foo";
6341 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6342}
6343
6344/*
6345 * AddEntropyTest.AddEmptyEntropy
6346 *
6347 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6348 */
6349TEST_P(AddEntropyTest, AddEmptyEntropy) {
6350 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6351}
6352
6353/*
6354 * AddEntropyTest.AddLargeEntropy
6355 *
6356 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6357 */
6358TEST_P(AddEntropyTest, AddLargeEntropy) {
6359 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6360}
6361
David Drysdalebb3d85e2021-04-13 11:15:51 +01006362/*
6363 * AddEntropyTest.AddTooLargeEntropy
6364 *
6365 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6366 */
6367TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6368 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6369 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6370}
6371
Selene Huang31ab4042020-04-29 04:22:39 -07006372INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6373
Selene Huang31ab4042020-04-29 04:22:39 -07006374typedef KeyMintAidlTestBase KeyDeletionTest;
6375
6376/**
6377 * KeyDeletionTest.DeleteKey
6378 *
6379 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6380 * valid key blob.
6381 */
6382TEST_P(KeyDeletionTest, DeleteKey) {
6383 auto error = GenerateKey(AuthorizationSetBuilder()
6384 .RsaSigningKey(2048, 65537)
6385 .Digest(Digest::NONE)
6386 .Padding(PaddingMode::NONE)
6387 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006388 .Authorization(TAG_ROLLBACK_RESISTANCE)
6389 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006390 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6391 GTEST_SKIP() << "Rollback resistance not supported";
6392 }
Selene Huang31ab4042020-04-29 04:22:39 -07006393
6394 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006395 ASSERT_EQ(ErrorCode::OK, error);
6396 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6397 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006398
David Drysdale513bf122021-10-06 11:53:13 +01006399 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07006400
David Drysdale513bf122021-10-06 11:53:13 +01006401 string message = "12345678901234567890123456789012";
6402 AuthorizationSet begin_out_params;
6403 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6404 Begin(KeyPurpose::SIGN, key_blob_,
6405 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6406 &begin_out_params));
6407 AbortIfNeeded();
6408 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006409}
6410
6411/**
6412 * KeyDeletionTest.DeleteInvalidKey
6413 *
6414 * This test checks that the HAL excepts invalid key blobs..
6415 */
6416TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6417 // Generate key just to check if rollback protection is implemented
6418 auto error = GenerateKey(AuthorizationSetBuilder()
6419 .RsaSigningKey(2048, 65537)
6420 .Digest(Digest::NONE)
6421 .Padding(PaddingMode::NONE)
6422 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006423 .Authorization(TAG_ROLLBACK_RESISTANCE)
6424 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006425 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6426 GTEST_SKIP() << "Rollback resistance not supported";
6427 }
Selene Huang31ab4042020-04-29 04:22:39 -07006428
6429 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006430 ASSERT_EQ(ErrorCode::OK, error);
6431 AuthorizationSet enforced(SecLevelAuthorizations());
6432 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006433
David Drysdale513bf122021-10-06 11:53:13 +01006434 // Delete the key we don't care about the result at this point.
6435 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07006436
David Drysdale513bf122021-10-06 11:53:13 +01006437 // Now create an invalid key blob and delete it.
6438 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07006439
David Drysdale513bf122021-10-06 11:53:13 +01006440 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07006441}
6442
6443/**
6444 * KeyDeletionTest.DeleteAllKeys
6445 *
6446 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6447 *
6448 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6449 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6450 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6451 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6452 * credentials stored in Keystore/Keymint.
6453 */
6454TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01006455 if (!arm_deleteAllKeys) {
6456 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
6457 return;
6458 }
Selene Huang31ab4042020-04-29 04:22:39 -07006459 auto error = GenerateKey(AuthorizationSetBuilder()
6460 .RsaSigningKey(2048, 65537)
6461 .Digest(Digest::NONE)
6462 .Padding(PaddingMode::NONE)
6463 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06006464 .Authorization(TAG_ROLLBACK_RESISTANCE)
6465 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006466 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6467 GTEST_SKIP() << "Rollback resistance not supported";
6468 }
Selene Huang31ab4042020-04-29 04:22:39 -07006469
6470 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006471 ASSERT_EQ(ErrorCode::OK, error);
6472 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6473 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006474
David Drysdale513bf122021-10-06 11:53:13 +01006475 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07006476
David Drysdale513bf122021-10-06 11:53:13 +01006477 string message = "12345678901234567890123456789012";
6478 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07006479
David Drysdale513bf122021-10-06 11:53:13 +01006480 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6481 Begin(KeyPurpose::SIGN, key_blob_,
6482 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6483 &begin_out_params));
6484 AbortIfNeeded();
6485 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006486}
6487
6488INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6489
David Drysdaled2cc8c22021-04-15 13:29:45 +01006490typedef KeyMintAidlTestBase KeyUpgradeTest;
6491
6492/**
6493 * KeyUpgradeTest.UpgradeInvalidKey
6494 *
6495 * This test checks that the HAL excepts invalid key blobs..
6496 */
6497TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6498 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6499
6500 std::vector<uint8_t> new_blob;
6501 Status result = keymint_->upgradeKey(key_blob,
6502 AuthorizationSetBuilder()
6503 .Authorization(TAG_APPLICATION_ID, "clientid")
6504 .Authorization(TAG_APPLICATION_DATA, "appdata")
6505 .vector_data(),
6506 &new_blob);
6507 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6508}
6509
6510INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6511
Selene Huang31ab4042020-04-29 04:22:39 -07006512using UpgradeKeyTest = KeyMintAidlTestBase;
6513
6514/*
6515 * UpgradeKeyTest.UpgradeKey
6516 *
6517 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6518 */
6519TEST_P(UpgradeKeyTest, UpgradeKey) {
6520 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6521 .AesEncryptionKey(128)
6522 .Padding(PaddingMode::NONE)
6523 .Authorization(TAG_NO_AUTH_REQUIRED)));
6524
6525 auto result = UpgradeKey(key_blob_);
6526
6527 // Key doesn't need upgrading. Should get okay, but no new key blob.
6528 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6529}
6530
6531INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6532
6533using ClearOperationsTest = KeyMintAidlTestBase;
6534
6535/*
6536 * ClearSlotsTest.TooManyOperations
6537 *
6538 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6539 * operations are started without being finished or aborted. Also verifies
6540 * that aborting the operations clears the operations.
6541 *
6542 */
6543TEST_P(ClearOperationsTest, TooManyOperations) {
6544 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6545 .Authorization(TAG_NO_AUTH_REQUIRED)
6546 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006547 .Padding(PaddingMode::NONE)
6548 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006549
6550 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6551 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006552 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006553 AuthorizationSet out_params;
6554 ErrorCode result;
6555 size_t i;
6556
6557 for (i = 0; i < max_operations; i++) {
6558 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6559 if (ErrorCode::OK != result) {
6560 break;
6561 }
6562 }
6563 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6564 // Try again just in case there's a weird overflow bug
6565 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6566 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6567 for (size_t j = 0; j < i; j++) {
6568 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6569 << "Aboort failed for i = " << j << std::endl;
6570 }
6571 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6572 AbortIfNeeded();
6573}
6574
6575INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6576
6577typedef KeyMintAidlTestBase TransportLimitTest;
6578
6579/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006580 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006581 *
6582 * Verifies that passing input data to finish succeeds as expected.
6583 */
6584TEST_P(TransportLimitTest, LargeFinishInput) {
6585 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6586 .Authorization(TAG_NO_AUTH_REQUIRED)
6587 .AesEncryptionKey(128)
6588 .BlockMode(BlockMode::ECB)
6589 .Padding(PaddingMode::NONE)));
6590
6591 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6592 auto cipher_params =
6593 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6594
6595 AuthorizationSet out_params;
6596 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6597
6598 string plain_message = std::string(1 << msg_size, 'x');
6599 string encrypted_message;
6600 auto rc = Finish(plain_message, &encrypted_message);
6601
6602 EXPECT_EQ(ErrorCode::OK, rc);
6603 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6604 << "Encrypt finish returned OK, but did not consume all of the given input";
6605 cipher_params.push_back(out_params);
6606
6607 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6608
6609 string decrypted_message;
6610 rc = Finish(encrypted_message, &decrypted_message);
6611 EXPECT_EQ(ErrorCode::OK, rc);
6612 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6613 << "Decrypt finish returned OK, did not consume all of the given input";
6614 }
6615}
6616
6617INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6618
David Zeuthene0c40892021-01-08 12:54:11 -05006619typedef KeyMintAidlTestBase KeyAgreementTest;
6620
Seth Moored79a0ec2021-12-13 20:03:33 +00006621static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05006622 switch (curve) {
6623 case EcCurve::P_224:
6624 return NID_secp224r1;
6625 case EcCurve::P_256:
6626 return NID_X9_62_prime256v1;
6627 case EcCurve::P_384:
6628 return NID_secp384r1;
6629 case EcCurve::P_521:
6630 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00006631 case EcCurve::CURVE_25519:
6632 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05006633 }
6634}
6635
6636/*
6637 * KeyAgreementTest.Ecdh
6638 *
6639 * Verifies that ECDH works for all curves
6640 */
6641TEST_P(KeyAgreementTest, Ecdh) {
6642 // Because it's possible to use this API with keys on different curves, we
6643 // check all N^2 combinations where N is the number of supported
6644 // curves.
6645 //
6646 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6647 // lot more curves we can be smart about things and just pick |otherCurve| so
6648 // it's not |curve| and that way we end up with only 2*N runs
6649 //
6650 for (auto curve : ValidCurves()) {
6651 for (auto localCurve : ValidCurves()) {
6652 // Generate EC key locally (with access to private key material)
6653 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
Seth Moored79a0ec2021-12-13 20:03:33 +00006654 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
David Zeuthene0c40892021-01-08 12:54:11 -05006655 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6656 ASSERT_NE(group, nullptr);
6657 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6658 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6659 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6660 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6661
6662 // Get encoded form of the public part of the locally generated key...
6663 unsigned char* p = nullptr;
6664 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6665 ASSERT_GT(encodedPublicKeySize, 0);
6666 vector<uint8_t> encodedPublicKey(
6667 reinterpret_cast<const uint8_t*>(p),
6668 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6669 OPENSSL_free(p);
6670
6671 // Generate EC key in KeyMint (only access to public key material)
6672 vector<uint8_t> challenge = {0x41, 0x42};
6673 EXPECT_EQ(
6674 ErrorCode::OK,
6675 GenerateKey(AuthorizationSetBuilder()
6676 .Authorization(TAG_NO_AUTH_REQUIRED)
6677 .Authorization(TAG_EC_CURVE, curve)
6678 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6679 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6680 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006681 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6682 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006683 << "Failed to generate key";
6684 ASSERT_GT(cert_chain_.size(), 0);
6685 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6686 ASSERT_NE(kmKeyCert, nullptr);
6687 // Check that keyAgreement (bit 4) is set in KeyUsage
6688 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6689 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6690 ASSERT_NE(kmPkey, nullptr);
6691 if (dump_Attestations) {
6692 for (size_t n = 0; n < cert_chain_.size(); n++) {
6693 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6694 }
6695 }
6696
6697 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6698 if (curve != localCurve) {
6699 // If the keys are using different curves KeyMint should fail with
6700 // ErrorCode:INVALID_ARGUMENT. Check that.
6701 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6702 string ZabFromKeyMintStr;
6703 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6704 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6705 &ZabFromKeyMintStr));
6706
6707 } else {
6708 // Otherwise if the keys are using the same curve, it should work.
6709 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6710 string ZabFromKeyMintStr;
6711 EXPECT_EQ(ErrorCode::OK,
6712 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6713 &ZabFromKeyMintStr));
6714 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6715
6716 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6717 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6718 ASSERT_NE(ctx, nullptr);
6719 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6720 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6721 size_t ZabFromTestLen = 0;
6722 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6723 vector<uint8_t> ZabFromTest;
6724 ZabFromTest.resize(ZabFromTestLen);
6725 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6726
6727 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6728 }
6729
6730 CheckedDeleteKey();
6731 }
6732 }
6733}
6734
6735INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6736
David Drysdaled2cc8c22021-04-15 13:29:45 +01006737using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6738
6739// This is a problematic test, as it can render the device under test permanently unusable.
6740// Re-enable and run at your own risk.
6741TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6742 auto result = DestroyAttestationIds();
6743 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6744}
6745
6746INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6747
Shawn Willdend659c7c2021-02-19 14:51:51 -07006748using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006749
David Drysdaledb0dcf52021-05-18 11:43:31 +01006750/*
6751 * EarlyBootKeyTest.CreateEarlyBootKeys
6752 *
6753 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6754 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006755TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01006756 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006757 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6758 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6759
David Drysdaleadfe6112021-05-27 12:00:53 +01006760 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6761 ASSERT_GT(keyData.blob.size(), 0U);
6762 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6763 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6764 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006765 CheckedDeleteKey(&aesKeyData.blob);
6766 CheckedDeleteKey(&hmacKeyData.blob);
6767 CheckedDeleteKey(&rsaKeyData.blob);
6768 CheckedDeleteKey(&ecdsaKeyData.blob);
6769}
6770
David Drysdaledb0dcf52021-05-18 11:43:31 +01006771/*
David Drysdaleadfe6112021-05-27 12:00:53 +01006772 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6773 *
6774 * Verifies that creating an early boot key with attestation succeeds.
6775 */
6776TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6777 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6778 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6779 builder->AttestationChallenge("challenge");
6780 builder->AttestationApplicationId("app_id");
6781 });
6782
6783 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6784 ASSERT_GT(keyData.blob.size(), 0U);
6785 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6786 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6787 }
6788 CheckedDeleteKey(&aesKeyData.blob);
6789 CheckedDeleteKey(&hmacKeyData.blob);
6790 CheckedDeleteKey(&rsaKeyData.blob);
6791 CheckedDeleteKey(&ecdsaKeyData.blob);
6792}
6793
6794/*
6795 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01006796 *
6797 * Verifies that using early boot keys at a later stage fails.
6798 */
6799TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6800 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6801 .Authorization(TAG_NO_AUTH_REQUIRED)
6802 .Authorization(TAG_EARLY_BOOT_ONLY)
6803 .HmacKey(128)
6804 .Digest(Digest::SHA_2_256)
6805 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6806 AuthorizationSet output_params;
6807 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6808 AuthorizationSetBuilder()
6809 .Digest(Digest::SHA_2_256)
6810 .Authorization(TAG_MAC_LENGTH, 256),
6811 &output_params));
6812}
6813
6814/*
6815 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6816 *
6817 * Verifies that importing early boot keys fails.
6818 */
6819TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6820 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6821 .Authorization(TAG_NO_AUTH_REQUIRED)
6822 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01006823 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01006824 .Digest(Digest::SHA_2_256)
6825 .SetDefaultValidity(),
6826 KeyFormat::PKCS8, ec_256_key));
6827}
6828
David Drysdaled2cc8c22021-04-15 13:29:45 +01006829// 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 +00006830// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6831// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6832// early boot, so you'll have to reboot between runs.
6833TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6834 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6835 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6836 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6837 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6838 EXPECT_TRUE(
6839 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6840 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6841 EXPECT_TRUE(
6842 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6843
6844 // Should be able to use keys, since early boot has not ended
6845 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6846 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6847 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6848 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6849
6850 // End early boot
6851 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6852 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6853
6854 // Should not be able to use already-created keys.
6855 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6856 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6857 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6858 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6859
6860 CheckedDeleteKey(&aesKeyData.blob);
6861 CheckedDeleteKey(&hmacKeyData.blob);
6862 CheckedDeleteKey(&rsaKeyData.blob);
6863 CheckedDeleteKey(&ecdsaKeyData.blob);
6864
6865 // Should not be able to create new keys
6866 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6867 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6868
6869 CheckedDeleteKey(&aesKeyData.blob);
6870 CheckedDeleteKey(&hmacKeyData.blob);
6871 CheckedDeleteKey(&rsaKeyData.blob);
6872 CheckedDeleteKey(&ecdsaKeyData.blob);
6873}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006874
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006875INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6876
Shawn Willdend659c7c2021-02-19 14:51:51 -07006877using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006878
6879// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6880// between runs... and on most test devices there are no enrolled credentials so it can't be
6881// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6882// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6883// a manual test process, which includes unlocking between runs, which is why it's included here.
6884// Well, that and the fact that it's the only test we can do without also making calls into the
6885// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6886// implications might be, so that may or may not be a solution.
6887TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6888 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6889 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6890
6891 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6892 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6893 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6894 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6895
6896 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006897 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006898 ASSERT_EQ(ErrorCode::OK, rc);
6899 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6900 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6901 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6902 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6903
6904 CheckedDeleteKey(&aesKeyData.blob);
6905 CheckedDeleteKey(&hmacKeyData.blob);
6906 CheckedDeleteKey(&rsaKeyData.blob);
6907 CheckedDeleteKey(&ecdsaKeyData.blob);
6908}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006909
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006910INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6911
Janis Danisevskis24c04702020-12-16 18:28:39 -08006912} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006913
6914int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006915 std::cout << "Testing ";
6916 auto halInstances =
6917 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6918 std::cout << "HAL instances:\n";
6919 for (auto& entry : halInstances) {
6920 std::cout << " " << entry << '\n';
6921 }
6922
Selene Huang31ab4042020-04-29 04:22:39 -07006923 ::testing::InitGoogleTest(&argc, argv);
6924 for (int i = 1; i < argc; ++i) {
6925 if (argv[i][0] == '-') {
6926 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006927 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6928 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006929 }
6930 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006931 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6932 dump_Attestations = true;
6933 } else {
6934 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006935 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00006936 if (std::string(argv[i]) == "--skip_boot_pl_check") {
6937 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
6938 // be run in emulated environments that don't have the normal bootloader
6939 // interactions.
6940 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
6941 }
Selene Huang31ab4042020-04-29 04:22:39 -07006942 }
6943 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006944 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006945}