blob: 49fe5fbea5501049ab52302ac872ae3bbe3cae4d [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/*
3358 * ImportKeyTest.EcdsaSuccess
3359 *
3360 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3361 */
3362TEST_P(ImportKeyTest, EcdsaSuccess) {
3363 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3364 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003365 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003366 .Digest(Digest::SHA_2_256)
3367 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003368 KeyFormat::PKCS8, ec_256_key));
3369
3370 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003371 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3372 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3373
3374 CheckOrigin();
3375
3376 string message(32, 'a');
3377 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3378 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003379 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003380}
3381
3382/*
3383 * ImportKeyTest.EcdsaP256RFC5915Success
3384 *
3385 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3386 * correctly.
3387 */
3388TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3389 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3390 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003391 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003392 .Digest(Digest::SHA_2_256)
3393 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003394 KeyFormat::PKCS8, ec_256_key_rfc5915));
3395
3396 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003397 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3398 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3399
3400 CheckOrigin();
3401
3402 string message(32, 'a');
3403 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3404 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003405 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003406}
3407
3408/*
3409 * ImportKeyTest.EcdsaP256SEC1Success
3410 *
3411 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3412 */
3413TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3414 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3415 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003416 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003417 .Digest(Digest::SHA_2_256)
3418 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003419 KeyFormat::PKCS8, ec_256_key_sec1));
3420
3421 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003422 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3423 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3424
3425 CheckOrigin();
3426
3427 string message(32, 'a');
3428 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3429 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003430 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003431}
3432
3433/*
3434 * ImportKeyTest.Ecdsa521Success
3435 *
3436 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3437 */
3438TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01003439 if (SecLevel() == SecurityLevel::STRONGBOX) {
3440 GTEST_SKIP() << "Test not applicable to StrongBox device";
3441 }
Selene Huang31ab4042020-04-29 04:22:39 -07003442 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3443 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003444 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003445 .Digest(Digest::SHA_2_256)
3446 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003447 KeyFormat::PKCS8, ec_521_key));
3448
3449 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003450 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3451 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3452 CheckOrigin();
3453
3454 string message(32, 'a');
3455 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3456 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003457 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003458}
3459
3460/*
Selene Huang31ab4042020-04-29 04:22:39 -07003461 * ImportKeyTest.EcdsaCurveMismatch
3462 *
3463 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3464 * the correct way.
3465 */
3466TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3467 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3468 ImportKey(AuthorizationSetBuilder()
3469 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003470 .Digest(Digest::NONE)
3471 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003472 KeyFormat::PKCS8, ec_256_key));
3473}
3474
3475/*
3476 * ImportKeyTest.AesSuccess
3477 *
3478 * Verifies that importing and using an AES key works.
3479 */
3480TEST_P(ImportKeyTest, AesSuccess) {
3481 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3482 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3483 .Authorization(TAG_NO_AUTH_REQUIRED)
3484 .AesEncryptionKey(key.size() * 8)
3485 .EcbMode()
3486 .Padding(PaddingMode::PKCS7),
3487 KeyFormat::RAW, key));
3488
3489 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3490 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3491 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3492 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3493 CheckOrigin();
3494
3495 string message = "Hello World!";
3496 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3497 string ciphertext = EncryptMessage(message, params);
3498 string plaintext = DecryptMessage(ciphertext, params);
3499 EXPECT_EQ(message, plaintext);
3500}
3501
3502/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003503 * ImportKeyTest.AesFailure
3504 *
3505 * Verifies that importing an invalid AES key fails.
3506 */
3507TEST_P(ImportKeyTest, AesFailure) {
3508 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3509 uint32_t bitlen = key.size() * 8;
3510 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003511 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003512 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003513 .Authorization(TAG_NO_AUTH_REQUIRED)
3514 .AesEncryptionKey(key_size)
3515 .EcbMode()
3516 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003517 KeyFormat::RAW, key);
3518 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003519 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3520 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003521 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003522
3523 // Explicit key size matches that of the provided key, but it's not a valid size.
3524 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3525 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3526 ImportKey(AuthorizationSetBuilder()
3527 .Authorization(TAG_NO_AUTH_REQUIRED)
3528 .AesEncryptionKey(long_key.size() * 8)
3529 .EcbMode()
3530 .Padding(PaddingMode::PKCS7),
3531 KeyFormat::RAW, long_key));
3532 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3533 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3534 ImportKey(AuthorizationSetBuilder()
3535 .Authorization(TAG_NO_AUTH_REQUIRED)
3536 .AesEncryptionKey(short_key.size() * 8)
3537 .EcbMode()
3538 .Padding(PaddingMode::PKCS7),
3539 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003540}
3541
3542/*
3543 * ImportKeyTest.TripleDesSuccess
3544 *
3545 * Verifies that importing and using a 3DES key works.
3546 */
3547TEST_P(ImportKeyTest, TripleDesSuccess) {
3548 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3549 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3550 .Authorization(TAG_NO_AUTH_REQUIRED)
3551 .TripleDesEncryptionKey(168)
3552 .EcbMode()
3553 .Padding(PaddingMode::PKCS7),
3554 KeyFormat::RAW, key));
3555
3556 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3557 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3558 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3559 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3560 CheckOrigin();
3561
3562 string message = "Hello World!";
3563 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3564 string ciphertext = EncryptMessage(message, params);
3565 string plaintext = DecryptMessage(ciphertext, params);
3566 EXPECT_EQ(message, plaintext);
3567}
3568
3569/*
3570 * ImportKeyTest.TripleDesFailure
3571 *
3572 * Verifies that importing an invalid 3DES key fails.
3573 */
3574TEST_P(ImportKeyTest, TripleDesFailure) {
3575 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003576 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003577 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003578 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003579 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003580 .Authorization(TAG_NO_AUTH_REQUIRED)
3581 .TripleDesEncryptionKey(key_size)
3582 .EcbMode()
3583 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003584 KeyFormat::RAW, key);
3585 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003586 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3587 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003588 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003589 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003590 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003591 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3592 ImportKey(AuthorizationSetBuilder()
3593 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003594 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003595 .EcbMode()
3596 .Padding(PaddingMode::PKCS7),
3597 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003598 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003599 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3600 ImportKey(AuthorizationSetBuilder()
3601 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003602 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003603 .EcbMode()
3604 .Padding(PaddingMode::PKCS7),
3605 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003606}
3607
3608/*
3609 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003610 *
3611 * Verifies that importing and using an HMAC key works.
3612 */
3613TEST_P(ImportKeyTest, HmacKeySuccess) {
3614 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3615 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3616 .Authorization(TAG_NO_AUTH_REQUIRED)
3617 .HmacKey(key.size() * 8)
3618 .Digest(Digest::SHA_2_256)
3619 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3620 KeyFormat::RAW, key));
3621
3622 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3623 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3624 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3625 CheckOrigin();
3626
3627 string message = "Hello World!";
3628 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3629 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3630}
3631
3632INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3633
3634auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003635 // IKeyMintDevice.aidl
3636 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3637 "020100" // INTEGER length 1 value 0x00 (version)
3638 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3639 "934bf94e2aa28a3f83c9f79297250262"
3640 "fbe3276b5a1c91159bbfa3ef8957aac8"
3641 "4b59b30b455a79c2973480823d8b3863"
3642 "c3deef4a8e243590268d80e18751a0e1"
3643 "30f67ce6a1ace9f79b95e097474febc9"
3644 "81195b1d13a69086c0863f66a7b7fdb4"
3645 "8792227b1ac5e2489febdf087ab54864"
3646 "83033a6f001ca5d1ec1e27f5c30f4cec"
3647 "2642074a39ae68aee552e196627a8e3d"
3648 "867e67a8c01b11e75f13cca0a97ab668"
3649 "b50cda07a8ecb7cd8e3dd7009c963653"
3650 "4f6f239cffe1fc8daa466f78b676c711"
3651 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3652 "99b801597d5220e307eaa5bee507fb94"
3653 "d1fa69f9e519b2de315bac92c36f2ea1"
3654 "fa1df4478c0ddedeae8c70e0233cd098"
3655 "040c" // OCTET STRING length 0x0c (initializationVector)
3656 "d796b02c370f1fa4cc0124f1"
3657 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3658 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3659 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3660 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3661 "3106" // SET length 0x06
3662 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3663 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3664 // } end SET
3665 // } end [1]
3666 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3667 "020120" // INTEGER length 1 value 0x20 (AES)
3668 // } end [2]
3669 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3670 "02020100" // INTEGER length 2 value 0x100
3671 // } end [3]
3672 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3673 "3103" // SET length 0x03 {
3674 "020101" // INTEGER length 1 value 0x01 (ECB)
3675 // } end SET
3676 // } end [4]
3677 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3678 "3103" // SET length 0x03 {
3679 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3680 // } end SET
3681 // } end [5]
3682 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3683 // (noAuthRequired)
3684 "0500" // NULL
3685 // } end [503]
3686 // } end SEQUENCE (AuthorizationList)
3687 // } end SEQUENCE (KeyDescription)
3688 "0420" // OCTET STRING length 0x20 (encryptedKey)
3689 "ccd540855f833a5e1480bfd2d36faf3a"
3690 "eee15df5beabe2691bc82dde2a7aa910"
3691 "0410" // OCTET STRING length 0x10 (tag)
3692 "64c9f689c60ff6223ab6e6999e0eb6e5"
3693 // } SEQUENCE (SecureKeyWrapper)
3694);
Selene Huang31ab4042020-04-29 04:22:39 -07003695
3696auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003697 // IKeyMintDevice.aidl
3698 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3699 "020100" // INTEGER length 1 value 0x00 (version)
3700 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3701 "aad93ed5924f283b4bb5526fbe7a1412"
3702 "f9d9749ec30db9062b29e574a8546f33"
3703 "c88732452f5b8e6a391ee76c39ed1712"
3704 "c61d8df6213dec1cffbc17a8c6d04c7b"
3705 "30893d8daa9b2015213e219468215532"
3706 "07f8f9931c4caba23ed3bee28b36947e"
3707 "47f10e0a5c3dc51c988a628daad3e5e1"
3708 "f4005e79c2d5a96c284b4b8d7e4948f3"
3709 "31e5b85dd5a236f85579f3ea1d1b8484"
3710 "87470bdb0ab4f81a12bee42c99fe0df4"
3711 "bee3759453e69ad1d68a809ce06b949f"
3712 "7694a990429b2fe81e066ff43e56a216"
3713 "02db70757922a4bcc23ab89f1e35da77"
3714 "586775f423e519c2ea394caf48a28d0c"
3715 "8020f1dcf6b3a68ec246f615ae96dae9"
3716 "a079b1f6eb959033c1af5c125fd94168"
3717 "040c" // OCTET STRING length 0x0c (initializationVector)
3718 "6d9721d08589581ab49204a3"
3719 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3720 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3721 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3722 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3723 "3106" // SET length 0x06
3724 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3725 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3726 // } end SET
3727 // } end [1]
3728 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3729 "020120" // INTEGER length 1 value 0x20 (AES)
3730 // } end [2]
3731 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3732 "02020100" // INTEGER length 2 value 0x100
3733 // } end [3]
3734 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3735 "3103" // SET length 0x03 {
3736 "020101" // INTEGER length 1 value 0x01 (ECB)
3737 // } end SET
3738 // } end [4]
3739 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3740 "3103" // SET length 0x03 {
3741 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3742 // } end SET
3743 // } end [5]
3744 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3745 // (noAuthRequired)
3746 "0500" // NULL
3747 // } end [503]
3748 // } end SEQUENCE (AuthorizationList)
3749 // } end SEQUENCE (KeyDescription)
3750 "0420" // OCTET STRING length 0x20 (encryptedKey)
3751 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3752 "c20d1f99a9a024a76f35c8e2cab9b68d"
3753 "0410" // OCTET STRING length 0x10 (tag)
3754 "2560c70109ae67c030f00b98b512a670"
3755 // } SEQUENCE (SecureKeyWrapper)
3756);
Selene Huang31ab4042020-04-29 04:22:39 -07003757
3758auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003759 // RFC 5208 s5
3760 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3761 "020100" // INTEGER length 1 value 0x00 (version)
3762 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3763 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3764 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3765 "0500" // NULL (parameters)
3766 // } SEQUENCE (AlgorithmIdentifier)
3767 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3768 // RFC 8017 A.1.2
3769 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3770 "020100" // INTEGER length 1 value 0x00 (version)
3771 "02820101" // INTEGER length 0x0101 (modulus) value...
3772 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3773 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3774 "7b06e673a837313d56b1c725150a3fef" // 0x30
3775 "86acbddc41bb759c2854eae32d35841e" // 0x40
3776 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3777 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3778 "312d7bd5921ffaea1347c157406fef71" // 0x70
3779 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3780 "f4645c11f5c1374c3886427411c44979" // 0x90
3781 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3782 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3783 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3784 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3785 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3786 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3787 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3788 "55" // 0x101
3789 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3790 "02820100" // INTEGER length 0x100 (privateExponent) value...
3791 "431447b6251908112b1ee76f99f3711a" // 0x10
3792 "52b6630960046c2de70de188d833f8b8" // 0x20
3793 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3794 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3795 "e710b630a03adc683b5d2c43080e52be" // 0x50
3796 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3797 "822bccff087d63c940ba8a45f670feb2" // 0x70
3798 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3799 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3800 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3801 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3802 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3803 "52659d5a5ba05b663737a8696281865b" // 0xd0
3804 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3805 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3806 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3807 "028181" // INTEGER length 0x81 (prime1) value...
3808 "00de392e18d682c829266cc3454e1d61" // 0x10
3809 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3810 "ff841be5bac82a164c5970007047b8c5" // 0x30
3811 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3812 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3813 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3814 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3815 "9e91346130748a6e3c124f9149d71c74" // 0x80
3816 "35"
3817 "028181" // INTEGER length 0x81 (prime2) value...
3818 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3819 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3820 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3821 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3822 "9ed39a2d934c880440aed8832f984316" // 0x50
3823 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3824 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3825 "b880677c068e1be936e81288815252a8" // 0x80
3826 "a1"
3827 "028180" // INTEGER length 0x80 (exponent1) value...
3828 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3829 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3830 "5a063212a4f105a3764743e53281988a" // 0x30
3831 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3832 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3833 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3834 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3835 "4719d6e2b9439823719cd08bcd031781" // 0x80
3836 "028181" // INTEGER length 0x81 (exponent2) value...
3837 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3838 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3839 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3840 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3841 "1254186af30b22c10582a8a43e34fe94" // 0x50
3842 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3843 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3844 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3845 "61"
3846 "028181" // INTEGER length 0x81 (coefficient) value...
3847 "00c931617c77829dfb1270502be9195c" // 0x10
3848 "8f2830885f57dba869536811e6864236" // 0x20
3849 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3850 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3851 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3852 "959356210723287b0affcc9f727044d4" // 0x60
3853 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3854 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3855 "22"
3856 // } SEQUENCE
3857 // } SEQUENCE ()
3858);
Selene Huang31ab4042020-04-29 04:22:39 -07003859
3860string zero_masking_key =
3861 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3862string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3863
3864class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3865
3866TEST_P(ImportWrappedKeyTest, Success) {
3867 auto wrapping_key_desc = AuthorizationSetBuilder()
3868 .RsaEncryptionKey(2048, 65537)
3869 .Digest(Digest::SHA_2_256)
3870 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003871 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3872 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003873
3874 ASSERT_EQ(ErrorCode::OK,
3875 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3876 AuthorizationSetBuilder()
3877 .Digest(Digest::SHA_2_256)
3878 .Padding(PaddingMode::RSA_OAEP)));
3879
3880 string message = "Hello World!";
3881 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3882 string ciphertext = EncryptMessage(message, params);
3883 string plaintext = DecryptMessage(ciphertext, params);
3884 EXPECT_EQ(message, plaintext);
3885}
3886
David Drysdaled2cc8c22021-04-15 13:29:45 +01003887/*
3888 * ImportWrappedKeyTest.SuccessSidsIgnored
3889 *
3890 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3891 * include Tag:USER_SECURE_ID.
3892 */
3893TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3894 auto wrapping_key_desc = AuthorizationSetBuilder()
3895 .RsaEncryptionKey(2048, 65537)
3896 .Digest(Digest::SHA_2_256)
3897 .Padding(PaddingMode::RSA_OAEP)
3898 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3899 .SetDefaultValidity();
3900
3901 int64_t password_sid = 42;
3902 int64_t biometric_sid = 24;
3903 ASSERT_EQ(ErrorCode::OK,
3904 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3905 AuthorizationSetBuilder()
3906 .Digest(Digest::SHA_2_256)
3907 .Padding(PaddingMode::RSA_OAEP),
3908 password_sid, biometric_sid));
3909
3910 string message = "Hello World!";
3911 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3912 string ciphertext = EncryptMessage(message, params);
3913 string plaintext = DecryptMessage(ciphertext, params);
3914 EXPECT_EQ(message, plaintext);
3915}
3916
Selene Huang31ab4042020-04-29 04:22:39 -07003917TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3918 auto wrapping_key_desc = AuthorizationSetBuilder()
3919 .RsaEncryptionKey(2048, 65537)
3920 .Digest(Digest::SHA_2_256)
3921 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003922 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3923 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003924
3925 ASSERT_EQ(ErrorCode::OK,
3926 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3927 AuthorizationSetBuilder()
3928 .Digest(Digest::SHA_2_256)
3929 .Padding(PaddingMode::RSA_OAEP)));
3930}
3931
3932TEST_P(ImportWrappedKeyTest, WrongMask) {
3933 auto wrapping_key_desc = AuthorizationSetBuilder()
3934 .RsaEncryptionKey(2048, 65537)
3935 .Digest(Digest::SHA_2_256)
3936 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003937 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3938 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003939
3940 ASSERT_EQ(
3941 ErrorCode::VERIFICATION_FAILED,
3942 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3943 AuthorizationSetBuilder()
3944 .Digest(Digest::SHA_2_256)
3945 .Padding(PaddingMode::RSA_OAEP)));
3946}
3947
3948TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3949 auto wrapping_key_desc = AuthorizationSetBuilder()
3950 .RsaEncryptionKey(2048, 65537)
3951 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003952 .Padding(PaddingMode::RSA_OAEP)
3953 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003954
3955 ASSERT_EQ(
3956 ErrorCode::INCOMPATIBLE_PURPOSE,
3957 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3958 AuthorizationSetBuilder()
3959 .Digest(Digest::SHA_2_256)
3960 .Padding(PaddingMode::RSA_OAEP)));
3961}
3962
David Drysdaled2cc8c22021-04-15 13:29:45 +01003963TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3964 auto wrapping_key_desc = AuthorizationSetBuilder()
3965 .RsaEncryptionKey(2048, 65537)
3966 .Digest(Digest::SHA_2_256)
3967 .Padding(PaddingMode::RSA_PSS)
3968 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3969 .SetDefaultValidity();
3970
3971 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3972 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3973 AuthorizationSetBuilder()
3974 .Digest(Digest::SHA_2_256)
3975 .Padding(PaddingMode::RSA_OAEP)));
3976}
3977
3978TEST_P(ImportWrappedKeyTest, WrongDigest) {
3979 auto wrapping_key_desc = AuthorizationSetBuilder()
3980 .RsaEncryptionKey(2048, 65537)
3981 .Digest(Digest::SHA_2_512)
3982 .Padding(PaddingMode::RSA_OAEP)
3983 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3984 .SetDefaultValidity();
3985
3986 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3987 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3988 AuthorizationSetBuilder()
3989 .Digest(Digest::SHA_2_256)
3990 .Padding(PaddingMode::RSA_OAEP)));
3991}
3992
Selene Huang31ab4042020-04-29 04:22:39 -07003993INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3994
3995typedef KeyMintAidlTestBase EncryptionOperationsTest;
3996
3997/*
3998 * EncryptionOperationsTest.RsaNoPaddingSuccess
3999 *
David Drysdale59cae642021-05-12 13:52:03 +01004000 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07004001 */
4002TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01004003 for (uint64_t exponent : {3, 65537}) {
4004 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4005 .Authorization(TAG_NO_AUTH_REQUIRED)
4006 .RsaEncryptionKey(2048, exponent)
4007 .Padding(PaddingMode::NONE)
4008 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004009
David Drysdaled2cc8c22021-04-15 13:29:45 +01004010 string message = string(2048 / 8, 'a');
4011 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004012 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004013 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004014
David Drysdale59cae642021-05-12 13:52:03 +01004015 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004016 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004017
David Drysdaled2cc8c22021-04-15 13:29:45 +01004018 // Unpadded RSA is deterministic
4019 EXPECT_EQ(ciphertext1, ciphertext2);
4020
4021 CheckedDeleteKey();
4022 }
Selene Huang31ab4042020-04-29 04:22:39 -07004023}
4024
4025/*
4026 * EncryptionOperationsTest.RsaNoPaddingShortMessage
4027 *
David Drysdale59cae642021-05-12 13:52:03 +01004028 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07004029 */
4030TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
4031 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4032 .Authorization(TAG_NO_AUTH_REQUIRED)
4033 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004034 .Padding(PaddingMode::NONE)
4035 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004036
4037 string message = "1";
4038 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4039
David Drysdale59cae642021-05-12 13:52:03 +01004040 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004041 EXPECT_EQ(2048U / 8, ciphertext.size());
4042
4043 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
4044 string plaintext = DecryptMessage(ciphertext, params);
4045
4046 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07004047}
4048
4049/*
Selene Huang31ab4042020-04-29 04:22:39 -07004050 * EncryptionOperationsTest.RsaOaepSuccess
4051 *
David Drysdale59cae642021-05-12 13:52:03 +01004052 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07004053 */
4054TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4055 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4056
4057 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01004058 ASSERT_EQ(ErrorCode::OK,
4059 GenerateKey(AuthorizationSetBuilder()
4060 .Authorization(TAG_NO_AUTH_REQUIRED)
4061 .RsaEncryptionKey(key_size, 65537)
4062 .Padding(PaddingMode::RSA_OAEP)
4063 .Digest(digests)
4064 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
4065 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004066
4067 string message = "Hello";
4068
4069 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01004070 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4071
4072 auto params = AuthorizationSetBuilder()
4073 .Digest(digest)
4074 .Padding(PaddingMode::RSA_OAEP)
4075 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
4076 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004077 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4078 EXPECT_EQ(key_size / 8, ciphertext1.size());
4079
David Drysdale59cae642021-05-12 13:52:03 +01004080 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004081 EXPECT_EQ(key_size / 8, ciphertext2.size());
4082
4083 // OAEP randomizes padding so every result should be different (with astronomically high
4084 // probability).
4085 EXPECT_NE(ciphertext1, ciphertext2);
4086
4087 string plaintext1 = DecryptMessage(ciphertext1, params);
4088 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4089 string plaintext2 = DecryptMessage(ciphertext2, params);
4090 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4091
4092 // Decrypting corrupted ciphertext should fail.
4093 size_t offset_to_corrupt = random() % ciphertext1.size();
4094 char corrupt_byte;
4095 do {
4096 corrupt_byte = static_cast<char>(random() % 256);
4097 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4098 ciphertext1[offset_to_corrupt] = corrupt_byte;
4099
4100 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4101 string result;
4102 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4103 EXPECT_EQ(0U, result.size());
4104 }
4105}
4106
4107/*
4108 * EncryptionOperationsTest.RsaOaepInvalidDigest
4109 *
David Drysdale59cae642021-05-12 13:52:03 +01004110 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07004111 * without a digest.
4112 */
4113TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
4114 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4115 .Authorization(TAG_NO_AUTH_REQUIRED)
4116 .RsaEncryptionKey(2048, 65537)
4117 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004118 .Digest(Digest::NONE)
4119 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004120
4121 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004122 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07004123}
4124
4125/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004126 * EncryptionOperationsTest.RsaOaepInvalidPadding
4127 *
David Drysdale59cae642021-05-12 13:52:03 +01004128 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01004129 * with a padding value that is only suitable for signing/verifying.
4130 */
4131TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
4132 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4133 .Authorization(TAG_NO_AUTH_REQUIRED)
4134 .RsaEncryptionKey(2048, 65537)
4135 .Padding(PaddingMode::RSA_PSS)
4136 .Digest(Digest::NONE)
4137 .SetDefaultValidity()));
4138
4139 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004140 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01004141}
4142
4143/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004144 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07004145 *
David Drysdale59cae642021-05-12 13:52:03 +01004146 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004147 * with a different digest than was used to encrypt.
4148 */
4149TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01004150 if (SecLevel() == SecurityLevel::STRONGBOX) {
4151 GTEST_SKIP() << "Test not applicable to StrongBox device";
4152 }
Selene Huang31ab4042020-04-29 04:22:39 -07004153
4154 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4155 .Authorization(TAG_NO_AUTH_REQUIRED)
4156 .RsaEncryptionKey(1024, 65537)
4157 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004158 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
4159 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004160 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01004161 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07004162 message,
4163 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
4164
4165 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4166 .Digest(Digest::SHA_2_256)
4167 .Padding(PaddingMode::RSA_OAEP)));
4168 string result;
4169 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
4170 EXPECT_EQ(0U, result.size());
4171}
4172
4173/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004174 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
4175 *
David Drysdale59cae642021-05-12 13:52:03 +01004176 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004177 * digests.
4178 */
4179TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
4180 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4181
4182 size_t key_size = 2048; // Need largish key for SHA-512 test.
4183 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4184 .OaepMGFDigest(digests)
4185 .Authorization(TAG_NO_AUTH_REQUIRED)
4186 .RsaEncryptionKey(key_size, 65537)
4187 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004188 .Digest(Digest::SHA_2_256)
4189 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004190
4191 string message = "Hello";
4192
4193 for (auto digest : digests) {
4194 auto params = AuthorizationSetBuilder()
4195 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4196 .Digest(Digest::SHA_2_256)
4197 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01004198 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004199 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4200 EXPECT_EQ(key_size / 8, ciphertext1.size());
4201
David Drysdale59cae642021-05-12 13:52:03 +01004202 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004203 EXPECT_EQ(key_size / 8, ciphertext2.size());
4204
4205 // OAEP randomizes padding so every result should be different (with astronomically high
4206 // probability).
4207 EXPECT_NE(ciphertext1, ciphertext2);
4208
4209 string plaintext1 = DecryptMessage(ciphertext1, params);
4210 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4211 string plaintext2 = DecryptMessage(ciphertext2, params);
4212 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4213
4214 // Decrypting corrupted ciphertext should fail.
4215 size_t offset_to_corrupt = random() % ciphertext1.size();
4216 char corrupt_byte;
4217 do {
4218 corrupt_byte = static_cast<char>(random() % 256);
4219 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4220 ciphertext1[offset_to_corrupt] = corrupt_byte;
4221
4222 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4223 string result;
4224 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4225 EXPECT_EQ(0U, result.size());
4226 }
4227}
4228
4229/*
4230 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4231 *
David Drysdale59cae642021-05-12 13:52:03 +01004232 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004233 * with incompatible MGF digest.
4234 */
4235TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4236 ASSERT_EQ(ErrorCode::OK,
4237 GenerateKey(AuthorizationSetBuilder()
4238 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4239 .Authorization(TAG_NO_AUTH_REQUIRED)
4240 .RsaEncryptionKey(2048, 65537)
4241 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004242 .Digest(Digest::SHA_2_256)
4243 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004244 string message = "Hello World!";
4245
4246 auto params = AuthorizationSetBuilder()
4247 .Padding(PaddingMode::RSA_OAEP)
4248 .Digest(Digest::SHA_2_256)
4249 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004250 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004251}
4252
4253/*
4254 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4255 *
4256 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4257 * with unsupported MGF digest.
4258 */
4259TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4260 ASSERT_EQ(ErrorCode::OK,
4261 GenerateKey(AuthorizationSetBuilder()
4262 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4263 .Authorization(TAG_NO_AUTH_REQUIRED)
4264 .RsaEncryptionKey(2048, 65537)
4265 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004266 .Digest(Digest::SHA_2_256)
4267 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004268 string message = "Hello World!";
4269
4270 auto params = AuthorizationSetBuilder()
4271 .Padding(PaddingMode::RSA_OAEP)
4272 .Digest(Digest::SHA_2_256)
4273 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004274 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004275}
4276
4277/*
Selene Huang31ab4042020-04-29 04:22:39 -07004278 * EncryptionOperationsTest.RsaPkcs1Success
4279 *
4280 * Verifies that RSA PKCS encryption/decrypts works.
4281 */
4282TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4283 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4284 .Authorization(TAG_NO_AUTH_REQUIRED)
4285 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004286 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4287 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004288
4289 string message = "Hello World!";
4290 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004291 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004292 EXPECT_EQ(2048U / 8, ciphertext1.size());
4293
David Drysdale59cae642021-05-12 13:52:03 +01004294 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004295 EXPECT_EQ(2048U / 8, ciphertext2.size());
4296
4297 // PKCS1 v1.5 randomizes padding so every result should be different.
4298 EXPECT_NE(ciphertext1, ciphertext2);
4299
4300 string plaintext = DecryptMessage(ciphertext1, params);
4301 EXPECT_EQ(message, plaintext);
4302
4303 // Decrypting corrupted ciphertext should fail.
4304 size_t offset_to_corrupt = random() % ciphertext1.size();
4305 char corrupt_byte;
4306 do {
4307 corrupt_byte = static_cast<char>(random() % 256);
4308 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4309 ciphertext1[offset_to_corrupt] = corrupt_byte;
4310
4311 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4312 string result;
4313 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4314 EXPECT_EQ(0U, result.size());
4315}
4316
4317/*
Selene Huang31ab4042020-04-29 04:22:39 -07004318 * EncryptionOperationsTest.EcdsaEncrypt
4319 *
4320 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4321 */
4322TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4323 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4324 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004325 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004326 .Digest(Digest::NONE)
4327 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004328 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4329 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4330 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4331}
4332
4333/*
4334 * EncryptionOperationsTest.HmacEncrypt
4335 *
4336 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4337 */
4338TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4339 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4340 .Authorization(TAG_NO_AUTH_REQUIRED)
4341 .HmacKey(128)
4342 .Digest(Digest::SHA_2_256)
4343 .Padding(PaddingMode::NONE)
4344 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4345 auto params = AuthorizationSetBuilder()
4346 .Digest(Digest::SHA_2_256)
4347 .Padding(PaddingMode::NONE)
4348 .Authorization(TAG_MAC_LENGTH, 128);
4349 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4350 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4351}
4352
4353/*
4354 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4355 *
4356 * Verifies that AES ECB mode works.
4357 */
4358TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4359 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4360 .Authorization(TAG_NO_AUTH_REQUIRED)
4361 .AesEncryptionKey(128)
4362 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4363 .Padding(PaddingMode::NONE)));
4364
4365 ASSERT_GT(key_blob_.size(), 0U);
4366 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4367
4368 // Two-block message.
4369 string message = "12345678901234567890123456789012";
4370 string ciphertext1 = EncryptMessage(message, params);
4371 EXPECT_EQ(message.size(), ciphertext1.size());
4372
4373 string ciphertext2 = EncryptMessage(string(message), params);
4374 EXPECT_EQ(message.size(), ciphertext2.size());
4375
4376 // ECB is deterministic.
4377 EXPECT_EQ(ciphertext1, ciphertext2);
4378
4379 string plaintext = DecryptMessage(ciphertext1, params);
4380 EXPECT_EQ(message, plaintext);
4381}
4382
4383/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004384 * EncryptionOperationsTest.AesEcbUnknownTag
4385 *
4386 * Verifies that AES ECB operations ignore unknown tags.
4387 */
4388TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4389 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4390 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4391 KeyParameter unknown_param;
4392 unknown_param.tag = unknown_tag;
4393
4394 vector<KeyCharacteristics> key_characteristics;
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 .Authorization(unknown_param),
4401 &key_blob_, &key_characteristics));
4402 ASSERT_GT(key_blob_.size(), 0U);
4403
4404 // Unknown tags should not be returned in key characteristics.
4405 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4406 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4407 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4408 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4409
4410 // Encrypt without mentioning the unknown parameter.
4411 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4412 string message = "12345678901234567890123456789012";
4413 string ciphertext = EncryptMessage(message, params);
4414 EXPECT_EQ(message.size(), ciphertext.size());
4415
4416 // Decrypt including the unknown parameter.
4417 auto decrypt_params = AuthorizationSetBuilder()
4418 .BlockMode(BlockMode::ECB)
4419 .Padding(PaddingMode::NONE)
4420 .Authorization(unknown_param);
4421 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4422 EXPECT_EQ(message, plaintext);
4423}
4424
4425/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004426 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004427 *
4428 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4429 */
4430TEST_P(EncryptionOperationsTest, AesWrongMode) {
4431 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4432 .Authorization(TAG_NO_AUTH_REQUIRED)
4433 .AesEncryptionKey(128)
4434 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4435 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004436 ASSERT_GT(key_blob_.size(), 0U);
4437
Selene Huang31ab4042020-04-29 04:22:39 -07004438 EXPECT_EQ(
4439 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4440 Begin(KeyPurpose::ENCRYPT,
4441 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4442}
4443
4444/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004445 * EncryptionOperationsTest.AesWrongPadding
4446 *
4447 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4448 */
4449TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4450 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4451 .Authorization(TAG_NO_AUTH_REQUIRED)
4452 .AesEncryptionKey(128)
4453 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4454 .Padding(PaddingMode::NONE)));
4455 ASSERT_GT(key_blob_.size(), 0U);
4456
4457 EXPECT_EQ(
4458 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4459 Begin(KeyPurpose::ENCRYPT,
4460 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4461}
4462
4463/*
4464 * EncryptionOperationsTest.AesInvalidParams
4465 *
4466 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4467 */
4468TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4469 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4470 .Authorization(TAG_NO_AUTH_REQUIRED)
4471 .AesEncryptionKey(128)
4472 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4473 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4474 .Padding(PaddingMode::NONE)
4475 .Padding(PaddingMode::PKCS7)));
4476 ASSERT_GT(key_blob_.size(), 0U);
4477
4478 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4479 .BlockMode(BlockMode::CBC)
4480 .BlockMode(BlockMode::ECB)
4481 .Padding(PaddingMode::NONE));
4482 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4483 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4484
4485 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4486 .BlockMode(BlockMode::ECB)
4487 .Padding(PaddingMode::NONE)
4488 .Padding(PaddingMode::PKCS7));
4489 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4490 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4491}
4492
4493/*
Selene Huang31ab4042020-04-29 04:22:39 -07004494 * EncryptionOperationsTest.AesWrongPurpose
4495 *
4496 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4497 * specified.
4498 */
4499TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4500 auto err = GenerateKey(AuthorizationSetBuilder()
4501 .Authorization(TAG_NO_AUTH_REQUIRED)
4502 .AesKey(128)
4503 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4504 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4505 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4506 .Padding(PaddingMode::NONE));
4507 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4508 ASSERT_GT(key_blob_.size(), 0U);
4509
4510 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4511 .BlockMode(BlockMode::GCM)
4512 .Padding(PaddingMode::NONE)
4513 .Authorization(TAG_MAC_LENGTH, 128));
4514 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4515
4516 CheckedDeleteKey();
4517
4518 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4519 .Authorization(TAG_NO_AUTH_REQUIRED)
4520 .AesKey(128)
4521 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4522 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4523 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4524 .Padding(PaddingMode::NONE)));
4525
4526 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4527 .BlockMode(BlockMode::GCM)
4528 .Padding(PaddingMode::NONE)
4529 .Authorization(TAG_MAC_LENGTH, 128));
4530 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4531}
4532
4533/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004534 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004535 *
4536 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4537 * multiple of the block size and no padding is specified.
4538 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004539TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4540 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4541 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4542 .Authorization(TAG_NO_AUTH_REQUIRED)
4543 .AesEncryptionKey(128)
4544 .Authorization(TAG_BLOCK_MODE, blockMode)
4545 .Padding(PaddingMode::NONE)));
4546 // Message is slightly shorter than two blocks.
4547 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004548
David Drysdaled2cc8c22021-04-15 13:29:45 +01004549 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4550 AuthorizationSet out_params;
4551 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4552 string ciphertext;
4553 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4554 EXPECT_EQ(0U, ciphertext.size());
4555
4556 CheckedDeleteKey();
4557 }
Selene Huang31ab4042020-04-29 04:22:39 -07004558}
4559
4560/*
4561 * EncryptionOperationsTest.AesEcbPkcs7Padding
4562 *
4563 * Verifies that AES PKCS7 padding works for any message length.
4564 */
4565TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4566 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4567 .Authorization(TAG_NO_AUTH_REQUIRED)
4568 .AesEncryptionKey(128)
4569 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4570 .Padding(PaddingMode::PKCS7)));
4571
4572 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4573
4574 // Try various message lengths; all should work.
4575 for (size_t i = 0; i < 32; ++i) {
4576 string message(i, 'a');
4577 string ciphertext = EncryptMessage(message, params);
4578 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4579 string plaintext = DecryptMessage(ciphertext, params);
4580 EXPECT_EQ(message, plaintext);
4581 }
4582}
4583
4584/*
4585 * EncryptionOperationsTest.AesEcbWrongPadding
4586 *
4587 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4588 * specified.
4589 */
4590TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4591 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4592 .Authorization(TAG_NO_AUTH_REQUIRED)
4593 .AesEncryptionKey(128)
4594 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4595 .Padding(PaddingMode::NONE)));
4596
4597 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4598
4599 // Try various message lengths; all should fail
4600 for (size_t i = 0; i < 32; ++i) {
4601 string message(i, 'a');
4602 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4603 }
4604}
4605
4606/*
4607 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4608 *
4609 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4610 */
4611TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4612 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4613 .Authorization(TAG_NO_AUTH_REQUIRED)
4614 .AesEncryptionKey(128)
4615 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4616 .Padding(PaddingMode::PKCS7)));
4617
4618 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4619
4620 string message = "a";
4621 string ciphertext = EncryptMessage(message, params);
4622 EXPECT_EQ(16U, ciphertext.size());
4623 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07004624
Seth Moore7a55ae32021-06-23 14:28:11 -07004625 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
4626 ++ciphertext[ciphertext.size() / 2];
4627
4628 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4629 string plaintext;
4630 ErrorCode error = Finish(message, &plaintext);
4631 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
4632 // This is the expected error, we can exit the test now.
4633 return;
4634 } else {
4635 // Very small chance we got valid decryption, so try again.
4636 ASSERT_EQ(error, ErrorCode::OK);
4637 }
4638 }
4639 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07004640}
4641
4642vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4643 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004644 EXPECT_TRUE(iv);
4645 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004646}
4647
4648/*
4649 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4650 *
4651 * Verifies that AES CTR mode works.
4652 */
4653TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4654 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4655 .Authorization(TAG_NO_AUTH_REQUIRED)
4656 .AesEncryptionKey(128)
4657 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4658 .Padding(PaddingMode::NONE)));
4659
4660 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4661
4662 string message = "123";
4663 AuthorizationSet out_params;
4664 string ciphertext1 = EncryptMessage(message, params, &out_params);
4665 vector<uint8_t> iv1 = CopyIv(out_params);
4666 EXPECT_EQ(16U, iv1.size());
4667
4668 EXPECT_EQ(message.size(), ciphertext1.size());
4669
4670 out_params.Clear();
4671 string ciphertext2 = EncryptMessage(message, params, &out_params);
4672 vector<uint8_t> iv2 = CopyIv(out_params);
4673 EXPECT_EQ(16U, iv2.size());
4674
4675 // IVs should be random, so ciphertexts should differ.
4676 EXPECT_NE(ciphertext1, ciphertext2);
4677
4678 auto params_iv1 =
4679 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4680 auto params_iv2 =
4681 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4682
4683 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4684 EXPECT_EQ(message, plaintext);
4685 plaintext = DecryptMessage(ciphertext2, params_iv2);
4686 EXPECT_EQ(message, plaintext);
4687
4688 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4689 plaintext = DecryptMessage(ciphertext1, params_iv2);
4690 EXPECT_NE(message, plaintext);
4691 plaintext = DecryptMessage(ciphertext2, params_iv1);
4692 EXPECT_NE(message, plaintext);
4693}
4694
4695/*
4696 * EncryptionOperationsTest.AesIncremental
4697 *
4698 * Verifies that AES works, all modes, when provided data in various size increments.
4699 */
4700TEST_P(EncryptionOperationsTest, AesIncremental) {
4701 auto block_modes = {
4702 BlockMode::ECB,
4703 BlockMode::CBC,
4704 BlockMode::CTR,
4705 BlockMode::GCM,
4706 };
4707
4708 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4709 .Authorization(TAG_NO_AUTH_REQUIRED)
4710 .AesEncryptionKey(128)
4711 .BlockMode(block_modes)
4712 .Padding(PaddingMode::NONE)
4713 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4714
4715 for (int increment = 1; increment <= 240; ++increment) {
4716 for (auto block_mode : block_modes) {
4717 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004718 auto params =
4719 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4720 if (block_mode == BlockMode::GCM) {
4721 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4722 }
Selene Huang31ab4042020-04-29 04:22:39 -07004723
4724 AuthorizationSet output_params;
4725 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4726
4727 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004728 string to_send;
4729 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004730 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004731 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004732 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4733 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004734
4735 switch (block_mode) {
4736 case BlockMode::GCM:
4737 EXPECT_EQ(message.size() + 16, ciphertext.size());
4738 break;
4739 case BlockMode::CTR:
4740 EXPECT_EQ(message.size(), ciphertext.size());
4741 break;
4742 case BlockMode::CBC:
4743 case BlockMode::ECB:
4744 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4745 break;
4746 }
4747
4748 auto iv = output_params.GetTagValue(TAG_NONCE);
4749 switch (block_mode) {
4750 case BlockMode::CBC:
4751 case BlockMode::GCM:
4752 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004753 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4754 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4755 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004756 break;
4757
4758 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004759 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004760 break;
4761 }
4762
4763 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4764 << "Decrypt begin() failed for block mode " << block_mode;
4765
4766 string plaintext;
4767 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004768 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004769 }
4770 ErrorCode error = Finish(to_send, &plaintext);
4771 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4772 << " and increment " << increment;
4773 if (error == ErrorCode::OK) {
4774 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4775 << block_mode << " and increment " << increment;
4776 }
4777 }
4778 }
4779}
4780
4781struct AesCtrSp80038aTestVector {
4782 const char* key;
4783 const char* nonce;
4784 const char* plaintext;
4785 const char* ciphertext;
4786};
4787
4788// These test vectors are taken from
4789// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4790static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4791 // AES-128
4792 {
4793 "2b7e151628aed2a6abf7158809cf4f3c",
4794 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4795 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4796 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4797 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4798 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4799 },
4800 // AES-192
4801 {
4802 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4803 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4804 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4805 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4806 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4807 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4808 },
4809 // AES-256
4810 {
4811 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4812 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4813 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4814 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4815 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4816 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4817 },
4818};
4819
4820/*
4821 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4822 *
4823 * Verifies AES CTR implementation against SP800-38A test vectors.
4824 */
4825TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4826 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4827 for (size_t i = 0; i < 3; i++) {
4828 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4829 const string key = hex2str(test.key);
4830 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4831 InvalidSizes.end())
4832 continue;
4833 const string nonce = hex2str(test.nonce);
4834 const string plaintext = hex2str(test.plaintext);
4835 const string ciphertext = hex2str(test.ciphertext);
4836 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4837 }
4838}
4839
4840/*
4841 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4842 *
4843 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4844 */
4845TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4846 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4847 .Authorization(TAG_NO_AUTH_REQUIRED)
4848 .AesEncryptionKey(128)
4849 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4850 .Padding(PaddingMode::PKCS7)));
4851 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4852 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4853}
4854
4855/*
4856 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4857 *
4858 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4859 */
4860TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4861 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4862 .Authorization(TAG_NO_AUTH_REQUIRED)
4863 .AesEncryptionKey(128)
4864 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4865 .Authorization(TAG_CALLER_NONCE)
4866 .Padding(PaddingMode::NONE)));
4867
4868 auto params = AuthorizationSetBuilder()
4869 .BlockMode(BlockMode::CTR)
4870 .Padding(PaddingMode::NONE)
4871 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4872 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4873
4874 params = AuthorizationSetBuilder()
4875 .BlockMode(BlockMode::CTR)
4876 .Padding(PaddingMode::NONE)
4877 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4878 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4879
4880 params = AuthorizationSetBuilder()
4881 .BlockMode(BlockMode::CTR)
4882 .Padding(PaddingMode::NONE)
4883 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4884 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4885}
4886
4887/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004888 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004889 *
4890 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4891 */
4892TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4893 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4894 .Authorization(TAG_NO_AUTH_REQUIRED)
4895 .AesEncryptionKey(128)
4896 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4897 .Padding(PaddingMode::NONE)));
4898 // Two-block message.
4899 string message = "12345678901234567890123456789012";
4900 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4901 AuthorizationSet out_params;
4902 string ciphertext1 = EncryptMessage(message, params, &out_params);
4903 vector<uint8_t> iv1 = CopyIv(out_params);
4904 EXPECT_EQ(message.size(), ciphertext1.size());
4905
4906 out_params.Clear();
4907
4908 string ciphertext2 = EncryptMessage(message, params, &out_params);
4909 vector<uint8_t> iv2 = CopyIv(out_params);
4910 EXPECT_EQ(message.size(), ciphertext2.size());
4911
4912 // IVs should be random, so ciphertexts should differ.
4913 EXPECT_NE(ciphertext1, ciphertext2);
4914
4915 params.push_back(TAG_NONCE, iv1);
4916 string plaintext = DecryptMessage(ciphertext1, params);
4917 EXPECT_EQ(message, plaintext);
4918}
4919
4920/*
4921 * EncryptionOperationsTest.AesCallerNonce
4922 *
4923 * Verifies that AES caller-provided nonces work correctly.
4924 */
4925TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4926 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4927 .Authorization(TAG_NO_AUTH_REQUIRED)
4928 .AesEncryptionKey(128)
4929 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4930 .Authorization(TAG_CALLER_NONCE)
4931 .Padding(PaddingMode::NONE)));
4932
4933 string message = "12345678901234567890123456789012";
4934
4935 // Don't specify nonce, should get a random one.
4936 AuthorizationSetBuilder params =
4937 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4938 AuthorizationSet out_params;
4939 string ciphertext = EncryptMessage(message, params, &out_params);
4940 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004941 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004942
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004943 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004944 string plaintext = DecryptMessage(ciphertext, params);
4945 EXPECT_EQ(message, plaintext);
4946
4947 // Now specify a nonce, should also work.
4948 params = AuthorizationSetBuilder()
4949 .BlockMode(BlockMode::CBC)
4950 .Padding(PaddingMode::NONE)
4951 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4952 out_params.Clear();
4953 ciphertext = EncryptMessage(message, params, &out_params);
4954
4955 // Decrypt with correct nonce.
4956 plaintext = DecryptMessage(ciphertext, params);
4957 EXPECT_EQ(message, plaintext);
4958
4959 // Try with wrong nonce.
4960 params = AuthorizationSetBuilder()
4961 .BlockMode(BlockMode::CBC)
4962 .Padding(PaddingMode::NONE)
4963 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4964 plaintext = DecryptMessage(ciphertext, params);
4965 EXPECT_NE(message, plaintext);
4966}
4967
4968/*
4969 * EncryptionOperationsTest.AesCallerNonceProhibited
4970 *
4971 * Verifies that caller-provided nonces are not permitted when not specified in the key
4972 * authorizations.
4973 */
4974TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4975 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4976 .Authorization(TAG_NO_AUTH_REQUIRED)
4977 .AesEncryptionKey(128)
4978 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4979 .Padding(PaddingMode::NONE)));
4980
4981 string message = "12345678901234567890123456789012";
4982
4983 // Don't specify nonce, should get a random one.
4984 AuthorizationSetBuilder params =
4985 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4986 AuthorizationSet out_params;
4987 string ciphertext = EncryptMessage(message, params, &out_params);
4988 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004989 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004990
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004991 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004992 string plaintext = DecryptMessage(ciphertext, params);
4993 EXPECT_EQ(message, plaintext);
4994
4995 // Now specify a nonce, should fail
4996 params = AuthorizationSetBuilder()
4997 .BlockMode(BlockMode::CBC)
4998 .Padding(PaddingMode::NONE)
4999 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5000 out_params.Clear();
5001 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5002}
5003
5004/*
5005 * EncryptionOperationsTest.AesGcmRoundTripSuccess
5006 *
5007 * Verifies that AES GCM mode works.
5008 */
5009TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
5010 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5011 .Authorization(TAG_NO_AUTH_REQUIRED)
5012 .AesEncryptionKey(128)
5013 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5014 .Padding(PaddingMode::NONE)
5015 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5016
5017 string aad = "foobar";
5018 string message = "123456789012345678901234567890123456";
5019
5020 auto begin_params = AuthorizationSetBuilder()
5021 .BlockMode(BlockMode::GCM)
5022 .Padding(PaddingMode::NONE)
5023 .Authorization(TAG_MAC_LENGTH, 128);
5024
Selene Huang31ab4042020-04-29 04:22:39 -07005025 // Encrypt
5026 AuthorizationSet begin_out_params;
5027 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5028 << "Begin encrypt";
5029 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005030 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5031 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005032 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5033
5034 // Grab nonce
5035 begin_params.push_back(begin_out_params);
5036
5037 // Decrypt.
5038 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07005039 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005040 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005041 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005042 EXPECT_EQ(message.length(), plaintext.length());
5043 EXPECT_EQ(message, plaintext);
5044}
5045
5046/*
5047 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
5048 *
5049 * Verifies that AES GCM mode works, even when there's a long delay
5050 * between operations.
5051 */
5052TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
5053 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5054 .Authorization(TAG_NO_AUTH_REQUIRED)
5055 .AesEncryptionKey(128)
5056 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5057 .Padding(PaddingMode::NONE)
5058 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5059
5060 string aad = "foobar";
5061 string message = "123456789012345678901234567890123456";
5062
5063 auto begin_params = AuthorizationSetBuilder()
5064 .BlockMode(BlockMode::GCM)
5065 .Padding(PaddingMode::NONE)
5066 .Authorization(TAG_MAC_LENGTH, 128);
5067
Selene Huang31ab4042020-04-29 04:22:39 -07005068 // Encrypt
5069 AuthorizationSet begin_out_params;
5070 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5071 << "Begin encrypt";
5072 string ciphertext;
5073 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005074 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005075 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005076 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005077
5078 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5079
5080 // Grab nonce
5081 begin_params.push_back(begin_out_params);
5082
5083 // Decrypt.
5084 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5085 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005086 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005087 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005088 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005089 sleep(5);
5090 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5091 EXPECT_EQ(message.length(), plaintext.length());
5092 EXPECT_EQ(message, plaintext);
5093}
5094
5095/*
5096 * EncryptionOperationsTest.AesGcmDifferentNonces
5097 *
5098 * Verifies that encrypting the same data with different nonces produces different outputs.
5099 */
5100TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
5101 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5102 .Authorization(TAG_NO_AUTH_REQUIRED)
5103 .AesEncryptionKey(128)
5104 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5105 .Padding(PaddingMode::NONE)
5106 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5107 .Authorization(TAG_CALLER_NONCE)));
5108
5109 string aad = "foobar";
5110 string message = "123456789012345678901234567890123456";
5111 string nonce1 = "000000000000";
5112 string nonce2 = "111111111111";
5113 string nonce3 = "222222222222";
5114
5115 string ciphertext1 =
5116 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
5117 string ciphertext2 =
5118 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
5119 string ciphertext3 =
5120 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
5121
5122 ASSERT_NE(ciphertext1, ciphertext2);
5123 ASSERT_NE(ciphertext1, ciphertext3);
5124 ASSERT_NE(ciphertext2, ciphertext3);
5125}
5126
5127/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005128 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
5129 *
5130 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
5131 */
5132TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
5133 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5134 .Authorization(TAG_NO_AUTH_REQUIRED)
5135 .AesEncryptionKey(128)
5136 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5137 .Padding(PaddingMode::NONE)
5138 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5139
5140 string aad = "foobar";
5141 string message = "123456789012345678901234567890123456";
5142
5143 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5144 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5145 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5146
5147 ASSERT_NE(ciphertext1, ciphertext2);
5148 ASSERT_NE(ciphertext1, ciphertext3);
5149 ASSERT_NE(ciphertext2, ciphertext3);
5150}
5151
5152/*
Selene Huang31ab4042020-04-29 04:22:39 -07005153 * EncryptionOperationsTest.AesGcmTooShortTag
5154 *
5155 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
5156 */
5157TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
5158 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5159 .Authorization(TAG_NO_AUTH_REQUIRED)
5160 .AesEncryptionKey(128)
5161 .BlockMode(BlockMode::GCM)
5162 .Padding(PaddingMode::NONE)
5163 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5164 string message = "123456789012345678901234567890123456";
5165 auto params = AuthorizationSetBuilder()
5166 .BlockMode(BlockMode::GCM)
5167 .Padding(PaddingMode::NONE)
5168 .Authorization(TAG_MAC_LENGTH, 96);
5169
5170 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
5171}
5172
5173/*
5174 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
5175 *
5176 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
5177 */
5178TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
5179 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5180 .Authorization(TAG_NO_AUTH_REQUIRED)
5181 .AesEncryptionKey(128)
5182 .BlockMode(BlockMode::GCM)
5183 .Padding(PaddingMode::NONE)
5184 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5185 string aad = "foobar";
5186 string message = "123456789012345678901234567890123456";
5187 auto params = AuthorizationSetBuilder()
5188 .BlockMode(BlockMode::GCM)
5189 .Padding(PaddingMode::NONE)
5190 .Authorization(TAG_MAC_LENGTH, 128);
5191
Selene Huang31ab4042020-04-29 04:22:39 -07005192 // Encrypt
5193 AuthorizationSet begin_out_params;
5194 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5195 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005196 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005197
5198 AuthorizationSet finish_out_params;
5199 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005200 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5201 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005202
5203 params = AuthorizationSetBuilder()
5204 .Authorizations(begin_out_params)
5205 .BlockMode(BlockMode::GCM)
5206 .Padding(PaddingMode::NONE)
5207 .Authorization(TAG_MAC_LENGTH, 96);
5208
5209 // Decrypt.
5210 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5211}
5212
5213/*
5214 * EncryptionOperationsTest.AesGcmCorruptKey
5215 *
5216 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5217 */
5218TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5219 const uint8_t nonce_bytes[] = {
5220 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5221 };
5222 string nonce = make_string(nonce_bytes);
5223 const uint8_t ciphertext_bytes[] = {
5224 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5225 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5226 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5227 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5228 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5229 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5230 };
5231 string ciphertext = make_string(ciphertext_bytes);
5232
5233 auto params = AuthorizationSetBuilder()
5234 .BlockMode(BlockMode::GCM)
5235 .Padding(PaddingMode::NONE)
5236 .Authorization(TAG_MAC_LENGTH, 128)
5237 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5238
5239 auto import_params = AuthorizationSetBuilder()
5240 .Authorization(TAG_NO_AUTH_REQUIRED)
5241 .AesEncryptionKey(128)
5242 .BlockMode(BlockMode::GCM)
5243 .Padding(PaddingMode::NONE)
5244 .Authorization(TAG_CALLER_NONCE)
5245 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5246
5247 // Import correct key and decrypt
5248 const uint8_t key_bytes[] = {
5249 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5250 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5251 };
5252 string key = make_string(key_bytes);
5253 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5254 string plaintext = DecryptMessage(ciphertext, params);
5255 CheckedDeleteKey();
5256
5257 // Corrupt key and attempt to decrypt
5258 key[0] = 0;
5259 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5260 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5261 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5262 CheckedDeleteKey();
5263}
5264
5265/*
5266 * EncryptionOperationsTest.AesGcmAadNoData
5267 *
5268 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5269 * encrypt.
5270 */
5271TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5272 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5273 .Authorization(TAG_NO_AUTH_REQUIRED)
5274 .AesEncryptionKey(128)
5275 .BlockMode(BlockMode::GCM)
5276 .Padding(PaddingMode::NONE)
5277 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5278
5279 string aad = "1234567890123456";
5280 auto params = AuthorizationSetBuilder()
5281 .BlockMode(BlockMode::GCM)
5282 .Padding(PaddingMode::NONE)
5283 .Authorization(TAG_MAC_LENGTH, 128);
5284
Selene Huang31ab4042020-04-29 04:22:39 -07005285 // Encrypt
5286 AuthorizationSet begin_out_params;
5287 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5288 string ciphertext;
5289 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005290 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5291 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005292 EXPECT_TRUE(finish_out_params.empty());
5293
5294 // Grab nonce
5295 params.push_back(begin_out_params);
5296
5297 // Decrypt.
5298 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005299 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005300 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005301 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005302
5303 EXPECT_TRUE(finish_out_params.empty());
5304
5305 EXPECT_EQ("", plaintext);
5306}
5307
5308/*
5309 * EncryptionOperationsTest.AesGcmMultiPartAad
5310 *
5311 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5312 * chunks.
5313 */
5314TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5315 const size_t tag_bits = 128;
5316 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5317 .Authorization(TAG_NO_AUTH_REQUIRED)
5318 .AesEncryptionKey(128)
5319 .BlockMode(BlockMode::GCM)
5320 .Padding(PaddingMode::NONE)
5321 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5322
5323 string message = "123456789012345678901234567890123456";
5324 auto begin_params = AuthorizationSetBuilder()
5325 .BlockMode(BlockMode::GCM)
5326 .Padding(PaddingMode::NONE)
5327 .Authorization(TAG_MAC_LENGTH, tag_bits);
5328 AuthorizationSet begin_out_params;
5329
Selene Huang31ab4042020-04-29 04:22:39 -07005330 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5331
5332 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005333 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5334 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005335 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005336 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5337 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005338
Selene Huang31ab4042020-04-29 04:22:39 -07005339 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005340 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005341
5342 // Grab nonce.
5343 begin_params.push_back(begin_out_params);
5344
5345 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005346 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005347 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005348 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005349 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005350 EXPECT_EQ(message, plaintext);
5351}
5352
5353/*
5354 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5355 *
5356 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5357 */
5358TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5359 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5360 .Authorization(TAG_NO_AUTH_REQUIRED)
5361 .AesEncryptionKey(128)
5362 .BlockMode(BlockMode::GCM)
5363 .Padding(PaddingMode::NONE)
5364 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5365
5366 string message = "123456789012345678901234567890123456";
5367 auto begin_params = AuthorizationSetBuilder()
5368 .BlockMode(BlockMode::GCM)
5369 .Padding(PaddingMode::NONE)
5370 .Authorization(TAG_MAC_LENGTH, 128);
5371 AuthorizationSet begin_out_params;
5372
Selene Huang31ab4042020-04-29 04:22:39 -07005373 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5374
Shawn Willden92d79c02021-02-19 07:31:55 -07005375 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005376 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005377 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5378 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005379
David Drysdaled2cc8c22021-04-15 13:29:45 +01005380 // The failure should have already cancelled the operation.
5381 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5382
Shawn Willden92d79c02021-02-19 07:31:55 -07005383 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005384}
5385
5386/*
5387 * EncryptionOperationsTest.AesGcmBadAad
5388 *
5389 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5390 */
5391TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5392 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5393 .Authorization(TAG_NO_AUTH_REQUIRED)
5394 .AesEncryptionKey(128)
5395 .BlockMode(BlockMode::GCM)
5396 .Padding(PaddingMode::NONE)
5397 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5398
5399 string message = "12345678901234567890123456789012";
5400 auto begin_params = AuthorizationSetBuilder()
5401 .BlockMode(BlockMode::GCM)
5402 .Padding(PaddingMode::NONE)
5403 .Authorization(TAG_MAC_LENGTH, 128);
5404
Selene Huang31ab4042020-04-29 04:22:39 -07005405 // Encrypt
5406 AuthorizationSet begin_out_params;
5407 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005408 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005409 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005410 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005411
5412 // Grab nonce
5413 begin_params.push_back(begin_out_params);
5414
Selene Huang31ab4042020-04-29 04:22:39 -07005415 // Decrypt.
5416 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005417 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005418 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005419 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005420}
5421
5422/*
5423 * EncryptionOperationsTest.AesGcmWrongNonce
5424 *
5425 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5426 */
5427TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
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;
5446 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005447 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005448
5449 // Wrong nonce
5450 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5451
5452 // Decrypt.
5453 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005454 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005455 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005456 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005457
5458 // With wrong nonce, should have gotten garbage plaintext (or none).
5459 EXPECT_NE(message, plaintext);
5460}
5461
5462/*
5463 * EncryptionOperationsTest.AesGcmCorruptTag
5464 *
5465 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5466 */
5467TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5468 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5469 .Authorization(TAG_NO_AUTH_REQUIRED)
5470 .AesEncryptionKey(128)
5471 .BlockMode(BlockMode::GCM)
5472 .Padding(PaddingMode::NONE)
5473 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5474
5475 string aad = "1234567890123456";
5476 string message = "123456789012345678901234567890123456";
5477
5478 auto params = AuthorizationSetBuilder()
5479 .BlockMode(BlockMode::GCM)
5480 .Padding(PaddingMode::NONE)
5481 .Authorization(TAG_MAC_LENGTH, 128);
5482
Selene Huang31ab4042020-04-29 04:22:39 -07005483 // Encrypt
5484 AuthorizationSet begin_out_params;
5485 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005486 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005487 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005488 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005489
5490 // Corrupt tag
5491 ++(*ciphertext.rbegin());
5492
5493 // Grab nonce
5494 params.push_back(begin_out_params);
5495
5496 // Decrypt.
5497 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005498 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005499 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005500 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005501}
5502
5503/*
5504 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5505 *
5506 * Verifies that 3DES is basically functional.
5507 */
5508TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5509 auto auths = AuthorizationSetBuilder()
5510 .TripleDesEncryptionKey(168)
5511 .BlockMode(BlockMode::ECB)
5512 .Authorization(TAG_NO_AUTH_REQUIRED)
5513 .Padding(PaddingMode::NONE);
5514
5515 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5516 // Two-block message.
5517 string message = "1234567890123456";
5518 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5519 string ciphertext1 = EncryptMessage(message, inParams);
5520 EXPECT_EQ(message.size(), ciphertext1.size());
5521
5522 string ciphertext2 = EncryptMessage(string(message), inParams);
5523 EXPECT_EQ(message.size(), ciphertext2.size());
5524
5525 // ECB is deterministic.
5526 EXPECT_EQ(ciphertext1, ciphertext2);
5527
5528 string plaintext = DecryptMessage(ciphertext1, inParams);
5529 EXPECT_EQ(message, plaintext);
5530}
5531
5532/*
5533 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5534 *
5535 * Verifies that CBC keys reject ECB usage.
5536 */
5537TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5538 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5539 .TripleDesEncryptionKey(168)
5540 .BlockMode(BlockMode::CBC)
5541 .Authorization(TAG_NO_AUTH_REQUIRED)
5542 .Padding(PaddingMode::NONE)));
5543
5544 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5545 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5546}
5547
5548/*
5549 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5550 *
5551 * Tests ECB mode with PKCS#7 padding, various message sizes.
5552 */
5553TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5554 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5555 .TripleDesEncryptionKey(168)
5556 .BlockMode(BlockMode::ECB)
5557 .Authorization(TAG_NO_AUTH_REQUIRED)
5558 .Padding(PaddingMode::PKCS7)));
5559
5560 for (size_t i = 0; i < 32; ++i) {
5561 string message(i, 'a');
5562 auto inParams =
5563 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5564 string ciphertext = EncryptMessage(message, inParams);
5565 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5566 string plaintext = DecryptMessage(ciphertext, inParams);
5567 EXPECT_EQ(message, plaintext);
5568 }
5569}
5570
5571/*
5572 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5573 *
5574 * Verifies that keys configured for no padding reject PKCS7 padding
5575 */
5576TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5577 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5578 .TripleDesEncryptionKey(168)
5579 .BlockMode(BlockMode::ECB)
5580 .Authorization(TAG_NO_AUTH_REQUIRED)
5581 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005582 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5583 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005584}
5585
5586/*
5587 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5588 *
5589 * Verifies that corrupted padding is detected.
5590 */
5591TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5592 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5593 .TripleDesEncryptionKey(168)
5594 .BlockMode(BlockMode::ECB)
5595 .Authorization(TAG_NO_AUTH_REQUIRED)
5596 .Padding(PaddingMode::PKCS7)));
5597
5598 string message = "a";
5599 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5600 EXPECT_EQ(8U, ciphertext.size());
5601 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005602
5603 AuthorizationSetBuilder begin_params;
5604 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5605 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07005606
5607 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5608 ++ciphertext[ciphertext.size() / 2];
5609
5610 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5611 string plaintext;
5612 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5613 ErrorCode error = Finish(&plaintext);
5614 if (error == ErrorCode::INVALID_ARGUMENT) {
5615 // This is the expected error, we can exit the test now.
5616 return;
5617 } else {
5618 // Very small chance we got valid decryption, so try again.
5619 ASSERT_EQ(error, ErrorCode::OK);
5620 }
5621 }
5622 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005623}
5624
5625struct TripleDesTestVector {
5626 const char* name;
5627 const KeyPurpose purpose;
5628 const BlockMode block_mode;
5629 const PaddingMode padding_mode;
5630 const char* key;
5631 const char* iv;
5632 const char* input;
5633 const char* output;
5634};
5635
5636// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5637// of the NIST vectors are multiples of the block size.
5638static const TripleDesTestVector kTripleDesTestVectors[] = {
5639 {
5640 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5641 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5642 "", // IV
5643 "329d86bdf1bc5af4", // input
5644 "d946c2756d78633f", // output
5645 },
5646 {
5647 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5648 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5649 "", // IV
5650 "6b1540781b01ce1997adae102dbf3c5b", // input
5651 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5652 },
5653 {
5654 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5655 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5656 "", // IV
5657 "6daad94ce08acfe7", // input
5658 "660e7d32dcc90e79", // output
5659 },
5660 {
5661 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5662 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5663 "", // IV
5664 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5665 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5666 },
5667 {
5668 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5669 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5670 "43f791134c5647ba", // IV
5671 "dcc153cef81d6f24", // input
5672 "92538bd8af18d3ba", // output
5673 },
5674 {
5675 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5676 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5677 "c2e999cb6249023c", // IV
5678 "c689aee38a301bb316da75db36f110b5", // input
5679 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5680 },
5681 {
5682 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5683 PaddingMode::PKCS7,
5684 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5685 "c2e999cb6249023c", // IV
5686 "c689aee38a301bb316da75db36f110b500", // input
5687 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5688 },
5689 {
5690 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5691 PaddingMode::PKCS7,
5692 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5693 "c2e999cb6249023c", // IV
5694 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5695 "c689aee38a301bb316da75db36f110b500", // output
5696 },
5697 {
5698 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5699 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5700 "41746c7e442d3681", // IV
5701 "c53a7b0ec40600fe", // input
5702 "d4f00eb455de1034", // output
5703 },
5704 {
5705 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5706 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5707 "3982bc02c3727d45", // IV
5708 "6006f10adef52991fcc777a1238bbb65", // input
5709 "edae09288e9e3bc05746d872b48e3b29", // output
5710 },
5711};
5712
5713/*
5714 * EncryptionOperationsTest.TripleDesTestVector
5715 *
5716 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5717 */
5718TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5719 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5720 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5721 SCOPED_TRACE(test->name);
5722 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5723 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5724 hex2str(test->output));
5725 }
5726}
5727
5728/*
5729 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5730 *
5731 * Validates CBC mode functionality.
5732 */
5733TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5734 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5735 .TripleDesEncryptionKey(168)
5736 .BlockMode(BlockMode::CBC)
5737 .Authorization(TAG_NO_AUTH_REQUIRED)
5738 .Padding(PaddingMode::NONE)));
5739
5740 ASSERT_GT(key_blob_.size(), 0U);
5741
5742 // Two-block message.
5743 string message = "1234567890123456";
5744 vector<uint8_t> iv1;
5745 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5746 EXPECT_EQ(message.size(), ciphertext1.size());
5747
5748 vector<uint8_t> iv2;
5749 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5750 EXPECT_EQ(message.size(), ciphertext2.size());
5751
5752 // IVs should be random, so ciphertexts should differ.
5753 EXPECT_NE(iv1, iv2);
5754 EXPECT_NE(ciphertext1, ciphertext2);
5755
5756 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5757 EXPECT_EQ(message, plaintext);
5758}
5759
5760/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005761 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5762 *
5763 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5764 */
5765TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5766 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5767 .TripleDesEncryptionKey(168)
5768 .BlockMode(BlockMode::CBC)
5769 .Authorization(TAG_NO_AUTH_REQUIRED)
5770 .Authorization(TAG_CALLER_NONCE)
5771 .Padding(PaddingMode::NONE)));
5772 auto params = AuthorizationSetBuilder()
5773 .BlockMode(BlockMode::CBC)
5774 .Padding(PaddingMode::NONE)
5775 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5776 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5777}
5778
5779/*
Selene Huang31ab4042020-04-29 04:22:39 -07005780 * EncryptionOperationsTest.TripleDesCallerIv
5781 *
5782 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5783 */
5784TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5785 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5786 .TripleDesEncryptionKey(168)
5787 .BlockMode(BlockMode::CBC)
5788 .Authorization(TAG_NO_AUTH_REQUIRED)
5789 .Authorization(TAG_CALLER_NONCE)
5790 .Padding(PaddingMode::NONE)));
5791 string message = "1234567890123456";
5792 vector<uint8_t> iv;
5793 // Don't specify IV, should get a random one.
5794 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5795 EXPECT_EQ(message.size(), ciphertext1.size());
5796 EXPECT_EQ(8U, iv.size());
5797
5798 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5799 EXPECT_EQ(message, plaintext);
5800
5801 // Now specify an IV, should also work.
5802 iv = AidlBuf("abcdefgh");
5803 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5804
5805 // Decrypt with correct IV.
5806 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5807 EXPECT_EQ(message, plaintext);
5808
5809 // Now try with wrong IV.
5810 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5811 EXPECT_NE(message, plaintext);
5812}
5813
5814/*
5815 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5816 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005817 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005818 */
5819TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5820 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5821 .TripleDesEncryptionKey(168)
5822 .BlockMode(BlockMode::CBC)
5823 .Authorization(TAG_NO_AUTH_REQUIRED)
5824 .Padding(PaddingMode::NONE)));
5825
5826 string message = "12345678901234567890123456789012";
5827 vector<uint8_t> iv;
5828 // Don't specify nonce, should get a random one.
5829 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5830 EXPECT_EQ(message.size(), ciphertext1.size());
5831 EXPECT_EQ(8U, iv.size());
5832
5833 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5834 EXPECT_EQ(message, plaintext);
5835
5836 // Now specify a nonce, should fail.
5837 auto input_params = AuthorizationSetBuilder()
5838 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5839 .BlockMode(BlockMode::CBC)
5840 .Padding(PaddingMode::NONE);
5841 AuthorizationSet output_params;
5842 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5843 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5844}
5845
5846/*
5847 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5848 *
5849 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5850 */
5851TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5852 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5853 .TripleDesEncryptionKey(168)
5854 .BlockMode(BlockMode::ECB)
5855 .Authorization(TAG_NO_AUTH_REQUIRED)
5856 .Padding(PaddingMode::NONE)));
5857 // Two-block message.
5858 string message = "1234567890123456";
5859 auto begin_params =
5860 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5861 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5862}
5863
5864/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005865 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005866 *
5867 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5868 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005869TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5870 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5871 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5872 .TripleDesEncryptionKey(168)
5873 .BlockMode(blockMode)
5874 .Authorization(TAG_NO_AUTH_REQUIRED)
5875 .Padding(PaddingMode::NONE)));
5876 // Message is slightly shorter than two blocks.
5877 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005878
David Drysdaled2cc8c22021-04-15 13:29:45 +01005879 auto begin_params =
5880 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5881 AuthorizationSet output_params;
5882 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5883 string ciphertext;
5884 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5885
5886 CheckedDeleteKey();
5887 }
Selene Huang31ab4042020-04-29 04:22:39 -07005888}
5889
5890/*
5891 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5892 *
5893 * Verifies that PKCS7 padding works correctly in CBC mode.
5894 */
5895TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5896 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5897 .TripleDesEncryptionKey(168)
5898 .BlockMode(BlockMode::CBC)
5899 .Authorization(TAG_NO_AUTH_REQUIRED)
5900 .Padding(PaddingMode::PKCS7)));
5901
5902 // Try various message lengths; all should work.
5903 for (size_t i = 0; i < 32; ++i) {
5904 string message(i, 'a');
5905 vector<uint8_t> iv;
5906 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5907 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5908 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5909 EXPECT_EQ(message, plaintext);
5910 }
5911}
5912
5913/*
5914 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5915 *
5916 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5917 */
5918TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5919 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5920 .TripleDesEncryptionKey(168)
5921 .BlockMode(BlockMode::CBC)
5922 .Authorization(TAG_NO_AUTH_REQUIRED)
5923 .Padding(PaddingMode::NONE)));
5924
5925 // Try various message lengths; all should fail.
5926 for (size_t i = 0; i < 32; ++i) {
5927 auto begin_params =
5928 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5929 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5930 }
5931}
5932
5933/*
5934 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5935 *
5936 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5937 */
5938TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5939 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5940 .TripleDesEncryptionKey(168)
5941 .BlockMode(BlockMode::CBC)
5942 .Authorization(TAG_NO_AUTH_REQUIRED)
5943 .Padding(PaddingMode::PKCS7)));
5944
5945 string message = "a";
5946 vector<uint8_t> iv;
5947 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5948 EXPECT_EQ(8U, ciphertext.size());
5949 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005950
5951 auto begin_params = AuthorizationSetBuilder()
5952 .BlockMode(BlockMode::CBC)
5953 .Padding(PaddingMode::PKCS7)
5954 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07005955
5956 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5957 ++ciphertext[ciphertext.size() / 2];
5958 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5959 string plaintext;
5960 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5961 ErrorCode error = Finish(&plaintext);
5962 if (error == ErrorCode::INVALID_ARGUMENT) {
5963 // This is the expected error, we can exit the test now.
5964 return;
5965 } else {
5966 // Very small chance we got valid decryption, so try again.
5967 ASSERT_EQ(error, ErrorCode::OK);
5968 }
5969 }
5970 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005971}
5972
5973/*
5974 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5975 *
5976 * Verifies that 3DES CBC works with many different input sizes.
5977 */
5978TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5979 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5980 .TripleDesEncryptionKey(168)
5981 .BlockMode(BlockMode::CBC)
5982 .Authorization(TAG_NO_AUTH_REQUIRED)
5983 .Padding(PaddingMode::NONE)));
5984
5985 int increment = 7;
5986 string message(240, 'a');
5987 AuthorizationSet input_params =
5988 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5989 AuthorizationSet output_params;
5990 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5991
5992 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005993 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005994 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005995 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5996 EXPECT_EQ(message.size(), ciphertext.size());
5997
5998 // Move TAG_NONCE into input_params
5999 input_params = output_params;
6000 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
6001 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
6002 output_params.Clear();
6003
6004 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
6005 string plaintext;
6006 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006007 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006008 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
6009 EXPECT_EQ(ciphertext.size(), plaintext.size());
6010 EXPECT_EQ(message, plaintext);
6011}
6012
6013INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
6014
6015typedef KeyMintAidlTestBase MaxOperationsTest;
6016
6017/*
6018 * MaxOperationsTest.TestLimitAes
6019 *
6020 * Verifies that the max uses per boot tag works correctly with AES keys.
6021 */
6022TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006023 if (SecLevel() == SecurityLevel::STRONGBOX) {
6024 GTEST_SKIP() << "Test not applicable to StrongBox device";
6025 }
Selene Huang31ab4042020-04-29 04:22:39 -07006026
6027 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6028 .Authorization(TAG_NO_AUTH_REQUIRED)
6029 .AesEncryptionKey(128)
6030 .EcbMode()
6031 .Padding(PaddingMode::NONE)
6032 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
6033
6034 string message = "1234567890123456";
6035
6036 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6037
6038 EncryptMessage(message, params);
6039 EncryptMessage(message, params);
6040 EncryptMessage(message, params);
6041
6042 // Fourth time should fail.
6043 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
6044}
6045
6046/*
Qi Wud22ec842020-11-26 13:27:53 +08006047 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07006048 *
6049 * Verifies that the max uses per boot tag works correctly with RSA keys.
6050 */
6051TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006052 if (SecLevel() == SecurityLevel::STRONGBOX) {
6053 GTEST_SKIP() << "Test not applicable to StrongBox device";
6054 }
Selene Huang31ab4042020-04-29 04:22:39 -07006055
6056 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6057 .Authorization(TAG_NO_AUTH_REQUIRED)
6058 .RsaSigningKey(1024, 65537)
6059 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006060 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
6061 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006062
6063 string message = "1234567890123456";
6064
6065 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6066
6067 SignMessage(message, params);
6068 SignMessage(message, params);
6069 SignMessage(message, params);
6070
6071 // Fourth time should fail.
6072 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6073}
6074
6075INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6076
Qi Wud22ec842020-11-26 13:27:53 +08006077typedef KeyMintAidlTestBase UsageCountLimitTest;
6078
6079/*
Qi Wubeefae42021-01-28 23:16:37 +08006080 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006081 *
Qi Wubeefae42021-01-28 23:16:37 +08006082 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006083 */
Qi Wubeefae42021-01-28 23:16:37 +08006084TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006085 if (SecLevel() == SecurityLevel::STRONGBOX) {
6086 GTEST_SKIP() << "Test not applicable to StrongBox device";
6087 }
Qi Wud22ec842020-11-26 13:27:53 +08006088
6089 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6090 .Authorization(TAG_NO_AUTH_REQUIRED)
6091 .AesEncryptionKey(128)
6092 .EcbMode()
6093 .Padding(PaddingMode::NONE)
6094 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
6095
6096 // Check the usage count limit tag appears in the authorizations.
6097 AuthorizationSet auths;
6098 for (auto& entry : key_characteristics_) {
6099 auths.push_back(AuthorizationSet(entry.authorizations));
6100 }
6101 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6102 << "key usage count limit " << 1U << " missing";
6103
6104 string message = "1234567890123456";
6105 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6106
Qi Wubeefae42021-01-28 23:16:37 +08006107 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6108 AuthorizationSet keystore_auths =
6109 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6110
Qi Wud22ec842020-11-26 13:27:53 +08006111 // First usage of AES key should work.
6112 EncryptMessage(message, params);
6113
Qi Wud22ec842020-11-26 13:27:53 +08006114 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6115 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6116 // must be invalidated from secure storage (such as RPMB partition).
6117 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6118 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006119 // Usage count limit tag is enforced by keystore, keymint does nothing.
6120 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08006121 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6122 }
6123}
6124
6125/*
Qi Wubeefae42021-01-28 23:16:37 +08006126 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006127 *
Qi Wubeefae42021-01-28 23:16:37 +08006128 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006129 */
Qi Wubeefae42021-01-28 23:16:37 +08006130TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006131 if (SecLevel() == SecurityLevel::STRONGBOX) {
6132 GTEST_SKIP() << "Test not applicable to StrongBox device";
6133 }
Qi Wubeefae42021-01-28 23:16:37 +08006134
6135 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6136 .Authorization(TAG_NO_AUTH_REQUIRED)
6137 .AesEncryptionKey(128)
6138 .EcbMode()
6139 .Padding(PaddingMode::NONE)
6140 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
6141
6142 // Check the usage count limit tag appears in the authorizations.
6143 AuthorizationSet auths;
6144 for (auto& entry : key_characteristics_) {
6145 auths.push_back(AuthorizationSet(entry.authorizations));
6146 }
6147 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6148 << "key usage count limit " << 3U << " missing";
6149
6150 string message = "1234567890123456";
6151 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6152
6153 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6154 AuthorizationSet keystore_auths =
6155 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6156
6157 EncryptMessage(message, params);
6158 EncryptMessage(message, params);
6159 EncryptMessage(message, params);
6160
6161 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6162 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6163 // must be invalidated from secure storage (such as RPMB partition).
6164 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6165 } else {
6166 // Usage count limit tag is enforced by keystore, keymint does nothing.
6167 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
6168 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6169 }
6170}
6171
6172/*
6173 * UsageCountLimitTest.TestSingleUseRsa
6174 *
6175 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
6176 */
6177TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006178 if (SecLevel() == SecurityLevel::STRONGBOX) {
6179 GTEST_SKIP() << "Test not applicable to StrongBox device";
6180 }
Qi Wud22ec842020-11-26 13:27:53 +08006181
6182 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6183 .Authorization(TAG_NO_AUTH_REQUIRED)
6184 .RsaSigningKey(1024, 65537)
6185 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006186 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6187 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08006188
6189 // Check the usage count limit tag appears in the authorizations.
6190 AuthorizationSet auths;
6191 for (auto& entry : key_characteristics_) {
6192 auths.push_back(AuthorizationSet(entry.authorizations));
6193 }
6194 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6195 << "key usage count limit " << 1U << " missing";
6196
6197 string message = "1234567890123456";
6198 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6199
Qi Wubeefae42021-01-28 23:16:37 +08006200 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6201 AuthorizationSet keystore_auths =
6202 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6203
Qi Wud22ec842020-11-26 13:27:53 +08006204 // First usage of RSA key should work.
6205 SignMessage(message, params);
6206
Qi Wud22ec842020-11-26 13:27:53 +08006207 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6208 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6209 // must be invalidated from secure storage (such as RPMB partition).
6210 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6211 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006212 // Usage count limit tag is enforced by keystore, keymint does nothing.
6213 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
6214 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6215 }
6216}
6217
6218/*
6219 * UsageCountLimitTest.TestLimitUseRsa
6220 *
6221 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
6222 */
6223TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006224 if (SecLevel() == SecurityLevel::STRONGBOX) {
6225 GTEST_SKIP() << "Test not applicable to StrongBox device";
6226 }
Qi Wubeefae42021-01-28 23:16:37 +08006227
6228 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6229 .Authorization(TAG_NO_AUTH_REQUIRED)
6230 .RsaSigningKey(1024, 65537)
6231 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006232 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6233 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006234
6235 // Check the usage count limit tag appears in the authorizations.
6236 AuthorizationSet auths;
6237 for (auto& entry : key_characteristics_) {
6238 auths.push_back(AuthorizationSet(entry.authorizations));
6239 }
6240 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6241 << "key usage count limit " << 3U << " missing";
6242
6243 string message = "1234567890123456";
6244 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6245
6246 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6247 AuthorizationSet keystore_auths =
6248 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6249
6250 SignMessage(message, params);
6251 SignMessage(message, params);
6252 SignMessage(message, params);
6253
6254 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6255 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6256 // must be invalidated from secure storage (such as RPMB partition).
6257 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6258 } else {
6259 // Usage count limit tag is enforced by keystore, keymint does nothing.
6260 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006261 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6262 }
6263}
6264
Qi Wu8e727f72021-02-11 02:49:33 +08006265/*
6266 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6267 *
6268 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6269 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6270 * in hardware.
6271 */
6272TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01006273 if (SecLevel() == SecurityLevel::STRONGBOX) {
6274 GTEST_SKIP() << "Test not applicable to StrongBox device";
6275 }
Qi Wu8e727f72021-02-11 02:49:33 +08006276
6277 auto error = GenerateKey(AuthorizationSetBuilder()
6278 .RsaSigningKey(2048, 65537)
6279 .Digest(Digest::NONE)
6280 .Padding(PaddingMode::NONE)
6281 .Authorization(TAG_NO_AUTH_REQUIRED)
6282 .Authorization(TAG_ROLLBACK_RESISTANCE)
6283 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006284 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6285 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08006286 }
David Drysdale513bf122021-10-06 11:53:13 +01006287
6288 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6289 ASSERT_EQ(ErrorCode::OK, error);
6290 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6291 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6292 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6293
6294 // The KeyMint should also enforce single use key in hardware when it supports rollback
6295 // resistance.
6296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6297 .Authorization(TAG_NO_AUTH_REQUIRED)
6298 .RsaSigningKey(1024, 65537)
6299 .NoDigestOrPadding()
6300 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6301 .SetDefaultValidity()));
6302
6303 // Check the usage count limit tag appears in the hardware authorizations.
6304 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6305 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6306 << "key usage count limit " << 1U << " missing";
6307
6308 string message = "1234567890123456";
6309 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6310
6311 // First usage of RSA key should work.
6312 SignMessage(message, params);
6313
6314 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6315 // must be invalidated from secure storage (such as RPMB partition).
6316 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08006317}
6318
Qi Wud22ec842020-11-26 13:27:53 +08006319INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6320
David Drysdale7de9feb2021-03-05 14:56:19 +00006321typedef KeyMintAidlTestBase GetHardwareInfoTest;
6322
6323TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6324 // Retrieving hardware info should give the same result each time.
6325 KeyMintHardwareInfo info;
6326 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6327 KeyMintHardwareInfo info2;
6328 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6329 EXPECT_EQ(info, info2);
6330}
6331
6332INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6333
Selene Huang31ab4042020-04-29 04:22:39 -07006334typedef KeyMintAidlTestBase AddEntropyTest;
6335
6336/*
6337 * AddEntropyTest.AddEntropy
6338 *
6339 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6340 * is actually added.
6341 */
6342TEST_P(AddEntropyTest, AddEntropy) {
6343 string data = "foo";
6344 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6345}
6346
6347/*
6348 * AddEntropyTest.AddEmptyEntropy
6349 *
6350 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6351 */
6352TEST_P(AddEntropyTest, AddEmptyEntropy) {
6353 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6354}
6355
6356/*
6357 * AddEntropyTest.AddLargeEntropy
6358 *
6359 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6360 */
6361TEST_P(AddEntropyTest, AddLargeEntropy) {
6362 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6363}
6364
David Drysdalebb3d85e2021-04-13 11:15:51 +01006365/*
6366 * AddEntropyTest.AddTooLargeEntropy
6367 *
6368 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6369 */
6370TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6371 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6372 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6373}
6374
Selene Huang31ab4042020-04-29 04:22:39 -07006375INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6376
Selene Huang31ab4042020-04-29 04:22:39 -07006377typedef KeyMintAidlTestBase KeyDeletionTest;
6378
6379/**
6380 * KeyDeletionTest.DeleteKey
6381 *
6382 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6383 * valid key blob.
6384 */
6385TEST_P(KeyDeletionTest, DeleteKey) {
6386 auto error = GenerateKey(AuthorizationSetBuilder()
6387 .RsaSigningKey(2048, 65537)
6388 .Digest(Digest::NONE)
6389 .Padding(PaddingMode::NONE)
6390 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006391 .Authorization(TAG_ROLLBACK_RESISTANCE)
6392 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006393 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6394 GTEST_SKIP() << "Rollback resistance not supported";
6395 }
Selene Huang31ab4042020-04-29 04:22:39 -07006396
6397 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006398 ASSERT_EQ(ErrorCode::OK, error);
6399 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6400 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006401
David Drysdale513bf122021-10-06 11:53:13 +01006402 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07006403
David Drysdale513bf122021-10-06 11:53:13 +01006404 string message = "12345678901234567890123456789012";
6405 AuthorizationSet begin_out_params;
6406 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6407 Begin(KeyPurpose::SIGN, key_blob_,
6408 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6409 &begin_out_params));
6410 AbortIfNeeded();
6411 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006412}
6413
6414/**
6415 * KeyDeletionTest.DeleteInvalidKey
6416 *
6417 * This test checks that the HAL excepts invalid key blobs..
6418 */
6419TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6420 // Generate key just to check if rollback protection is implemented
6421 auto error = GenerateKey(AuthorizationSetBuilder()
6422 .RsaSigningKey(2048, 65537)
6423 .Digest(Digest::NONE)
6424 .Padding(PaddingMode::NONE)
6425 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006426 .Authorization(TAG_ROLLBACK_RESISTANCE)
6427 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006428 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6429 GTEST_SKIP() << "Rollback resistance not supported";
6430 }
Selene Huang31ab4042020-04-29 04:22:39 -07006431
6432 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006433 ASSERT_EQ(ErrorCode::OK, error);
6434 AuthorizationSet enforced(SecLevelAuthorizations());
6435 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006436
David Drysdale513bf122021-10-06 11:53:13 +01006437 // Delete the key we don't care about the result at this point.
6438 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07006439
David Drysdale513bf122021-10-06 11:53:13 +01006440 // Now create an invalid key blob and delete it.
6441 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07006442
David Drysdale513bf122021-10-06 11:53:13 +01006443 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07006444}
6445
6446/**
6447 * KeyDeletionTest.DeleteAllKeys
6448 *
6449 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6450 *
6451 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6452 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6453 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6454 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6455 * credentials stored in Keystore/Keymint.
6456 */
6457TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01006458 if (!arm_deleteAllKeys) {
6459 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
6460 return;
6461 }
Selene Huang31ab4042020-04-29 04:22:39 -07006462 auto error = GenerateKey(AuthorizationSetBuilder()
6463 .RsaSigningKey(2048, 65537)
6464 .Digest(Digest::NONE)
6465 .Padding(PaddingMode::NONE)
6466 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06006467 .Authorization(TAG_ROLLBACK_RESISTANCE)
6468 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006469 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6470 GTEST_SKIP() << "Rollback resistance not supported";
6471 }
Selene Huang31ab4042020-04-29 04:22:39 -07006472
6473 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006474 ASSERT_EQ(ErrorCode::OK, error);
6475 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6476 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006477
David Drysdale513bf122021-10-06 11:53:13 +01006478 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07006479
David Drysdale513bf122021-10-06 11:53:13 +01006480 string message = "12345678901234567890123456789012";
6481 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07006482
David Drysdale513bf122021-10-06 11:53:13 +01006483 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6484 Begin(KeyPurpose::SIGN, key_blob_,
6485 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6486 &begin_out_params));
6487 AbortIfNeeded();
6488 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006489}
6490
6491INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6492
David Drysdaled2cc8c22021-04-15 13:29:45 +01006493typedef KeyMintAidlTestBase KeyUpgradeTest;
6494
6495/**
6496 * KeyUpgradeTest.UpgradeInvalidKey
6497 *
6498 * This test checks that the HAL excepts invalid key blobs..
6499 */
6500TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6501 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6502
6503 std::vector<uint8_t> new_blob;
6504 Status result = keymint_->upgradeKey(key_blob,
6505 AuthorizationSetBuilder()
6506 .Authorization(TAG_APPLICATION_ID, "clientid")
6507 .Authorization(TAG_APPLICATION_DATA, "appdata")
6508 .vector_data(),
6509 &new_blob);
6510 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6511}
6512
6513INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6514
Selene Huang31ab4042020-04-29 04:22:39 -07006515using UpgradeKeyTest = KeyMintAidlTestBase;
6516
6517/*
6518 * UpgradeKeyTest.UpgradeKey
6519 *
6520 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6521 */
6522TEST_P(UpgradeKeyTest, UpgradeKey) {
6523 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6524 .AesEncryptionKey(128)
6525 .Padding(PaddingMode::NONE)
6526 .Authorization(TAG_NO_AUTH_REQUIRED)));
6527
6528 auto result = UpgradeKey(key_blob_);
6529
6530 // Key doesn't need upgrading. Should get okay, but no new key blob.
6531 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6532}
6533
6534INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6535
6536using ClearOperationsTest = KeyMintAidlTestBase;
6537
6538/*
6539 * ClearSlotsTest.TooManyOperations
6540 *
6541 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6542 * operations are started without being finished or aborted. Also verifies
6543 * that aborting the operations clears the operations.
6544 *
6545 */
6546TEST_P(ClearOperationsTest, TooManyOperations) {
6547 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6548 .Authorization(TAG_NO_AUTH_REQUIRED)
6549 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006550 .Padding(PaddingMode::NONE)
6551 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006552
6553 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6554 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006555 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006556 AuthorizationSet out_params;
6557 ErrorCode result;
6558 size_t i;
6559
6560 for (i = 0; i < max_operations; i++) {
6561 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6562 if (ErrorCode::OK != result) {
6563 break;
6564 }
6565 }
6566 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6567 // Try again just in case there's a weird overflow bug
6568 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6569 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6570 for (size_t j = 0; j < i; j++) {
6571 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6572 << "Aboort failed for i = " << j << std::endl;
6573 }
6574 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6575 AbortIfNeeded();
6576}
6577
6578INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6579
6580typedef KeyMintAidlTestBase TransportLimitTest;
6581
6582/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006583 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006584 *
6585 * Verifies that passing input data to finish succeeds as expected.
6586 */
6587TEST_P(TransportLimitTest, LargeFinishInput) {
6588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6589 .Authorization(TAG_NO_AUTH_REQUIRED)
6590 .AesEncryptionKey(128)
6591 .BlockMode(BlockMode::ECB)
6592 .Padding(PaddingMode::NONE)));
6593
6594 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6595 auto cipher_params =
6596 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6597
6598 AuthorizationSet out_params;
6599 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6600
6601 string plain_message = std::string(1 << msg_size, 'x');
6602 string encrypted_message;
6603 auto rc = Finish(plain_message, &encrypted_message);
6604
6605 EXPECT_EQ(ErrorCode::OK, rc);
6606 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6607 << "Encrypt finish returned OK, but did not consume all of the given input";
6608 cipher_params.push_back(out_params);
6609
6610 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6611
6612 string decrypted_message;
6613 rc = Finish(encrypted_message, &decrypted_message);
6614 EXPECT_EQ(ErrorCode::OK, rc);
6615 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6616 << "Decrypt finish returned OK, did not consume all of the given input";
6617 }
6618}
6619
6620INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6621
David Zeuthene0c40892021-01-08 12:54:11 -05006622typedef KeyMintAidlTestBase KeyAgreementTest;
6623
Seth Moored79a0ec2021-12-13 20:03:33 +00006624static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05006625 switch (curve) {
6626 case EcCurve::P_224:
6627 return NID_secp224r1;
6628 case EcCurve::P_256:
6629 return NID_X9_62_prime256v1;
6630 case EcCurve::P_384:
6631 return NID_secp384r1;
6632 case EcCurve::P_521:
6633 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00006634 case EcCurve::CURVE_25519:
6635 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05006636 }
6637}
6638
6639/*
6640 * KeyAgreementTest.Ecdh
6641 *
6642 * Verifies that ECDH works for all curves
6643 */
6644TEST_P(KeyAgreementTest, Ecdh) {
6645 // Because it's possible to use this API with keys on different curves, we
6646 // check all N^2 combinations where N is the number of supported
6647 // curves.
6648 //
6649 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6650 // lot more curves we can be smart about things and just pick |otherCurve| so
6651 // it's not |curve| and that way we end up with only 2*N runs
6652 //
6653 for (auto curve : ValidCurves()) {
6654 for (auto localCurve : ValidCurves()) {
6655 // Generate EC key locally (with access to private key material)
6656 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
Seth Moored79a0ec2021-12-13 20:03:33 +00006657 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
David Zeuthene0c40892021-01-08 12:54:11 -05006658 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6659 ASSERT_NE(group, nullptr);
6660 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6661 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6662 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6663 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6664
6665 // Get encoded form of the public part of the locally generated key...
6666 unsigned char* p = nullptr;
6667 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6668 ASSERT_GT(encodedPublicKeySize, 0);
6669 vector<uint8_t> encodedPublicKey(
6670 reinterpret_cast<const uint8_t*>(p),
6671 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6672 OPENSSL_free(p);
6673
6674 // Generate EC key in KeyMint (only access to public key material)
6675 vector<uint8_t> challenge = {0x41, 0x42};
6676 EXPECT_EQ(
6677 ErrorCode::OK,
6678 GenerateKey(AuthorizationSetBuilder()
6679 .Authorization(TAG_NO_AUTH_REQUIRED)
6680 .Authorization(TAG_EC_CURVE, curve)
6681 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6682 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6683 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006684 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6685 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006686 << "Failed to generate key";
6687 ASSERT_GT(cert_chain_.size(), 0);
6688 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6689 ASSERT_NE(kmKeyCert, nullptr);
6690 // Check that keyAgreement (bit 4) is set in KeyUsage
6691 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6692 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6693 ASSERT_NE(kmPkey, nullptr);
6694 if (dump_Attestations) {
6695 for (size_t n = 0; n < cert_chain_.size(); n++) {
6696 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6697 }
6698 }
6699
6700 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6701 if (curve != localCurve) {
6702 // If the keys are using different curves KeyMint should fail with
6703 // ErrorCode:INVALID_ARGUMENT. Check that.
6704 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6705 string ZabFromKeyMintStr;
6706 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6707 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6708 &ZabFromKeyMintStr));
6709
6710 } else {
6711 // Otherwise if the keys are using the same curve, it should work.
6712 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6713 string ZabFromKeyMintStr;
6714 EXPECT_EQ(ErrorCode::OK,
6715 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6716 &ZabFromKeyMintStr));
6717 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6718
6719 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6720 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6721 ASSERT_NE(ctx, nullptr);
6722 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6723 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6724 size_t ZabFromTestLen = 0;
6725 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6726 vector<uint8_t> ZabFromTest;
6727 ZabFromTest.resize(ZabFromTestLen);
6728 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6729
6730 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6731 }
6732
6733 CheckedDeleteKey();
6734 }
6735 }
6736}
6737
6738INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6739
David Drysdaled2cc8c22021-04-15 13:29:45 +01006740using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6741
6742// This is a problematic test, as it can render the device under test permanently unusable.
6743// Re-enable and run at your own risk.
6744TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6745 auto result = DestroyAttestationIds();
6746 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6747}
6748
6749INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6750
Shawn Willdend659c7c2021-02-19 14:51:51 -07006751using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006752
David Drysdaledb0dcf52021-05-18 11:43:31 +01006753/*
6754 * EarlyBootKeyTest.CreateEarlyBootKeys
6755 *
6756 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6757 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006758TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01006759 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006760 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6761 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6762
David Drysdaleadfe6112021-05-27 12:00:53 +01006763 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6764 ASSERT_GT(keyData.blob.size(), 0U);
6765 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6766 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6767 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006768 CheckedDeleteKey(&aesKeyData.blob);
6769 CheckedDeleteKey(&hmacKeyData.blob);
6770 CheckedDeleteKey(&rsaKeyData.blob);
6771 CheckedDeleteKey(&ecdsaKeyData.blob);
6772}
6773
David Drysdaledb0dcf52021-05-18 11:43:31 +01006774/*
David Drysdaleadfe6112021-05-27 12:00:53 +01006775 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6776 *
6777 * Verifies that creating an early boot key with attestation succeeds.
6778 */
6779TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6780 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6781 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6782 builder->AttestationChallenge("challenge");
6783 builder->AttestationApplicationId("app_id");
6784 });
6785
6786 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6787 ASSERT_GT(keyData.blob.size(), 0U);
6788 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6789 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6790 }
6791 CheckedDeleteKey(&aesKeyData.blob);
6792 CheckedDeleteKey(&hmacKeyData.blob);
6793 CheckedDeleteKey(&rsaKeyData.blob);
6794 CheckedDeleteKey(&ecdsaKeyData.blob);
6795}
6796
6797/*
6798 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01006799 *
6800 * Verifies that using early boot keys at a later stage fails.
6801 */
6802TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6803 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6804 .Authorization(TAG_NO_AUTH_REQUIRED)
6805 .Authorization(TAG_EARLY_BOOT_ONLY)
6806 .HmacKey(128)
6807 .Digest(Digest::SHA_2_256)
6808 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6809 AuthorizationSet output_params;
6810 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6811 AuthorizationSetBuilder()
6812 .Digest(Digest::SHA_2_256)
6813 .Authorization(TAG_MAC_LENGTH, 256),
6814 &output_params));
6815}
6816
6817/*
6818 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6819 *
6820 * Verifies that importing early boot keys fails.
6821 */
6822TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6823 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6824 .Authorization(TAG_NO_AUTH_REQUIRED)
6825 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01006826 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01006827 .Digest(Digest::SHA_2_256)
6828 .SetDefaultValidity(),
6829 KeyFormat::PKCS8, ec_256_key));
6830}
6831
David Drysdaled2cc8c22021-04-15 13:29:45 +01006832// 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 +00006833// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6834// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6835// early boot, so you'll have to reboot between runs.
6836TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6837 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6838 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6839 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6840 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6841 EXPECT_TRUE(
6842 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6843 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6844 EXPECT_TRUE(
6845 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6846
6847 // Should be able to use keys, since early boot has not ended
6848 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6849 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6850 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6851 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6852
6853 // End early boot
6854 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6855 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6856
6857 // Should not be able to use already-created keys.
6858 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6859 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6860 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6861 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6862
6863 CheckedDeleteKey(&aesKeyData.blob);
6864 CheckedDeleteKey(&hmacKeyData.blob);
6865 CheckedDeleteKey(&rsaKeyData.blob);
6866 CheckedDeleteKey(&ecdsaKeyData.blob);
6867
6868 // Should not be able to create new keys
6869 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6870 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6871
6872 CheckedDeleteKey(&aesKeyData.blob);
6873 CheckedDeleteKey(&hmacKeyData.blob);
6874 CheckedDeleteKey(&rsaKeyData.blob);
6875 CheckedDeleteKey(&ecdsaKeyData.blob);
6876}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006877
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006878INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6879
Shawn Willdend659c7c2021-02-19 14:51:51 -07006880using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006881
6882// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6883// between runs... and on most test devices there are no enrolled credentials so it can't be
6884// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6885// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6886// a manual test process, which includes unlocking between runs, which is why it's included here.
6887// Well, that and the fact that it's the only test we can do without also making calls into the
6888// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6889// implications might be, so that may or may not be a solution.
6890TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6891 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6892 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6893
6894 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6895 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6896 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6897 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6898
6899 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006900 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006901 ASSERT_EQ(ErrorCode::OK, rc);
6902 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6903 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6904 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6905 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6906
6907 CheckedDeleteKey(&aesKeyData.blob);
6908 CheckedDeleteKey(&hmacKeyData.blob);
6909 CheckedDeleteKey(&rsaKeyData.blob);
6910 CheckedDeleteKey(&ecdsaKeyData.blob);
6911}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006912
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006913INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6914
Janis Danisevskis24c04702020-12-16 18:28:39 -08006915} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006916
6917int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006918 std::cout << "Testing ";
6919 auto halInstances =
6920 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6921 std::cout << "HAL instances:\n";
6922 for (auto& entry : halInstances) {
6923 std::cout << " " << entry << '\n';
6924 }
6925
Selene Huang31ab4042020-04-29 04:22:39 -07006926 ::testing::InitGoogleTest(&argc, argv);
6927 for (int i = 1; i < argc; ++i) {
6928 if (argv[i][0] == '-') {
6929 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006930 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6931 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006932 }
6933 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006934 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6935 dump_Attestations = true;
6936 } else {
6937 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006938 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00006939 if (std::string(argv[i]) == "--skip_boot_pl_check") {
6940 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
6941 // be run in emulated environments that don't have the normal bootloader
6942 // interactions.
6943 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
6944 }
Selene Huang31ab4042020-04-29 04:22:39 -07006945 }
6946 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006947 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006948}