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