blob: 2a7911cc36fd473ffdd86680da23b5fa79a64170 [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale37af4b32021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Zeuthene0c40892021-01-08 12:54:11 -050025#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070026#include <openssl/evp.h>
27#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050028#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070029
30#include <cutils/properties.h>
31
David Drysdale4dc01072021-04-01 12:17:35 +010032#include <android/binder_manager.h>
33
34#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080035#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070036
Shawn Willden08a7e432020-12-11 13:05:27 +000037#include <keymint_support/key_param_output.h>
38#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070039
40#include "KeyMintAidlTestBase.h"
41
Janis Danisevskis24c04702020-12-16 18:28:39 -080042using aidl::android::hardware::security::keymint::AuthorizationSet;
43using aidl::android::hardware::security::keymint::KeyCharacteristics;
44using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070045
Selene Huang31ab4042020-04-29 04:22:39 -070046namespace std {
47
Janis Danisevskis24c04702020-12-16 18:28:39 -080048using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070049
50template <>
51struct std::equal_to<KeyCharacteristics> {
52 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070053 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070054
Shawn Willden7f424372021-01-10 18:06:50 -070055 // this isn't very efficient. Oh, well.
56 AuthorizationSet a_auths(a.authorizations);
57 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070058
Shawn Willden7f424372021-01-10 18:06:50 -070059 a_auths.Sort();
60 b_auths.Sort();
61
62 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070063 }
64};
65
66} // namespace std
67
Janis Danisevskis24c04702020-12-16 18:28:39 -080068namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000069
Selene Huang31ab4042020-04-29 04:22:39 -070070namespace {
71
David Drysdaledbbbe2e2021-12-02 07:44:23 +000072// Whether to check that BOOT_PATCHLEVEL is populated.
73bool check_boot_pl = true;
74
Seth Moore7a55ae32021-06-23 14:28:11 -070075// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000076// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070077// is a small (roughly 1/256) chance that corrupting ciphertext still results
78// in valid PKCS7 padding.
79constexpr size_t kMaxPaddingCorruptionRetries = 8;
80
Selene Huang31ab4042020-04-29 04:22:39 -070081template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000082bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
83 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070084 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080085 if (auto p = authorizationValue(ttag, param)) {
86 return *p == expected_value;
87 }
88 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070089 });
90 return (it != set.end());
91}
92
93template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000094bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070095 auto it = std::find_if(set.begin(), set.end(),
96 [&](const KeyParameter& param) { return param.tag == tag; });
97 return (it != set.end());
98}
99
100constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
101 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
102 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
103 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
104 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
107 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
115 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
116
117string hex2str(string a) {
118 string b;
119 size_t num = a.size() / 2;
120 b.resize(num);
121 for (size_t i = 0; i < num; i++) {
122 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
123 }
124 return b;
125}
126
David Drysdaled2cc8c22021-04-15 13:29:45 +0100127string rsa_key = hex2str(
128 // RFC 5208 s5
129 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
130 "020100" // INTEGER length 1 value 0x00 (version)
131 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
132 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
133 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
134 "0500" // NULL (parameters)
135 // } end SEQUENCE (AlgorithmIdentifier)
136 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
137 // RFC 8017 A.1.2
138 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
139 "020100" // INTEGER length 1 value 0x00 (version)
140 "028181" // INTEGER length 0x81 value (modulus) ...
141 "00c6095409047d8634812d5a218176e4"
142 "5c41d60a75b13901f234226cffe77652"
143 "1c5a77b9e389417b71c0b6a44d13afe4"
144 "e4a2805d46c9da2935adb1ff0c1f24ea"
145 "06e62b20d776430a4d435157233c6f91"
146 "6783c30e310fcbd89b85c2d567711697"
147 "85ac12bca244abda72bfb19fc44d27c8"
148 "1e1d92de284f4061edfd99280745ea6d"
149 "25"
150 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
151 "028180" // INTEGER length 0x80 (privateExponent) value...
152 "1be0f04d9cae3718691f035338308e91"
153 "564b55899ffb5084d2460e6630257e05"
154 "b3ceab02972dfabcd6ce5f6ee2589eb6"
155 "7911ed0fac16e43a444b8c861e544a05"
156 "93365772f8baf6b22fc9e3c5f1024b06"
157 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
158 "ace7240290bef16c0b3f7f3cdd64ce3a"
159 "b5912cf6e32f39ab188358afcccd8081"
160 "0241" // INTEGER length 0x41 (prime1)
161 "00e4b49ef50f765d3b24dde01aceaaf1"
162 "30f2c76670a91a61ae08af497b4a82be"
163 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
164 "8c92bfab137fba2285227b83c342ff7c"
165 "55"
166 "0241" // INTEGER length 0x41 (prime2)
167 "00ddabb5839c4c7f6bf3d4183231f005"
168 "b31aa58affdda5c79e4cce217f6bc930"
169 "dbe563d480706c24e9ebfcab28a6cdef"
170 "d324b77e1bf7251b709092c24ff501fd"
171 "91"
172 "0240" // INTEGER length 0x40 (exponent1)
173 "23d4340eda3445d8cd26c14411da6fdc"
174 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
175 "842c1d280405bc2f6c1bea214a1d742a"
176 "b996b35b63a82a5e470fa88dbf823cdd"
177 "0240" // INTEGER length 0x40 (exponent2)
178 "1b7b57449ad30d1518249a5f56bb9829"
179 "4d4b6ac12ffc86940497a5a5837a6cf9"
180 "46262b494526d328c11e1126380fde04"
181 "c24f916dec250892db09a6d77cdba351"
182 "0240" // INTEGER length 0x40 (coefficient)
183 "7762cd8f4d050da56bd591adb515d24d"
184 "7ccd32cca0d05f866d583514bd7324d5"
185 "f33645e8ed8b4a1cb3cc4a1d67987399"
186 "f2a09f5b3fb68c88d5e5d90ac33492d6"
187 // } end SEQUENCE (PrivateKey)
188 // } end SEQUENCE (PrivateKeyInfo)
189);
Selene Huang31ab4042020-04-29 04:22:39 -0700190
Selene Huange5727e62021-04-13 22:41:20 -0700191/*
192 * DER-encoded PKCS#8 format RSA key. Generated using:
193 *
194 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
195 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100196string rsa_2048_key = hex2str(
197 // RFC 5208 s5
198 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
199 "020100" // INTEGER length 1 value 0x00 (version)
200 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
201 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
202 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
203 "0500" // NULL (parameters)
204 // } end SEQUENCE (AlgorithmIdentifier)
205 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
206 // RFC 8017 A.1.2
207 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
208 "020100" // INTEGER length 1 value 0x00 (version)
209 "02820101" // INTEGER length 0x101 value (modulus) ...
210 "00BEBC342B56D443B1299F9A6A7056E8"
211 "0A897E318476A5A18029E63B2ED739A6"
212 "1791D339F58DC763D9D14911F2EDEC38"
213 "3DEE11F6319B44510E7A3ECD9B79B973"
214 "82E49500ACF8117DC89CAF0E621F7775"
215 "6554A2FD4664BFE7AB8B59AB48340DBF"
216 "A27B93B5A81F6ECDEB02D0759307128D"
217 "F3E3BAD4055C8B840216DFAA5700670E"
218 "6C5126F0962FCB70FF308F25049164CC"
219 "F76CC2DA66A7DD9A81A714C2809D6918"
220 "6133D29D84568E892B6FFBF3199BDB14"
221 "383EE224407F190358F111A949552ABA"
222 "6714227D1BD7F6B20DD0CB88F9467B71"
223 "9339F33BFF35B3870B3F62204E4286B0"
224 "948EA348B524544B5F9838F29EE643B0"
225 "79EEF8A713B220D7806924CDF7295070"
226 "C5"
227 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
228 "02820100" // INTEGER length 0x100 (privateExponent) value...
229 "69F377F35F2F584EF075353CCD1CA997"
230 "38DB3DBC7C7FF35F9366CE176DFD1B13"
231 "5AB10030344ABF5FBECF1D4659FDEF1C"
232 "0FC430834BE1BE3911951377BB3D563A"
233 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
234 "2686C7B4B3C09A7B8354133E6F93F790"
235 "D59EAEB92E84C9A4339302CCE28FDF04"
236 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
237 "6AB706645BF074A4E4090D06FB163124"
238 "365FD5EE7A20D350E9958CC30D91326E"
239 "1B292E9EF5DB408EC42DAF737D201497"
240 "04D0A678A0FB5B5446863B099228A352"
241 "D604BA8091A164D01D5AB05397C71EAD"
242 "20BE2A08FC528FE442817809C787FEE4"
243 "AB97F97B9130D022153EDC6EB6CBE7B0"
244 "F8E3473F2E901209B5DB10F93604DB01"
245 "028181" // INTEGER length 0x81 (prime1)
246 "00E83C0998214941EA4F9293F1B77E2E"
247 "99E6CF305FAF358238E126124FEAF2EB"
248 "9724B2EA7B78E6032343821A80E55D1D"
249 "88FB12D220C3F41A56142FEC85796D19"
250 "17F1E8C774F142B67D3D6E7B7E6B4383"
251 "E94DB5929089DBB346D5BDAB40CC2D96"
252 "EE0409475E175C63BF78CFD744136740"
253 "838127EA723FF3FE7FA368C1311B4A4E"
254 "05"
255 "028181" // INTEGER length 0x81 (prime2)
256 "00D240FCC0F5D7715CDE21CB2DC86EA1"
257 "46132EA3B06F61FF2AF54BF38473F59D"
258 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
259 "B1B58C39F95E4798CCBB43E83D0119AC"
260 "F532F359CA743C85199F0286610E2009"
261 "97D7312917179AC9B67558773212EC96"
262 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
263 "94D94E066A0900B7B70E82A44FB30053"
264 "C1"
265 "028181" // INTEGER length 0x81 (exponent1)
266 "00AD15DA1CBD6A492B66851BA8C316D3"
267 "8AB700E2CFDDD926A658003513C54BAA"
268 "152B30021D667D20078F500F8AD3E7F3"
269 "945D74A891ED1A28EAD0FEEAEC8C14A8"
270 "E834CF46A13D1378C99D18940823CFDD"
271 "27EC5810D59339E0C34198AC638E09C8"
272 "7CBB1B634A9864AE9F4D5EB2D53514F6"
273 "7B4CAEC048C8AB849A02E397618F3271"
274 "35"
275 "028180" // INTEGER length 0x80 (exponent2)
276 "1FA2C1A5331880A92D8F3E281C617108"
277 "BF38244F16E352E69ED417C7153F9EC3"
278 "18F211839C643DCF8B4DD67CE2AC312E"
279 "95178D5D952F06B1BF779F4916924B70"
280 "F582A23F11304E02A5E7565AE22A35E7"
281 "4FECC8B6FDC93F92A1A37703E4CF0E63"
282 "783BD02EB716A7ECBBFA606B10B74D01"
283 "579522E7EF84D91FC522292108D902C1"
284 "028180" // INTEGER length 0x80 (coefficient)
285 "796FE3825F9DCC85DF22D58690065D93"
286 "898ACD65C087BEA8DA3A63BF4549B795"
287 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
288 "0D74F40DED8E1102C52152A31B6165F8"
289 "3A6722AECFCC35A493D7634664B888A0"
290 "8D3EB034F12EA28BFEE346E205D33482"
291 "7F778B16ED40872BD29FCB36536B6E93"
292 "FFB06778696B4A9D81BB0A9423E63DE5"
293 // } end SEQUENCE (PrivateKey)
294 // } end SEQUENCE (PrivateKeyInfo)
295);
Selene Huange5727e62021-04-13 22:41:20 -0700296
David Drysdaled2cc8c22021-04-15 13:29:45 +0100297string ec_256_key = hex2str(
298 // RFC 5208 s5
299 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
300 "020100" // INTEGER length 1 value 0 (version)
301 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
302 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
303 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
304 "0608" // OBJECT IDENTIFIER length 8 (param)
305 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
306 // } end SEQUENCE (AlgorithmIdentifier)
307 "046d" // OCTET STRING length 0x6d (privateKey) holding...
308 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
309 "020101" // INTEGER length 1 value 1 (version)
310 "0420" // OCTET STRING length 0x20 (privateKey)
311 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
312 "941eed09366bc03299986481f3a4d859"
313 "a144" // TAG [1] len 0x44 (publicKey) {
314 "03420004bf85d7720d07c25461683bc6"
315 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
316 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
317 "bcc41c6eb00083cf3376d11fd44949e0"
318 "b2183bfe"
319 // } end SEQUENCE (ECPrivateKey)
320 // } end SEQUENCE (PrivateKeyInfo)
321);
Selene Huang31ab4042020-04-29 04:22:39 -0700322
David Drysdaled2cc8c22021-04-15 13:29:45 +0100323string ec_521_key = hex2str(
324 // RFC 5208 s5
325 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
326 "020100" // INTEGER length 1 value 0 (version)
327 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
328 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
329 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
330 "0605" // OBJECT IDENTIFIER length 5 (param)
331 "2B81040023" // 1.3.132.0.35 (secp521r1)
332 // } end SEQUENCE (AlgorithmIdentifier)
333 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
334 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
335 "020101" // INTEGER length 1 value 1 (version)
336 "0442" // OCTET STRING length 0x42 (privateKey)
337 "0011458C586DB5DAA92AFAB03F4FE46A"
338 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
339 "9D18D7D08B5BCFA0E53C75B064AD51C4"
340 "49BAE0258D54B94B1E885DED08ED4FB2"
341 "5CE9"
342 "A18189" // TAG [1] len 0x89 (publicKey) {
343 "03818600040149EC11C6DF0FA122C6A9"
344 "AFD9754A4FA9513A627CA329E349535A"
345 "5629875A8ADFBE27DCB932C051986377"
346 "108D054C28C6F39B6F2C9AF81802F9F3"
347 "26B842FF2E5F3C00AB7635CFB36157FC"
348 "0882D574A10D839C1A0C049DC5E0D775"
349 "E2EE50671A208431BB45E78E70BEFE93"
350 "0DB34818EE4D5C26259F5C6B8E28A652"
351 "950F9F88D7B4B2C9D9"
352 // } end SEQUENCE (ECPrivateKey)
353 // } end SEQUENCE (PrivateKeyInfo)
354);
Selene Huang31ab4042020-04-29 04:22:39 -0700355
David Drysdaled2cc8c22021-04-15 13:29:45 +0100356string ec_256_key_rfc5915 = hex2str(
357 // RFC 5208 s5
358 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
359 "020100" // INTEGER length 1 value 0 (version)
360 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
361 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
362 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
363 "0608" // OBJECT IDENTIFIER length 8 (param)
364 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
365 // } end SEQUENCE (AlgorithmIdentifier)
366 "0479" // OCTET STRING length 0x79 (privateKey) holding...
367 // RFC 5915 s3
368 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
369 "020101" // INTEGER length 1 value 1 (version)
370 "0420" // OCTET STRING length 0x42 (privateKey)
371 "782370a8c8ce5537baadd04dcff079c8"
372 "158cfa9c67b818b38e8d21c9fa750c1d"
373 "a00a" // TAG [0] length 0xa (parameters)
374 "0608" // OBJECT IDENTIFIER length 8
375 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
376 // } end TAG [0]
377 "a144" // TAG [1] length 0x44 (publicKey) {
378 "0342" // BIT STRING length 0x42
379 "00" // no pad bits
380 "04e2cc561ee701da0ad0ef0d176bb0c9"
381 "19d42e79c393fdc1bd6c4010d85cf2cf"
382 "8e68c905464666f98dad4f01573ba810"
383 "78b3428570a439ba3229fbc026c55068"
384 "2f"
385 // } end SEQUENCE (ECPrivateKey)
386 // } end SEQUENCE (PrivateKeyInfo)
387);
Selene Huang31ab4042020-04-29 04:22:39 -0700388
David Drysdaled2cc8c22021-04-15 13:29:45 +0100389string ec_256_key_sec1 = hex2str(
390 // RFC 5208 s5
391 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
392 "020100" // INTEGER length 1 value 0 (version)
393 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
394 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
395 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
396 "0608" // OBJECT IDENTIFIER length 8 (param)
397 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
398 // } end SEQUENCE (AlgorithmIdentifier)
399 "046d" // OCTET STRING length 0x6d (privateKey) holding...
400 // SEC1-v2 C.4
401 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
402 "020101" // INTEGER length 1 value 0x01 (version)
403 "0420" // OCTET STRING length 0x20 (privateKey)
404 "782370a8c8ce5537baadd04dcff079c8"
405 "158cfa9c67b818b38e8d21c9fa750c1d"
406 "a144" // TAG [1] length 0x44 (publicKey) {
407 "0342" // BIT STRING length 0x42
408 "00" // no pad bits
409 "04e2cc561ee701da0ad0ef0d176bb0c9"
410 "19d42e79c393fdc1bd6c4010d85cf2cf"
411 "8e68c905464666f98dad4f01573ba810"
412 "78b3428570a439ba3229fbc026c55068"
413 "2f"
414 // } end TAG [1] (publicKey)
415 // } end SEQUENCE (PrivateKeyInfo)
416);
Selene Huang31ab4042020-04-29 04:22:39 -0700417
418struct RSA_Delete {
419 void operator()(RSA* p) { RSA_free(p); }
420};
421
Selene Huang31ab4042020-04-29 04:22:39 -0700422std::string make_string(const uint8_t* data, size_t length) {
423 return std::string(reinterpret_cast<const char*>(data), length);
424}
425
426template <size_t N>
427std::string make_string(const uint8_t (&a)[N]) {
428 return make_string(a, N);
429}
430
431class AidlBuf : public vector<uint8_t> {
432 typedef vector<uint8_t> super;
433
434 public:
435 AidlBuf() {}
436 AidlBuf(const super& other) : super(other) {}
437 AidlBuf(super&& other) : super(std::move(other)) {}
438 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
439
440 AidlBuf& operator=(const super& other) {
441 super::operator=(other);
442 return *this;
443 }
444
445 AidlBuf& operator=(super&& other) {
446 super::operator=(std::move(other));
447 return *this;
448 }
449
450 AidlBuf& operator=(const string& other) {
451 resize(other.size());
452 for (size_t i = 0; i < other.size(); ++i) {
453 (*this)[i] = static_cast<uint8_t>(other[i]);
454 }
455 return *this;
456 }
457
458 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
459};
460
David Drysdale4dc01072021-04-01 12:17:35 +0100461string device_suffix(const string& name) {
462 size_t pos = name.find('/');
463 if (pos == string::npos) {
464 return name;
465 }
466 return name.substr(pos + 1);
467}
468
469bool matching_rp_instance(const string& km_name,
470 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
471 string km_suffix = device_suffix(km_name);
472
473 vector<string> rp_names =
474 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
475 for (const string& rp_name : rp_names) {
476 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
477 // KeyMint instance, assume they match.
478 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
479 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
480 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
481 return true;
482 }
483 }
484 return false;
485}
486
Selene Huang31ab4042020-04-29 04:22:39 -0700487} // namespace
488
489class NewKeyGenerationTest : public KeyMintAidlTestBase {
490 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700491 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000492 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700493 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700494
Selene Huang31ab4042020-04-29 04:22:39 -0700495 // Check that some unexpected tags/values are NOT present.
496 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
497 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000498 }
499
500 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
501 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
502 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
503 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
504
505 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000506 }
507
508 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
509 // TODO(swillden): Distinguish which params should be in which auth list.
510 AuthorizationSet auths;
511 for (auto& entry : keyCharacteristics) {
512 auths.push_back(AuthorizationSet(entry.authorizations));
513 }
514 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
515
516 // Verify that App data, ROT and auth timeout are NOT included.
517 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
518 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700519 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
520
David Drysdaled2cc8c22021-04-15 13:29:45 +0100521 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
522 // never adds it.
523 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
524
David Drysdale7de9feb2021-03-05 14:56:19 +0000525 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700526 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000527 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700528 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700529 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000530 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700531 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000532
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000533 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100534 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
535 EXPECT_TRUE(vendor_pl);
536 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000537
538 // Should include boot patchlevel (but there are some test scenarios where this is not
539 // possible).
540 if (check_boot_pl) {
541 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
542 EXPECT_TRUE(boot_pl);
543 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100544
David Drysdale7de9feb2021-03-05 14:56:19 +0000545 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700546 }
547};
548
549/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000550 * NewKeyGenerationTest.Aes
551 *
552 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
553 * have correct characteristics.
554 */
555TEST_P(NewKeyGenerationTest, Aes) {
556 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
557 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
558 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
559 SCOPED_TRACE(testing::Message()
560 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
561 vector<uint8_t> key_blob;
562 vector<KeyCharacteristics> key_characteristics;
563 auto builder = AuthorizationSetBuilder()
564 .AesEncryptionKey(key_size)
565 .BlockMode(block_mode)
566 .Padding(padding_mode)
567 .SetDefaultValidity();
568 if (block_mode == BlockMode::GCM) {
569 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
570 }
571 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
572
573 EXPECT_GT(key_blob.size(), 0U);
574 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100575 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000576
577 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
578
579 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
580 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
581 << "Key size " << key_size << "missing";
582
583 CheckedDeleteKey(&key_blob);
584 }
585 }
586 }
587}
588
589/*
590 * NewKeyGenerationTest.AesInvalidSize
591 *
592 * Verifies that specifying an invalid key size for AES key generation returns
593 * UNSUPPORTED_KEY_SIZE.
594 */
595TEST_P(NewKeyGenerationTest, AesInvalidSize) {
596 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
597 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
598 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
599 SCOPED_TRACE(testing::Message()
600 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
601 vector<uint8_t> key_blob;
602 vector<KeyCharacteristics> key_characteristics;
603 auto builder = AuthorizationSetBuilder()
604 .AesEncryptionKey(key_size)
605 .BlockMode(block_mode)
606 .Padding(padding_mode)
607 .SetDefaultValidity();
608 if (block_mode == BlockMode::GCM) {
609 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
610 }
611 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
612 GenerateKey(builder, &key_blob, &key_characteristics));
613 }
614 }
615 }
616
617 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
618 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
619 vector<uint8_t> key_blob;
620 vector<KeyCharacteristics> key_characteristics;
621 // No key size specified
622 auto builder = AuthorizationSetBuilder()
623 .Authorization(TAG_ALGORITHM, Algorithm::AES)
624 .BlockMode(block_mode)
625 .Padding(padding_mode)
626 .SetDefaultValidity();
627 if (block_mode == BlockMode::GCM) {
628 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
629 }
630 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
631 GenerateKey(builder, &key_blob, &key_characteristics));
632 }
633 }
634}
635
636/*
637 * NewKeyGenerationTest.AesInvalidPadding
638 *
639 * Verifies that specifying an invalid padding on AES keys gives a failure
640 * somewhere along the way.
641 */
642TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
643 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
644 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
645 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
646 SCOPED_TRACE(testing::Message()
647 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000648 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800649 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000650 .AesEncryptionKey(key_size)
651 .BlockMode(block_mode)
652 .Padding(padding_mode)
653 .SetDefaultValidity();
654 if (block_mode == BlockMode::GCM) {
655 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
656 }
657
Tommy Chiu3950b452021-05-03 22:01:46 +0800658 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000659 if (result == ErrorCode::OK) {
660 // Key creation was OK but has generated a key that cannot be used.
661 auto params =
662 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800663 if (block_mode == BlockMode::GCM) {
664 params.Authorization(TAG_MAC_LENGTH, 128);
665 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000666 auto result = Begin(KeyPurpose::ENCRYPT, params);
667 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100668 result == ErrorCode::INVALID_KEY_BLOB)
669 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000670 } else {
671 // The KeyMint implementation detected that the generated key
672 // is unusable.
673 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
674 }
675 }
676 }
677 }
678}
679
680/*
681 * NewKeyGenerationTest.AesGcmMissingMinMac
682 *
683 * Verifies that specifying an invalid key size for AES key generation returns
684 * UNSUPPORTED_KEY_SIZE.
685 */
686TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
687 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
688 BlockMode block_mode = BlockMode::GCM;
689 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
690 SCOPED_TRACE(testing::Message()
691 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
692 vector<uint8_t> key_blob;
693 vector<KeyCharacteristics> key_characteristics;
694 // No MIN_MAC_LENGTH provided.
695 auto builder = AuthorizationSetBuilder()
696 .AesEncryptionKey(key_size)
697 .BlockMode(block_mode)
698 .Padding(padding_mode)
699 .SetDefaultValidity();
700 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
701 GenerateKey(builder, &key_blob, &key_characteristics));
702 }
703 }
704}
705
706/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100707 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
708 *
709 * Verifies that specifying an invalid min MAC size for AES key generation returns
710 * UNSUPPORTED_MIN_MAC_LENGTH.
711 */
712TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
713 for (size_t min_mac_len : {88, 136}) {
714 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
715 BlockMode block_mode = BlockMode::GCM;
716 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
717 SCOPED_TRACE(testing::Message()
718 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
719 vector<uint8_t> key_blob;
720 vector<KeyCharacteristics> key_characteristics;
721 auto builder = AuthorizationSetBuilder()
722 .AesEncryptionKey(key_size)
723 .BlockMode(block_mode)
724 .Padding(padding_mode)
725 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
726 .SetDefaultValidity();
727 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
728 GenerateKey(builder, &key_blob, &key_characteristics));
729 }
730 }
731 }
732}
733
734/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000735 * NewKeyGenerationTest.TripleDes
736 *
737 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
738 * have correct characteristics.
739 */
740TEST_P(NewKeyGenerationTest, TripleDes) {
741 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
742 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
743 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
744 SCOPED_TRACE(testing::Message()
745 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
746 vector<uint8_t> key_blob;
747 vector<KeyCharacteristics> key_characteristics;
748 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
749 .TripleDesEncryptionKey(key_size)
750 .BlockMode(block_mode)
751 .Padding(padding_mode)
752 .Authorization(TAG_NO_AUTH_REQUIRED)
753 .SetDefaultValidity(),
754 &key_blob, &key_characteristics));
755
756 EXPECT_GT(key_blob.size(), 0U);
757 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100758 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000759
760 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
761
762 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
763 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
764 << "Key size " << key_size << "missing";
765
766 CheckedDeleteKey(&key_blob);
767 }
768 }
769 }
770}
771
772/*
773 * NewKeyGenerationTest.TripleDesWithAttestation
774 *
775 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
776 * have correct characteristics.
777 *
778 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
779 * put in a certificate) but which isn't an error.
780 */
781TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
782 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
783 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
784 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
785 SCOPED_TRACE(testing::Message()
786 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
787
788 auto challenge = "hello";
789 auto app_id = "foo";
790
791 vector<uint8_t> key_blob;
792 vector<KeyCharacteristics> key_characteristics;
793 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
794 .TripleDesEncryptionKey(key_size)
795 .BlockMode(block_mode)
796 .Padding(padding_mode)
797 .Authorization(TAG_NO_AUTH_REQUIRED)
798 .AttestationChallenge(challenge)
799 .AttestationApplicationId(app_id)
800 .SetDefaultValidity(),
801 &key_blob, &key_characteristics));
802
803 EXPECT_GT(key_blob.size(), 0U);
804 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100805 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000806
807 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
808
809 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
810 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
811 << "Key size " << key_size << "missing";
812
813 CheckedDeleteKey(&key_blob);
814 }
815 }
816 }
817}
818
819/*
820 * NewKeyGenerationTest.TripleDesInvalidSize
821 *
822 * Verifies that specifying an invalid key size for 3-DES key generation returns
823 * UNSUPPORTED_KEY_SIZE.
824 */
825TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
826 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
827 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
828 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
829 SCOPED_TRACE(testing::Message()
830 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
831 vector<uint8_t> key_blob;
832 vector<KeyCharacteristics> key_characteristics;
833 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
834 GenerateKey(AuthorizationSetBuilder()
835 .TripleDesEncryptionKey(key_size)
836 .BlockMode(block_mode)
837 .Padding(padding_mode)
838 .Authorization(TAG_NO_AUTH_REQUIRED)
839 .SetDefaultValidity(),
840 &key_blob, &key_characteristics));
841 }
842 }
843 }
844
845 // Omitting the key size fails.
846 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
847 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
848 SCOPED_TRACE(testing::Message()
849 << "3DES-default-" << block_mode << "-" << padding_mode);
850 vector<uint8_t> key_blob;
851 vector<KeyCharacteristics> key_characteristics;
852 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
853 GenerateKey(AuthorizationSetBuilder()
854 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
855 .BlockMode(block_mode)
856 .Padding(padding_mode)
857 .Authorization(TAG_NO_AUTH_REQUIRED)
858 .SetDefaultValidity(),
859 &key_blob, &key_characteristics));
860 }
861 }
862}
863
864/*
Selene Huang31ab4042020-04-29 04:22:39 -0700865 * NewKeyGenerationTest.Rsa
866 *
867 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
868 * have correct characteristics.
869 */
870TEST_P(NewKeyGenerationTest, Rsa) {
871 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
872 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700873 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700874 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
875 .RsaSigningKey(key_size, 65537)
876 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800877 .Padding(PaddingMode::NONE)
878 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700879 &key_blob, &key_characteristics));
880
881 ASSERT_GT(key_blob.size(), 0U);
882 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100883 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700884
Shawn Willden7f424372021-01-10 18:06:50 -0700885 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700886
887 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
888 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
889 << "Key size " << key_size << "missing";
890 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
891
892 CheckedDeleteKey(&key_blob);
893 }
894}
895
896/*
Qi Wud22ec842020-11-26 13:27:53 +0800897 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700898 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100899 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
900 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700901 */
902TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700903 auto challenge = "hello";
904 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700905
Selene Huang6e46f142021-04-20 19:20:11 -0700906 auto subject = "cert subj 2";
907 vector<uint8_t> subject_der(make_name_from_str(subject));
908
909 uint64_t serial_int = 66;
910 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
911
Selene Huang4f64c222021-04-13 19:54:36 -0700912 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700913 vector<uint8_t> key_blob;
914 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700915 ASSERT_EQ(ErrorCode::OK,
916 GenerateKey(AuthorizationSetBuilder()
917 .RsaSigningKey(key_size, 65537)
918 .Digest(Digest::NONE)
919 .Padding(PaddingMode::NONE)
920 .AttestationChallenge(challenge)
921 .AttestationApplicationId(app_id)
922 .Authorization(TAG_NO_AUTH_REQUIRED)
923 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
924 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
925 .SetDefaultValidity(),
926 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700927
928 ASSERT_GT(key_blob.size(), 0U);
929 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100930 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700931
932 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
933
934 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
935 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
936 << "Key size " << key_size << "missing";
937 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
938
Selene Huang6e46f142021-04-20 19:20:11 -0700939 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700940 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700941 ASSERT_GT(cert_chain_.size(), 0);
942
943 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
944 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
945 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
946 sw_enforced, hw_enforced, SecLevel(),
947 cert_chain_[0].encodedCertificate));
948
949 CheckedDeleteKey(&key_blob);
950 }
951}
952
953/*
David Drysdale4dc01072021-04-01 12:17:35 +0100954 * NewKeyGenerationTest.RsaWithRpkAttestation
955 *
956 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
957 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +0100958 *
959 * This test is disabled because the KeyMint specification does not require that implementations
960 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
961 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +0100962 */
David Drysdale0fce69d2021-04-13 17:22:13 +0100963TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +0100964 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
965 // instance.
966 std::shared_ptr<IRemotelyProvisionedComponent> rp;
967 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
968 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
969
970 // Generate a P-256 keypair to use as an attestation key.
971 MacedPublicKey macedPubKey;
972 std::vector<uint8_t> privateKeyBlob;
973 auto status =
974 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
975 ASSERT_TRUE(status.isOk());
976 vector<uint8_t> coseKeyData;
977 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
978
979 AttestationKey attestation_key;
980 attestation_key.keyBlob = std::move(privateKeyBlob);
981 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
982
983 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
984 auto challenge = "hello";
985 auto app_id = "foo";
986
987 vector<uint8_t> key_blob;
988 vector<KeyCharacteristics> key_characteristics;
989 ASSERT_EQ(ErrorCode::OK,
990 GenerateKey(AuthorizationSetBuilder()
991 .RsaSigningKey(key_size, 65537)
992 .Digest(Digest::NONE)
993 .Padding(PaddingMode::NONE)
994 .AttestationChallenge(challenge)
995 .AttestationApplicationId(app_id)
996 .Authorization(TAG_NO_AUTH_REQUIRED)
997 .SetDefaultValidity(),
998 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
999
1000 ASSERT_GT(key_blob.size(), 0U);
1001 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001002 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001003
1004 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1005
1006 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1007 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1008 << "Key size " << key_size << "missing";
1009 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1010
1011 // Attestation by itself is not valid (last entry is not self-signed).
1012 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1013
1014 // The signature over the attested key should correspond to the P256 public key.
1015 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1016 ASSERT_TRUE(key_cert.get());
1017 EVP_PKEY_Ptr signing_pubkey;
1018 p256_pub_key(coseKeyData, &signing_pubkey);
1019 ASSERT_TRUE(signing_pubkey.get());
1020
1021 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1022 << "Verification of attested certificate failed "
1023 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1024
1025 CheckedDeleteKey(&key_blob);
1026 }
1027}
1028
1029/*
Selene Huang4f64c222021-04-13 19:54:36 -07001030 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1031 *
1032 * Verifies that keymint attestation for RSA encryption keys with challenge and
1033 * app id is also successful.
1034 */
1035TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1036 auto key_size = 2048;
1037 auto challenge = "hello";
1038 auto app_id = "foo";
1039
Selene Huang6e46f142021-04-20 19:20:11 -07001040 auto subject = "subj 2";
1041 vector<uint8_t> subject_der(make_name_from_str(subject));
1042
1043 uint64_t serial_int = 111166;
1044 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1045
Selene Huang4f64c222021-04-13 19:54:36 -07001046 vector<uint8_t> key_blob;
1047 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001048 ASSERT_EQ(ErrorCode::OK,
1049 GenerateKey(AuthorizationSetBuilder()
1050 .RsaEncryptionKey(key_size, 65537)
1051 .Padding(PaddingMode::NONE)
1052 .AttestationChallenge(challenge)
1053 .AttestationApplicationId(app_id)
1054 .Authorization(TAG_NO_AUTH_REQUIRED)
1055 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1056 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1057 .SetDefaultValidity(),
1058 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001059
1060 ASSERT_GT(key_blob.size(), 0U);
1061 AuthorizationSet auths;
1062 for (auto& entry : key_characteristics) {
1063 auths.push_back(AuthorizationSet(entry.authorizations));
1064 }
1065
1066 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1067 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1068
1069 // Verify that App data and ROT are NOT included.
1070 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1071 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1072
1073 // Check that some unexpected tags/values are NOT present.
1074 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1075 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1076
1077 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1078
1079 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1080 ASSERT_TRUE(os_ver);
1081 EXPECT_EQ(*os_ver, os_version());
1082
1083 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1084
1085 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1086 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1087 << "Key size " << key_size << "missing";
1088 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1089
Selene Huang6e46f142021-04-20 19:20:11 -07001090 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001091 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1092 ASSERT_GT(cert_chain_.size(), 0);
1093
1094 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1095 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1096 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1097 sw_enforced, hw_enforced, SecLevel(),
1098 cert_chain_[0].encodedCertificate));
1099
1100 CheckedDeleteKey(&key_blob);
1101}
1102
1103/*
1104 * NewKeyGenerationTest.RsaWithSelfSign
1105 *
1106 * Verifies that attesting to RSA key generation is successful, and returns
1107 * self signed certificate if no challenge is provided. And signing etc
1108 * works as expected.
1109 */
1110TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001111 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1112 vector<uint8_t> subject_der(make_name_from_str(subject));
1113
1114 uint64_t serial_int = 0;
1115 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1116
Selene Huang4f64c222021-04-13 19:54:36 -07001117 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1118 vector<uint8_t> key_blob;
1119 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001120 ASSERT_EQ(ErrorCode::OK,
1121 GenerateKey(AuthorizationSetBuilder()
1122 .RsaSigningKey(key_size, 65537)
1123 .Digest(Digest::NONE)
1124 .Padding(PaddingMode::NONE)
1125 .Authorization(TAG_NO_AUTH_REQUIRED)
1126 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1127 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1128 .SetDefaultValidity(),
1129 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001130
1131 ASSERT_GT(key_blob.size(), 0U);
1132 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001133 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001134
1135 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1136
1137 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1138 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1139 << "Key size " << key_size << "missing";
1140 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1141
Selene Huang6e46f142021-04-20 19:20:11 -07001142 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001143 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1144 ASSERT_EQ(cert_chain_.size(), 1);
1145
1146 CheckedDeleteKey(&key_blob);
1147 }
1148}
1149
1150/*
1151 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1152 *
1153 * Verifies that attesting to RSA checks for missing app ID.
1154 */
1155TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1156 auto challenge = "hello";
1157 vector<uint8_t> key_blob;
1158 vector<KeyCharacteristics> key_characteristics;
1159
1160 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1161 GenerateKey(AuthorizationSetBuilder()
1162 .RsaSigningKey(2048, 65537)
1163 .Digest(Digest::NONE)
1164 .Padding(PaddingMode::NONE)
1165 .AttestationChallenge(challenge)
1166 .Authorization(TAG_NO_AUTH_REQUIRED)
1167 .SetDefaultValidity(),
1168 &key_blob, &key_characteristics));
1169}
1170
1171/*
1172 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1173 *
1174 * Verifies that attesting to RSA ignores app id if challenge is missing.
1175 */
1176TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1177 auto key_size = 2048;
1178 auto app_id = "foo";
1179
Selene Huang6e46f142021-04-20 19:20:11 -07001180 auto subject = "cert subj 2";
1181 vector<uint8_t> subject_der(make_name_from_str(subject));
1182
1183 uint64_t serial_int = 1;
1184 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1185
Selene Huang4f64c222021-04-13 19:54:36 -07001186 vector<uint8_t> key_blob;
1187 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001188 ASSERT_EQ(ErrorCode::OK,
1189 GenerateKey(AuthorizationSetBuilder()
1190 .RsaSigningKey(key_size, 65537)
1191 .Digest(Digest::NONE)
1192 .Padding(PaddingMode::NONE)
1193 .AttestationApplicationId(app_id)
1194 .Authorization(TAG_NO_AUTH_REQUIRED)
1195 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1196 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1197 .SetDefaultValidity(),
1198 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001199
1200 ASSERT_GT(key_blob.size(), 0U);
1201 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001202 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001203
1204 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1205
1206 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1207 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1208 << "Key size " << key_size << "missing";
1209 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1210
Selene Huang6e46f142021-04-20 19:20:11 -07001211 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001212 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1213 ASSERT_EQ(cert_chain_.size(), 1);
1214
1215 CheckedDeleteKey(&key_blob);
1216}
1217
1218/*
Qi Wud22ec842020-11-26 13:27:53 +08001219 * NewKeyGenerationTest.LimitedUsageRsa
1220 *
1221 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1222 * resulting keys have correct characteristics.
1223 */
1224TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1225 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1226 vector<uint8_t> key_blob;
1227 vector<KeyCharacteristics> key_characteristics;
1228 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1229 .RsaSigningKey(key_size, 65537)
1230 .Digest(Digest::NONE)
1231 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001232 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1233 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001234 &key_blob, &key_characteristics));
1235
1236 ASSERT_GT(key_blob.size(), 0U);
1237 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001238 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001239
1240 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1241
1242 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1243 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1244 << "Key size " << key_size << "missing";
1245 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1246
1247 // Check the usage count limit tag appears in the authorizations.
1248 AuthorizationSet auths;
1249 for (auto& entry : key_characteristics) {
1250 auths.push_back(AuthorizationSet(entry.authorizations));
1251 }
1252 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1253 << "key usage count limit " << 1U << " missing";
1254
1255 CheckedDeleteKey(&key_blob);
1256 }
1257}
1258
1259/*
Qi Wubeefae42021-01-28 23:16:37 +08001260 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1261 *
1262 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1263 * resulting keys have correct characteristics and attestation.
1264 */
1265TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001266 auto challenge = "hello";
1267 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001268
Selene Huang6e46f142021-04-20 19:20:11 -07001269 auto subject = "cert subj 2";
1270 vector<uint8_t> subject_der(make_name_from_str(subject));
1271
1272 uint64_t serial_int = 66;
1273 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1274
Selene Huang4f64c222021-04-13 19:54:36 -07001275 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001276 vector<uint8_t> key_blob;
1277 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001278 ASSERT_EQ(ErrorCode::OK,
1279 GenerateKey(AuthorizationSetBuilder()
1280 .RsaSigningKey(key_size, 65537)
1281 .Digest(Digest::NONE)
1282 .Padding(PaddingMode::NONE)
1283 .AttestationChallenge(challenge)
1284 .AttestationApplicationId(app_id)
1285 .Authorization(TAG_NO_AUTH_REQUIRED)
1286 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1287 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1288 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1289 .SetDefaultValidity(),
1290 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001291
1292 ASSERT_GT(key_blob.size(), 0U);
1293 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001294 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001295
1296 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1297
1298 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1299 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1300 << "Key size " << key_size << "missing";
1301 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1302
1303 // Check the usage count limit tag appears in the authorizations.
1304 AuthorizationSet auths;
1305 for (auto& entry : key_characteristics) {
1306 auths.push_back(AuthorizationSet(entry.authorizations));
1307 }
1308 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1309 << "key usage count limit " << 1U << " missing";
1310
1311 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001312 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001313 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001314 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001315
1316 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1317 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1318 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1319 sw_enforced, hw_enforced, SecLevel(),
1320 cert_chain_[0].encodedCertificate));
1321
1322 CheckedDeleteKey(&key_blob);
1323 }
1324}
1325
1326/*
Selene Huang31ab4042020-04-29 04:22:39 -07001327 * NewKeyGenerationTest.NoInvalidRsaSizes
1328 *
1329 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1330 */
1331TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1332 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1333 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001334 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001335 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1336 GenerateKey(AuthorizationSetBuilder()
1337 .RsaSigningKey(key_size, 65537)
1338 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001339 .Padding(PaddingMode::NONE)
1340 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001341 &key_blob, &key_characteristics));
1342 }
1343}
1344
1345/*
1346 * NewKeyGenerationTest.RsaNoDefaultSize
1347 *
1348 * Verifies that failing to specify a key size for RSA key generation returns
1349 * UNSUPPORTED_KEY_SIZE.
1350 */
1351TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1352 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1353 GenerateKey(AuthorizationSetBuilder()
1354 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1355 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001356 .SigningKey()
1357 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001358}
1359
1360/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001361 * NewKeyGenerationTest.RsaMissingParams
1362 *
1363 * Verifies that omitting optional tags works.
1364 */
1365TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1366 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1367 ASSERT_EQ(ErrorCode::OK,
1368 GenerateKey(
1369 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1370 CheckedDeleteKey();
1371 }
1372}
1373
1374/*
Selene Huang31ab4042020-04-29 04:22:39 -07001375 * NewKeyGenerationTest.Ecdsa
1376 *
1377 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1378 * have correct characteristics.
1379 */
1380TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001381 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001382 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001383 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001384 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001385 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001386 .Digest(Digest::NONE)
1387 .SetDefaultValidity(),
1388 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001389 ASSERT_GT(key_blob.size(), 0U);
1390 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001391 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001392
Shawn Willden7f424372021-01-10 18:06:50 -07001393 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001394
1395 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001396 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001397
1398 CheckedDeleteKey(&key_blob);
1399 }
1400}
1401
1402/*
Selene Huang4f64c222021-04-13 19:54:36 -07001403 * NewKeyGenerationTest.EcdsaAttestation
1404 *
1405 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1406 * an attestation will be generated.
1407 */
1408TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1409 auto challenge = "hello";
1410 auto app_id = "foo";
1411
Selene Huang6e46f142021-04-20 19:20:11 -07001412 auto subject = "cert subj 2";
1413 vector<uint8_t> subject_der(make_name_from_str(subject));
1414
1415 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1416 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1417
David Drysdaledf09e542021-06-08 15:46:11 +01001418 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001419 vector<uint8_t> key_blob;
1420 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001421 ASSERT_EQ(ErrorCode::OK,
1422 GenerateKey(AuthorizationSetBuilder()
1423 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001424 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001425 .Digest(Digest::NONE)
1426 .AttestationChallenge(challenge)
1427 .AttestationApplicationId(app_id)
1428 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1429 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1430 .SetDefaultValidity(),
1431 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001432 ASSERT_GT(key_blob.size(), 0U);
1433 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001434 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001435
1436 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1437
1438 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001439 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001440
1441 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1442 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001443 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001444
1445 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1446 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1447 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1448 sw_enforced, hw_enforced, SecLevel(),
1449 cert_chain_[0].encodedCertificate));
1450
1451 CheckedDeleteKey(&key_blob);
1452 }
1453}
1454
1455/*
David Drysdale37af4b32021-05-14 16:46:59 +01001456 * NewKeyGenerationTest.EcdsaAttestationTags
1457 *
1458 * Verifies that creation of an attested ECDSA key includes various tags in the
1459 * attestation extension.
1460 */
1461TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1462 auto challenge = "hello";
1463 auto app_id = "foo";
1464 auto subject = "cert subj 2";
1465 vector<uint8_t> subject_der(make_name_from_str(subject));
1466 uint64_t serial_int = 0x1010;
1467 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1468 const AuthorizationSetBuilder base_builder =
1469 AuthorizationSetBuilder()
1470 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001471 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001472 .Digest(Digest::NONE)
1473 .AttestationChallenge(challenge)
1474 .AttestationApplicationId(app_id)
1475 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1476 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1477 .SetDefaultValidity();
1478
1479 // Various tags that map to fields in the attestation extension ASN.1 schema.
1480 auto extra_tags = AuthorizationSetBuilder()
1481 .Authorization(TAG_ROLLBACK_RESISTANCE)
1482 .Authorization(TAG_EARLY_BOOT_ONLY)
1483 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1484 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1485 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1486 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1487 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1488 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1489 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1490 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1491 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1492 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001493
David Drysdale37af4b32021-05-14 16:46:59 +01001494 for (const KeyParameter& tag : extra_tags) {
1495 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1496 vector<uint8_t> key_blob;
1497 vector<KeyCharacteristics> key_characteristics;
1498 AuthorizationSetBuilder builder = base_builder;
1499 builder.push_back(tag);
1500 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1501 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1502 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1503 continue;
1504 }
Seth Mooreb393b082021-07-12 14:18:28 -07001505 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1506 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001507 continue;
1508 }
1509 ASSERT_EQ(result, ErrorCode::OK);
1510 ASSERT_GT(key_blob.size(), 0U);
1511
1512 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1513 ASSERT_GT(cert_chain_.size(), 0);
1514 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1515
1516 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1517 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001518 // Some tags are optional, so don't require them to be in the enforcements.
1519 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001520 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1521 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1522 }
1523
1524 // Verifying the attestation record will check for the specific tag because
1525 // it's included in the authorizations.
1526 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1527 SecLevel(), cert_chain_[0].encodedCertificate));
1528
1529 CheckedDeleteKey(&key_blob);
1530 }
1531
David Drysdalec53b7d92021-10-11 12:35:58 +01001532 // Collection of invalid attestation ID tags.
1533 auto invalid_tags =
1534 AuthorizationSetBuilder()
1535 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1536 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1537 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1538 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1539 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1540 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1541 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1542 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001543 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001544 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001545 vector<uint8_t> key_blob;
1546 vector<KeyCharacteristics> key_characteristics;
1547 AuthorizationSetBuilder builder =
1548 AuthorizationSetBuilder()
1549 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001550 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001551 .Digest(Digest::NONE)
1552 .AttestationChallenge(challenge)
1553 .AttestationApplicationId(app_id)
1554 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1555 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1556 .SetDefaultValidity();
1557 builder.push_back(tag);
1558 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1559 GenerateKey(builder, &key_blob, &key_characteristics));
1560 }
1561}
1562
1563/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001564 * NewKeyGenerationTest.EcdsaAttestationIdTags
1565 *
1566 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1567 * attestation extension.
1568 */
1569TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
1570 auto challenge = "hello";
1571 auto app_id = "foo";
1572 auto subject = "cert subj 2";
1573 vector<uint8_t> subject_der(make_name_from_str(subject));
1574 uint64_t serial_int = 0x1010;
1575 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1576 const AuthorizationSetBuilder base_builder =
1577 AuthorizationSetBuilder()
1578 .Authorization(TAG_NO_AUTH_REQUIRED)
1579 .EcdsaSigningKey(EcCurve::P_256)
1580 .Digest(Digest::NONE)
1581 .AttestationChallenge(challenge)
1582 .AttestationApplicationId(app_id)
1583 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1584 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1585 .SetDefaultValidity();
1586
1587 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1588 auto extra_tags = AuthorizationSetBuilder();
1589 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1590 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1591 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1592 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1593 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1594 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1595
1596 for (const KeyParameter& tag : extra_tags) {
1597 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1598 vector<uint8_t> key_blob;
1599 vector<KeyCharacteristics> key_characteristics;
1600 AuthorizationSetBuilder builder = base_builder;
1601 builder.push_back(tag);
1602 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1603 if (result == ErrorCode::CANNOT_ATTEST_IDS) {
1604 // Device ID attestation is optional; KeyMint may not support it at all.
1605 continue;
1606 }
1607 ASSERT_EQ(result, ErrorCode::OK);
1608 ASSERT_GT(key_blob.size(), 0U);
1609
1610 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1611 ASSERT_GT(cert_chain_.size(), 0);
1612 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1613
1614 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1615 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1616
1617 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
1618 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
1619 // attestation extension should contain them, so make sure the extra tag is added.
1620 hw_enforced.push_back(tag);
1621
1622 // Verifying the attestation record will check for the specific tag because
1623 // it's included in the authorizations.
1624 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1625 SecLevel(), cert_chain_[0].encodedCertificate));
1626
1627 CheckedDeleteKey(&key_blob);
1628 }
1629}
1630
1631/*
David Drysdale565ccc72021-10-11 12:49:50 +01001632 * NewKeyGenerationTest.EcdsaAttestationUniqueId
1633 *
1634 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
1635 */
1636TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
1637 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00001638 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01001639 auto challenge = "hello";
1640 auto subject = "cert subj 2";
1641 vector<uint8_t> subject_der(make_name_from_str(subject));
1642 uint64_t serial_int = 0x1010;
1643 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00001644 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01001645 AuthorizationSetBuilder()
1646 .Authorization(TAG_NO_AUTH_REQUIRED)
1647 .Authorization(TAG_INCLUDE_UNIQUE_ID)
1648 .EcdsaSigningKey(EcCurve::P_256)
1649 .Digest(Digest::NONE)
1650 .AttestationChallenge(challenge)
1651 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1652 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1653 .AttestationApplicationId(app_id)
1654 .Authorization(TAG_CREATION_DATETIME, datetime)
1655 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00001656 if (reset) {
1657 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
1658 }
David Drysdale565ccc72021-10-11 12:49:50 +01001659
1660 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
1661 ASSERT_GT(key_blob_.size(), 0U);
1662
1663 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1664 ASSERT_GT(cert_chain_.size(), 0);
1665 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1666
1667 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
1668 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
1669
1670 // Check that the unique ID field in the extension is non-empty.
1671 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1672 SecLevel(), cert_chain_[0].encodedCertificate,
1673 unique_id));
1674 EXPECT_GT(unique_id->size(), 0);
1675 CheckedDeleteKey();
1676 };
1677
1678 // Generate unique ID
1679 auto app_id = "foo";
1680 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
1681 vector<uint8_t> unique_id;
1682 get_unique_id(app_id, cert_date, &unique_id);
1683
1684 // Generating a new key with the same parameters should give the same unique ID.
1685 vector<uint8_t> unique_id2;
1686 get_unique_id(app_id, cert_date, &unique_id2);
1687 EXPECT_EQ(unique_id, unique_id2);
1688
1689 // Generating a new key with a slightly different date should give the same unique ID.
1690 uint64_t rounded_date = cert_date / 2592000000LLU;
1691 uint64_t min_date = rounded_date * 2592000000LLU;
1692 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
1693
1694 vector<uint8_t> unique_id3;
1695 get_unique_id(app_id, min_date, &unique_id3);
1696 EXPECT_EQ(unique_id, unique_id3);
1697
1698 vector<uint8_t> unique_id4;
1699 get_unique_id(app_id, max_date, &unique_id4);
1700 EXPECT_EQ(unique_id, unique_id4);
1701
1702 // A different attestation application ID should yield a different unique ID.
1703 auto app_id2 = "different_foo";
1704 vector<uint8_t> unique_id5;
1705 get_unique_id(app_id2, cert_date, &unique_id5);
1706 EXPECT_NE(unique_id, unique_id5);
1707
1708 // A radically different date should yield a different unique ID.
1709 vector<uint8_t> unique_id6;
1710 get_unique_id(app_id, 1611621648000, &unique_id6);
1711 EXPECT_NE(unique_id, unique_id6);
1712
1713 vector<uint8_t> unique_id7;
1714 get_unique_id(app_id, max_date + 1, &unique_id7);
1715 EXPECT_NE(unique_id, unique_id7);
1716
1717 vector<uint8_t> unique_id8;
1718 get_unique_id(app_id, min_date - 1, &unique_id8);
1719 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00001720
1721 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
1722 vector<uint8_t> unique_id9;
1723 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
1724 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01001725}
1726
1727/*
David Drysdale37af4b32021-05-14 16:46:59 +01001728 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1729 *
1730 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1731 */
1732TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1733 auto challenge = "hello";
1734 auto attest_app_id = "foo";
1735 auto subject = "cert subj 2";
1736 vector<uint8_t> subject_der(make_name_from_str(subject));
1737 uint64_t serial_int = 0x1010;
1738 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1739
1740 // Earlier versions of the attestation extension schema included a slot:
1741 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1742 // This should never have been included, and should never be filled in.
1743 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1744 // to confirm that this field never makes it into the attestation extension.
1745 vector<uint8_t> key_blob;
1746 vector<KeyCharacteristics> key_characteristics;
1747 auto result = GenerateKey(AuthorizationSetBuilder()
1748 .Authorization(TAG_NO_AUTH_REQUIRED)
1749 .EcdsaSigningKey(EcCurve::P_256)
1750 .Digest(Digest::NONE)
1751 .AttestationChallenge(challenge)
1752 .AttestationApplicationId(attest_app_id)
1753 .Authorization(TAG_APPLICATION_ID, "client_id")
1754 .Authorization(TAG_APPLICATION_DATA, "appdata")
1755 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1756 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1757 .SetDefaultValidity(),
1758 &key_blob, &key_characteristics);
1759 ASSERT_EQ(result, ErrorCode::OK);
1760 ASSERT_GT(key_blob.size(), 0U);
1761
1762 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1763 ASSERT_GT(cert_chain_.size(), 0);
1764 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1765
1766 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1767 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1768 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1769 SecLevel(), cert_chain_[0].encodedCertificate));
1770
1771 // Check that the app id is not in the cert.
1772 string app_id = "clientid";
1773 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1774 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1775 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1776 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1777 cert_chain_[0].encodedCertificate.end());
1778
1779 CheckedDeleteKey(&key_blob);
1780}
1781
1782/*
Selene Huang4f64c222021-04-13 19:54:36 -07001783 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1784 *
1785 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1786 * the key will generate a self signed attestation.
1787 */
1788TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001789 auto subject = "cert subj 2";
1790 vector<uint8_t> subject_der(make_name_from_str(subject));
1791
1792 uint64_t serial_int = 0x123456FFF1234;
1793 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1794
David Drysdaledf09e542021-06-08 15:46:11 +01001795 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001796 vector<uint8_t> key_blob;
1797 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001798 ASSERT_EQ(ErrorCode::OK,
1799 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001800 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001801 .Digest(Digest::NONE)
1802 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1803 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1804 .SetDefaultValidity(),
1805 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001806 ASSERT_GT(key_blob.size(), 0U);
1807 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001808 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001809
1810 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1811
1812 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001813 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001814
1815 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001816 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001817 ASSERT_EQ(cert_chain_.size(), 1);
1818
1819 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1820 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1821
1822 CheckedDeleteKey(&key_blob);
1823 }
1824}
1825
1826/*
1827 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1828 *
1829 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1830 * app id must also be provided or else it will fail.
1831 */
1832TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1833 auto challenge = "hello";
1834 vector<uint8_t> key_blob;
1835 vector<KeyCharacteristics> key_characteristics;
1836
1837 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1838 GenerateKey(AuthorizationSetBuilder()
1839 .EcdsaSigningKey(EcCurve::P_256)
1840 .Digest(Digest::NONE)
1841 .AttestationChallenge(challenge)
1842 .SetDefaultValidity(),
1843 &key_blob, &key_characteristics));
1844}
1845
1846/*
1847 * NewKeyGenerationTest.EcdsaIgnoreAppId
1848 *
1849 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1850 * any appid will be ignored, and keymint will generate a self sign certificate.
1851 */
1852TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1853 auto app_id = "foo";
1854
David Drysdaledf09e542021-06-08 15:46:11 +01001855 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001856 vector<uint8_t> key_blob;
1857 vector<KeyCharacteristics> key_characteristics;
1858 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001859 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001860 .Digest(Digest::NONE)
1861 .AttestationApplicationId(app_id)
1862 .SetDefaultValidity(),
1863 &key_blob, &key_characteristics));
1864
1865 ASSERT_GT(key_blob.size(), 0U);
1866 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001867 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001868
1869 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1870
1871 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001872 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001873
1874 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1875 ASSERT_EQ(cert_chain_.size(), 1);
1876
1877 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1878 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1879
1880 CheckedDeleteKey(&key_blob);
1881 }
1882}
1883
1884/*
1885 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1886 *
1887 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1888 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1889 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1890 * to specify how many following bytes will be used to encode the length.
1891 */
1892TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1893 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001894 std::vector<uint32_t> app_id_lengths{143, 258};
1895
1896 for (uint32_t length : app_id_lengths) {
1897 const string app_id(length, 'a');
1898 vector<uint8_t> key_blob;
1899 vector<KeyCharacteristics> key_characteristics;
1900 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1901 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001902 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001903 .Digest(Digest::NONE)
1904 .AttestationChallenge(challenge)
1905 .AttestationApplicationId(app_id)
1906 .SetDefaultValidity(),
1907 &key_blob, &key_characteristics));
1908 ASSERT_GT(key_blob.size(), 0U);
1909 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001910 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001911
1912 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1913
1914 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001915 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001916
1917 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1918 ASSERT_GT(cert_chain_.size(), 0);
1919
1920 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1921 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1922 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1923 sw_enforced, hw_enforced, SecLevel(),
1924 cert_chain_[0].encodedCertificate));
1925
1926 CheckedDeleteKey(&key_blob);
1927 }
1928}
1929
1930/*
Qi Wud22ec842020-11-26 13:27:53 +08001931 * NewKeyGenerationTest.LimitedUsageEcdsa
1932 *
1933 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1934 * resulting keys have correct characteristics.
1935 */
1936TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001937 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001938 vector<uint8_t> key_blob;
1939 vector<KeyCharacteristics> key_characteristics;
1940 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001941 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001942 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001943 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1944 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001945 &key_blob, &key_characteristics));
1946
1947 ASSERT_GT(key_blob.size(), 0U);
1948 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001949 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001950
1951 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1952
1953 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001954 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001955
1956 // Check the usage count limit tag appears in the authorizations.
1957 AuthorizationSet auths;
1958 for (auto& entry : key_characteristics) {
1959 auths.push_back(AuthorizationSet(entry.authorizations));
1960 }
1961 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1962 << "key usage count limit " << 1U << " missing";
1963
1964 CheckedDeleteKey(&key_blob);
1965 }
1966}
1967
1968/*
Selene Huang31ab4042020-04-29 04:22:39 -07001969 * NewKeyGenerationTest.EcdsaDefaultSize
1970 *
David Drysdaledf09e542021-06-08 15:46:11 +01001971 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001972 * UNSUPPORTED_KEY_SIZE.
1973 */
1974TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1975 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1976 GenerateKey(AuthorizationSetBuilder()
1977 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1978 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001979 .Digest(Digest::NONE)
1980 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001981}
1982
1983/*
1984 * NewKeyGenerationTest.EcdsaInvalidSize
1985 *
1986 * Verifies that specifying an invalid key size for EC key generation returns
1987 * UNSUPPORTED_KEY_SIZE.
1988 */
1989TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdaledf09e542021-06-08 15:46:11 +01001990 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001991 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001992 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001993 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001994 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001995 .Digest(Digest::NONE)
1996 .SetDefaultValidity(),
1997 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001998 }
1999
David Drysdaledf09e542021-06-08 15:46:11 +01002000 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2001 GenerateKey(AuthorizationSetBuilder()
2002 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2003 .Authorization(TAG_KEY_SIZE, 190)
2004 .SigningKey()
2005 .Digest(Digest::NONE)
2006 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002007}
2008
2009/*
2010 * NewKeyGenerationTest.EcdsaMismatchKeySize
2011 *
2012 * Verifies that specifying mismatched key size and curve for EC key generation returns
2013 * INVALID_ARGUMENT.
2014 */
2015TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002016 if (SecLevel() == SecurityLevel::STRONGBOX) {
2017 GTEST_SKIP() << "Test not applicable to StrongBox device";
2018 }
Selene Huang31ab4042020-04-29 04:22:39 -07002019
David Drysdaledf09e542021-06-08 15:46:11 +01002020 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002021 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002022 .Authorization(TAG_KEY_SIZE, 224)
2023 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002024 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002025 .Digest(Digest::NONE)
2026 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002027 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002028}
2029
2030/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002031 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002032 *
2033 * Verifies that keymint does not support any curve designated as unsupported.
2034 */
2035TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2036 Digest digest;
2037 if (SecLevel() == SecurityLevel::STRONGBOX) {
2038 digest = Digest::SHA_2_256;
2039 } else {
2040 digest = Digest::SHA_2_512;
2041 }
2042 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002043 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2044 .EcdsaSigningKey(curve)
2045 .Digest(digest)
2046 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002047 << "Failed to generate key on curve: " << curve;
2048 CheckedDeleteKey();
2049 }
2050}
2051
2052/*
2053 * NewKeyGenerationTest.Hmac
2054 *
2055 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2056 * characteristics.
2057 */
2058TEST_P(NewKeyGenerationTest, Hmac) {
2059 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2060 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002061 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002062 constexpr size_t key_size = 128;
2063 ASSERT_EQ(ErrorCode::OK,
2064 GenerateKey(
2065 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2066 TAG_MIN_MAC_LENGTH, 128),
2067 &key_blob, &key_characteristics));
2068
2069 ASSERT_GT(key_blob.size(), 0U);
2070 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002071 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002072
Shawn Willden7f424372021-01-10 18:06:50 -07002073 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2074 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2075 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2076 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002077
2078 CheckedDeleteKey(&key_blob);
2079 }
2080}
2081
2082/*
Selene Huang4f64c222021-04-13 19:54:36 -07002083 * NewKeyGenerationTest.HmacNoAttestation
2084 *
2085 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2086 * and app id are provided.
2087 */
2088TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2089 auto challenge = "hello";
2090 auto app_id = "foo";
2091
2092 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2093 vector<uint8_t> key_blob;
2094 vector<KeyCharacteristics> key_characteristics;
2095 constexpr size_t key_size = 128;
2096 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2097 .HmacKey(key_size)
2098 .Digest(digest)
2099 .AttestationChallenge(challenge)
2100 .AttestationApplicationId(app_id)
2101 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2102 &key_blob, &key_characteristics));
2103
2104 ASSERT_GT(key_blob.size(), 0U);
2105 ASSERT_EQ(cert_chain_.size(), 0);
2106 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002107 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002108
2109 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2110 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2111 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2112 << "Key size " << key_size << "missing";
2113
2114 CheckedDeleteKey(&key_blob);
2115 }
2116}
2117
2118/*
Qi Wud22ec842020-11-26 13:27:53 +08002119 * NewKeyGenerationTest.LimitedUsageHmac
2120 *
2121 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2122 * resulting keys have correct characteristics.
2123 */
2124TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2125 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2126 vector<uint8_t> key_blob;
2127 vector<KeyCharacteristics> key_characteristics;
2128 constexpr size_t key_size = 128;
2129 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2130 .HmacKey(key_size)
2131 .Digest(digest)
2132 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2133 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2134 &key_blob, &key_characteristics));
2135
2136 ASSERT_GT(key_blob.size(), 0U);
2137 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002138 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002139
2140 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2141 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2142 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2143 << "Key size " << key_size << "missing";
2144
2145 // Check the usage count limit tag appears in the authorizations.
2146 AuthorizationSet auths;
2147 for (auto& entry : key_characteristics) {
2148 auths.push_back(AuthorizationSet(entry.authorizations));
2149 }
2150 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2151 << "key usage count limit " << 1U << " missing";
2152
2153 CheckedDeleteKey(&key_blob);
2154 }
2155}
2156
2157/*
Selene Huang31ab4042020-04-29 04:22:39 -07002158 * NewKeyGenerationTest.HmacCheckKeySizes
2159 *
2160 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2161 */
2162TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2163 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2164 if (key_size < 64 || key_size % 8 != 0) {
2165 // To keep this test from being very slow, we only test a random fraction of
2166 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2167 // them, we expect to run ~40 of them in each run.
2168 if (key_size % 8 == 0 || random() % 10 == 0) {
2169 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2170 GenerateKey(AuthorizationSetBuilder()
2171 .HmacKey(key_size)
2172 .Digest(Digest::SHA_2_256)
2173 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2174 << "HMAC key size " << key_size << " invalid";
2175 }
2176 } else {
2177 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2178 .HmacKey(key_size)
2179 .Digest(Digest::SHA_2_256)
2180 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2181 << "Failed to generate HMAC key of size " << key_size;
2182 CheckedDeleteKey();
2183 }
2184 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002185 if (SecLevel() == SecurityLevel::STRONGBOX) {
2186 // STRONGBOX devices must not support keys larger than 512 bits.
2187 size_t key_size = 520;
2188 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2189 GenerateKey(AuthorizationSetBuilder()
2190 .HmacKey(key_size)
2191 .Digest(Digest::SHA_2_256)
2192 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2193 << "HMAC key size " << key_size << " unexpectedly valid";
2194 }
Selene Huang31ab4042020-04-29 04:22:39 -07002195}
2196
2197/*
2198 * NewKeyGenerationTest.HmacCheckMinMacLengths
2199 *
2200 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2201 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2202 * specific MAC length that failed, so reproducing a failed run will be easy.
2203 */
2204TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2205 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2206 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2207 // To keep this test from being very long, we only test a random fraction of
2208 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2209 // we expect to run ~17 of them in each run.
2210 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2211 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2212 GenerateKey(AuthorizationSetBuilder()
2213 .HmacKey(128)
2214 .Digest(Digest::SHA_2_256)
2215 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2216 << "HMAC min mac length " << min_mac_length << " invalid.";
2217 }
2218 } else {
2219 EXPECT_EQ(ErrorCode::OK,
2220 GenerateKey(AuthorizationSetBuilder()
2221 .HmacKey(128)
2222 .Digest(Digest::SHA_2_256)
2223 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2224 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2225 CheckedDeleteKey();
2226 }
2227 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002228
2229 // Minimum MAC length must be no more than 512 bits.
2230 size_t min_mac_length = 520;
2231 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2232 GenerateKey(AuthorizationSetBuilder()
2233 .HmacKey(128)
2234 .Digest(Digest::SHA_2_256)
2235 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2236 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002237}
2238
2239/*
2240 * NewKeyGenerationTest.HmacMultipleDigests
2241 *
2242 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2243 */
2244TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002245 if (SecLevel() == SecurityLevel::STRONGBOX) {
2246 GTEST_SKIP() << "Test not applicable to StrongBox device";
2247 }
Selene Huang31ab4042020-04-29 04:22:39 -07002248
2249 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2250 GenerateKey(AuthorizationSetBuilder()
2251 .HmacKey(128)
2252 .Digest(Digest::SHA1)
2253 .Digest(Digest::SHA_2_256)
2254 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2255}
2256
2257/*
2258 * NewKeyGenerationTest.HmacDigestNone
2259 *
2260 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2261 */
2262TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2263 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2264 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2265 128)));
2266
2267 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2268 GenerateKey(AuthorizationSetBuilder()
2269 .HmacKey(128)
2270 .Digest(Digest::NONE)
2271 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2272}
2273
Selene Huang4f64c222021-04-13 19:54:36 -07002274/*
2275 * NewKeyGenerationTest.AesNoAttestation
2276 *
2277 * Verifies that attestation parameters to AES keys are ignored and generateKey
2278 * will succeed.
2279 */
2280TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2281 auto challenge = "hello";
2282 auto app_id = "foo";
2283
2284 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2285 .Authorization(TAG_NO_AUTH_REQUIRED)
2286 .AesEncryptionKey(128)
2287 .EcbMode()
2288 .Padding(PaddingMode::PKCS7)
2289 .AttestationChallenge(challenge)
2290 .AttestationApplicationId(app_id)));
2291
2292 ASSERT_EQ(cert_chain_.size(), 0);
2293}
2294
2295/*
2296 * NewKeyGenerationTest.TripleDesNoAttestation
2297 *
2298 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2299 * will be successful. No attestation should be generated.
2300 */
2301TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2302 auto challenge = "hello";
2303 auto app_id = "foo";
2304
2305 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2306 .TripleDesEncryptionKey(168)
2307 .BlockMode(BlockMode::ECB)
2308 .Authorization(TAG_NO_AUTH_REQUIRED)
2309 .Padding(PaddingMode::NONE)
2310 .AttestationChallenge(challenge)
2311 .AttestationApplicationId(app_id)));
2312 ASSERT_EQ(cert_chain_.size(), 0);
2313}
2314
Selene Huang31ab4042020-04-29 04:22:39 -07002315INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2316
2317typedef KeyMintAidlTestBase SigningOperationsTest;
2318
2319/*
2320 * SigningOperationsTest.RsaSuccess
2321 *
2322 * Verifies that raw RSA signature operations succeed.
2323 */
2324TEST_P(SigningOperationsTest, RsaSuccess) {
2325 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2326 .RsaSigningKey(2048, 65537)
2327 .Digest(Digest::NONE)
2328 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002329 .Authorization(TAG_NO_AUTH_REQUIRED)
2330 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002331 string message = "12345678901234567890123456789012";
2332 string signature = SignMessage(
2333 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002334 LocalVerifyMessage(message, signature,
2335 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2336}
2337
2338/*
2339 * SigningOperationsTest.RsaAllPaddingsAndDigests
2340 *
2341 * Verifies RSA signature/verification for all padding modes and digests.
2342 */
2343TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2344 auto authorizations = AuthorizationSetBuilder()
2345 .Authorization(TAG_NO_AUTH_REQUIRED)
2346 .RsaSigningKey(2048, 65537)
2347 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2348 .Padding(PaddingMode::NONE)
2349 .Padding(PaddingMode::RSA_PSS)
2350 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2351 .SetDefaultValidity();
2352
2353 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2354
2355 string message(128, 'a');
2356 string corrupt_message(message);
2357 ++corrupt_message[corrupt_message.size() / 2];
2358
2359 for (auto padding :
2360 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2361 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2362 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2363 // Digesting only makes sense with padding.
2364 continue;
2365 }
2366
2367 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2368 // PSS requires digesting.
2369 continue;
2370 }
2371
2372 string signature =
2373 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2374 LocalVerifyMessage(message, signature,
2375 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2376 }
2377 }
Selene Huang31ab4042020-04-29 04:22:39 -07002378}
2379
2380/*
2381 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2382 *
Shawn Willden7f424372021-01-10 18:06:50 -07002383 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002384 */
2385TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2386 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2387 .Authorization(TAG_NO_AUTH_REQUIRED)
2388 .RsaSigningKey(2048, 65537)
2389 .Digest(Digest::NONE)
2390 .Padding(PaddingMode::NONE)
2391 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002392 .Authorization(TAG_APPLICATION_DATA, "appdata")
2393 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002394
2395 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2396
Selene Huang31ab4042020-04-29 04:22:39 -07002397 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2398 Begin(KeyPurpose::SIGN,
2399 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2400 AbortIfNeeded();
2401 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2402 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2403 .Digest(Digest::NONE)
2404 .Padding(PaddingMode::NONE)
2405 .Authorization(TAG_APPLICATION_ID, "clientid")));
2406 AbortIfNeeded();
2407 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2408 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2409 .Digest(Digest::NONE)
2410 .Padding(PaddingMode::NONE)
2411 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2412 AbortIfNeeded();
2413 EXPECT_EQ(ErrorCode::OK,
2414 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2415 .Digest(Digest::NONE)
2416 .Padding(PaddingMode::NONE)
2417 .Authorization(TAG_APPLICATION_DATA, "appdata")
2418 .Authorization(TAG_APPLICATION_ID, "clientid")));
2419 AbortIfNeeded();
2420}
2421
2422/*
2423 * SigningOperationsTest.RsaPssSha256Success
2424 *
2425 * Verifies that RSA-PSS signature operations succeed.
2426 */
2427TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2428 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2429 .RsaSigningKey(2048, 65537)
2430 .Digest(Digest::SHA_2_256)
2431 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002432 .Authorization(TAG_NO_AUTH_REQUIRED)
2433 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002434 // Use large message, which won't work without digesting.
2435 string message(1024, 'a');
2436 string signature = SignMessage(
2437 message,
2438 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2439}
2440
2441/*
2442 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2443 *
2444 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2445 * supports only unpadded operations.
2446 */
2447TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2448 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2449 .RsaSigningKey(2048, 65537)
2450 .Digest(Digest::NONE)
2451 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002452 .Padding(PaddingMode::NONE)
2453 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002454 string message = "12345678901234567890123456789012";
2455 string signature;
2456
2457 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2458 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2459 .Digest(Digest::NONE)
2460 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2461}
2462
2463/*
2464 * SigningOperationsTest.NoUserConfirmation
2465 *
2466 * Verifies that keymint rejects signing operations for keys with
2467 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2468 * presented.
2469 */
2470TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002471 if (SecLevel() == SecurityLevel::STRONGBOX) {
2472 GTEST_SKIP() << "Test not applicable to StrongBox device";
2473 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002474 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2475 .RsaSigningKey(1024, 65537)
2476 .Digest(Digest::NONE)
2477 .Padding(PaddingMode::NONE)
2478 .Authorization(TAG_NO_AUTH_REQUIRED)
2479 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2480 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002481
2482 const string message = "12345678901234567890123456789012";
2483 EXPECT_EQ(ErrorCode::OK,
2484 Begin(KeyPurpose::SIGN,
2485 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2486 string signature;
2487 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2488}
2489
2490/*
2491 * SigningOperationsTest.RsaPkcs1Sha256Success
2492 *
2493 * Verifies that digested RSA-PKCS1 signature operations succeed.
2494 */
2495TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2496 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2497 .RsaSigningKey(2048, 65537)
2498 .Digest(Digest::SHA_2_256)
2499 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002500 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2501 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002502 string message(1024, 'a');
2503 string signature = SignMessage(message, AuthorizationSetBuilder()
2504 .Digest(Digest::SHA_2_256)
2505 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2506}
2507
2508/*
2509 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2510 *
2511 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2512 */
2513TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2514 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2515 .RsaSigningKey(2048, 65537)
2516 .Digest(Digest::NONE)
2517 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002518 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2519 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002520 string message(53, 'a');
2521 string signature = SignMessage(message, AuthorizationSetBuilder()
2522 .Digest(Digest::NONE)
2523 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2524}
2525
2526/*
2527 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2528 *
2529 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2530 * given a too-long message.
2531 */
2532TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2533 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2534 .RsaSigningKey(2048, 65537)
2535 .Digest(Digest::NONE)
2536 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002537 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2538 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002539 string message(257, 'a');
2540
2541 EXPECT_EQ(ErrorCode::OK,
2542 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2543 .Digest(Digest::NONE)
2544 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2545 string signature;
2546 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2547}
2548
2549/*
2550 * SigningOperationsTest.RsaPssSha512TooSmallKey
2551 *
2552 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2553 * used with a key that is too small for the message.
2554 *
2555 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2556 * keymint specification requires that salt_size == digest_size, so the message will be
2557 * digest_size * 2 +
2558 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2559 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2560 * for a 1024-bit key.
2561 */
2562TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01002563 if (SecLevel() == SecurityLevel::STRONGBOX) {
2564 GTEST_SKIP() << "Test not applicable to StrongBox device";
2565 }
Selene Huang31ab4042020-04-29 04:22:39 -07002566 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2567 .RsaSigningKey(1024, 65537)
2568 .Digest(Digest::SHA_2_512)
2569 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002570 .Padding(PaddingMode::RSA_PSS)
2571 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002572 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2573 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2574 .Digest(Digest::SHA_2_512)
2575 .Padding(PaddingMode::RSA_PSS)));
2576}
2577
2578/*
2579 * SigningOperationsTest.RsaNoPaddingTooLong
2580 *
2581 * Verifies that raw RSA signature operations fail with the correct error code when
2582 * given a too-long message.
2583 */
2584TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2585 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2586 .RsaSigningKey(2048, 65537)
2587 .Digest(Digest::NONE)
2588 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002589 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2590 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002591 // One byte too long
2592 string message(2048 / 8 + 1, 'a');
2593 ASSERT_EQ(ErrorCode::OK,
2594 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2595 .Digest(Digest::NONE)
2596 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2597 string result;
2598 ErrorCode finish_error_code = Finish(message, &result);
2599 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2600 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2601
2602 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2603 message = string(128 * 1024, 'a');
2604 ASSERT_EQ(ErrorCode::OK,
2605 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2606 .Digest(Digest::NONE)
2607 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2608 finish_error_code = Finish(message, &result);
2609 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2610 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2611}
2612
2613/*
2614 * SigningOperationsTest.RsaAbort
2615 *
2616 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2617 * test, but the behavior should be algorithm and purpose-independent.
2618 */
2619TEST_P(SigningOperationsTest, RsaAbort) {
2620 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2621 .RsaSigningKey(2048, 65537)
2622 .Digest(Digest::NONE)
2623 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002624 .Padding(PaddingMode::NONE)
2625 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002626
2627 ASSERT_EQ(ErrorCode::OK,
2628 Begin(KeyPurpose::SIGN,
2629 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2630 EXPECT_EQ(ErrorCode::OK, Abort());
2631
2632 // Another abort should fail
2633 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2634
2635 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002636 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002637}
2638
2639/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002640 * SigningOperationsTest.RsaNonUniqueParams
2641 *
2642 * Verifies that an operation with multiple padding modes is rejected.
2643 */
2644TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2645 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2646 .RsaSigningKey(2048, 65537)
2647 .Digest(Digest::NONE)
2648 .Digest(Digest::SHA1)
2649 .Authorization(TAG_NO_AUTH_REQUIRED)
2650 .Padding(PaddingMode::NONE)
2651 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2652 .SetDefaultValidity()));
2653
2654 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2655 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2656 .Digest(Digest::NONE)
2657 .Padding(PaddingMode::NONE)
2658 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2659
Tommy Chiuc93c4392021-05-11 18:36:50 +08002660 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2661 .Digest(Digest::NONE)
2662 .Digest(Digest::SHA1)
2663 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2664 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002665
2666 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2667 Begin(KeyPurpose::SIGN,
2668 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2669}
2670
2671/*
Selene Huang31ab4042020-04-29 04:22:39 -07002672 * SigningOperationsTest.RsaUnsupportedPadding
2673 *
2674 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2675 * with a padding mode inappropriate for RSA.
2676 */
2677TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2678 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2679 .RsaSigningKey(2048, 65537)
2680 .Authorization(TAG_NO_AUTH_REQUIRED)
2681 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002682 .Padding(PaddingMode::PKCS7)
2683 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002684 ASSERT_EQ(
2685 ErrorCode::UNSUPPORTED_PADDING_MODE,
2686 Begin(KeyPurpose::SIGN,
2687 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002688 CheckedDeleteKey();
2689
2690 ASSERT_EQ(ErrorCode::OK,
2691 GenerateKey(
2692 AuthorizationSetBuilder()
2693 .RsaSigningKey(2048, 65537)
2694 .Authorization(TAG_NO_AUTH_REQUIRED)
2695 .Digest(Digest::SHA_2_256 /* supported digest */)
2696 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2697 .SetDefaultValidity()));
2698 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2699 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2700 .Digest(Digest::SHA_2_256)
2701 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002702}
2703
2704/*
2705 * SigningOperationsTest.RsaPssNoDigest
2706 *
2707 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2708 */
2709TEST_P(SigningOperationsTest, RsaNoDigest) {
2710 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2711 .RsaSigningKey(2048, 65537)
2712 .Authorization(TAG_NO_AUTH_REQUIRED)
2713 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002714 .Padding(PaddingMode::RSA_PSS)
2715 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002716 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2717 Begin(KeyPurpose::SIGN,
2718 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2719
2720 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2721 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2722}
2723
2724/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002725 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002726 *
2727 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2728 * supported in some cases (as validated in other tests), but a mode must be specified.
2729 */
2730TEST_P(SigningOperationsTest, RsaNoPadding) {
2731 // Padding must be specified
2732 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2733 .RsaKey(2048, 65537)
2734 .Authorization(TAG_NO_AUTH_REQUIRED)
2735 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002736 .Digest(Digest::NONE)
2737 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002738 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2739 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2740}
2741
2742/*
2743 * SigningOperationsTest.RsaShortMessage
2744 *
2745 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2746 */
2747TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2748 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2749 .Authorization(TAG_NO_AUTH_REQUIRED)
2750 .RsaSigningKey(2048, 65537)
2751 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002752 .Padding(PaddingMode::NONE)
2753 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002754
2755 // Barely shorter
2756 string message(2048 / 8 - 1, 'a');
2757 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2758
2759 // Much shorter
2760 message = "a";
2761 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2762}
2763
2764/*
2765 * SigningOperationsTest.RsaSignWithEncryptionKey
2766 *
2767 * Verifies that RSA encryption keys cannot be used to sign.
2768 */
2769TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2770 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2771 .Authorization(TAG_NO_AUTH_REQUIRED)
2772 .RsaEncryptionKey(2048, 65537)
2773 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002774 .Padding(PaddingMode::NONE)
2775 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002776 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2777 Begin(KeyPurpose::SIGN,
2778 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2779}
2780
2781/*
2782 * SigningOperationsTest.RsaSignTooLargeMessage
2783 *
2784 * Verifies that attempting a raw signature of a message which is the same length as the key,
2785 * but numerically larger than the public modulus, fails with the correct error.
2786 */
2787TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2788 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2789 .Authorization(TAG_NO_AUTH_REQUIRED)
2790 .RsaSigningKey(2048, 65537)
2791 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002792 .Padding(PaddingMode::NONE)
2793 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002794
2795 // Largest possible message will always be larger than the public modulus.
2796 string message(2048 / 8, static_cast<char>(0xff));
2797 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2798 .Authorization(TAG_NO_AUTH_REQUIRED)
2799 .Digest(Digest::NONE)
2800 .Padding(PaddingMode::NONE)));
2801 string signature;
2802 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2803}
2804
2805/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01002806 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2807 *
2808 * Verifies ECDSA signature/verification for all digests and curves.
2809 */
2810TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2811 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2812
2813 string message = "1234567890";
2814 string corrupt_message = "2234567890";
2815 for (auto curve : ValidCurves()) {
2816 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2817 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2818 .Authorization(TAG_NO_AUTH_REQUIRED)
2819 .EcdsaSigningKey(curve)
2820 .Digest(digests)
2821 .SetDefaultValidity());
2822 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2823 if (error != ErrorCode::OK) {
2824 continue;
2825 }
2826
2827 for (auto digest : digests) {
2828 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2829 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2830 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2831 }
2832
2833 auto rc = DeleteKey();
2834 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2835 }
2836}
2837
2838/*
Selene Huang31ab4042020-04-29 04:22:39 -07002839 * SigningOperationsTest.EcdsaAllCurves
2840 *
2841 * Verifies that ECDSA operations succeed with all possible curves.
2842 */
2843TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2844 for (auto curve : ValidCurves()) {
2845 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2846 .Authorization(TAG_NO_AUTH_REQUIRED)
2847 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002848 .Digest(Digest::SHA_2_256)
2849 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002850 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2851 if (error != ErrorCode::OK) continue;
2852
2853 string message(1024, 'a');
2854 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2855 CheckedDeleteKey();
2856 }
2857}
2858
2859/*
2860 * SigningOperationsTest.EcdsaNoDigestHugeData
2861 *
2862 * Verifies that ECDSA operations support very large messages, even without digesting. This
2863 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2864 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2865 * the framework.
2866 */
2867TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2868 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2869 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002870 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002871 .Digest(Digest::NONE)
2872 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002873 string message(1 * 1024, 'a');
2874 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2875}
2876
2877/*
2878 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2879 *
2880 * Verifies that using an EC key requires the correct app ID/data.
2881 */
2882TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2883 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2884 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002885 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002886 .Digest(Digest::NONE)
2887 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002888 .Authorization(TAG_APPLICATION_DATA, "appdata")
2889 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002890
2891 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2892
Selene Huang31ab4042020-04-29 04:22:39 -07002893 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2894 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2895 AbortIfNeeded();
2896 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2897 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2898 .Digest(Digest::NONE)
2899 .Authorization(TAG_APPLICATION_ID, "clientid")));
2900 AbortIfNeeded();
2901 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2902 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2903 .Digest(Digest::NONE)
2904 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2905 AbortIfNeeded();
2906 EXPECT_EQ(ErrorCode::OK,
2907 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2908 .Digest(Digest::NONE)
2909 .Authorization(TAG_APPLICATION_DATA, "appdata")
2910 .Authorization(TAG_APPLICATION_ID, "clientid")));
2911 AbortIfNeeded();
2912}
2913
2914/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002915 * SigningOperationsTest.EcdsaIncompatibleDigest
2916 *
2917 * Verifies that using an EC key requires compatible digest.
2918 */
2919TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2920 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2921 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002922 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002923 .Digest(Digest::NONE)
2924 .Digest(Digest::SHA1)
2925 .SetDefaultValidity()));
2926 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2927 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2928 AbortIfNeeded();
2929}
2930
2931/*
Selene Huang31ab4042020-04-29 04:22:39 -07002932 * SigningOperationsTest.AesEcbSign
2933 *
2934 * Verifies that attempts to use AES keys to sign fail in the correct way.
2935 */
2936TEST_P(SigningOperationsTest, AesEcbSign) {
2937 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2938 .Authorization(TAG_NO_AUTH_REQUIRED)
2939 .SigningKey()
2940 .AesEncryptionKey(128)
2941 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2942
2943 AuthorizationSet out_params;
2944 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2945 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2946 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2947 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2948}
2949
2950/*
2951 * SigningOperationsTest.HmacAllDigests
2952 *
2953 * Verifies that HMAC works with all digests.
2954 */
2955TEST_P(SigningOperationsTest, HmacAllDigests) {
2956 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2957 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2958 .Authorization(TAG_NO_AUTH_REQUIRED)
2959 .HmacKey(128)
2960 .Digest(digest)
2961 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2962 << "Failed to create HMAC key with digest " << digest;
2963 string message = "12345678901234567890123456789012";
2964 string signature = MacMessage(message, digest, 160);
2965 EXPECT_EQ(160U / 8U, signature.size())
2966 << "Failed to sign with HMAC key with digest " << digest;
2967 CheckedDeleteKey();
2968 }
2969}
2970
2971/*
2972 * SigningOperationsTest.HmacSha256TooLargeMacLength
2973 *
2974 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2975 * digest size.
2976 */
2977TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2978 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2979 .Authorization(TAG_NO_AUTH_REQUIRED)
2980 .HmacKey(128)
2981 .Digest(Digest::SHA_2_256)
2982 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2983 AuthorizationSet output_params;
2984 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2985 AuthorizationSetBuilder()
2986 .Digest(Digest::SHA_2_256)
2987 .Authorization(TAG_MAC_LENGTH, 264),
2988 &output_params));
2989}
2990
2991/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002992 * SigningOperationsTest.HmacSha256InvalidMacLength
2993 *
2994 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2995 * not a multiple of 8.
2996 */
2997TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2998 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2999 .Authorization(TAG_NO_AUTH_REQUIRED)
3000 .HmacKey(128)
3001 .Digest(Digest::SHA_2_256)
3002 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3003 AuthorizationSet output_params;
3004 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3005 AuthorizationSetBuilder()
3006 .Digest(Digest::SHA_2_256)
3007 .Authorization(TAG_MAC_LENGTH, 161),
3008 &output_params));
3009}
3010
3011/*
Selene Huang31ab4042020-04-29 04:22:39 -07003012 * SigningOperationsTest.HmacSha256TooSmallMacLength
3013 *
3014 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3015 * specified minimum MAC length.
3016 */
3017TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3018 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3019 .Authorization(TAG_NO_AUTH_REQUIRED)
3020 .HmacKey(128)
3021 .Digest(Digest::SHA_2_256)
3022 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3023 AuthorizationSet output_params;
3024 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3025 AuthorizationSetBuilder()
3026 .Digest(Digest::SHA_2_256)
3027 .Authorization(TAG_MAC_LENGTH, 120),
3028 &output_params));
3029}
3030
3031/*
3032 * SigningOperationsTest.HmacRfc4231TestCase3
3033 *
3034 * Validates against the test vectors from RFC 4231 test case 3.
3035 */
3036TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3037 string key(20, 0xaa);
3038 string message(50, 0xdd);
3039 uint8_t sha_224_expected[] = {
3040 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3041 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3042 };
3043 uint8_t sha_256_expected[] = {
3044 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3045 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3046 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3047 };
3048 uint8_t sha_384_expected[] = {
3049 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3050 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3051 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3052 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3053 };
3054 uint8_t sha_512_expected[] = {
3055 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3056 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3057 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3058 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3059 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3060 };
3061
3062 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3063 if (SecLevel() != SecurityLevel::STRONGBOX) {
3064 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3065 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3066 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3067 }
3068}
3069
3070/*
3071 * SigningOperationsTest.HmacRfc4231TestCase5
3072 *
3073 * Validates against the test vectors from RFC 4231 test case 5.
3074 */
3075TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3076 string key(20, 0x0c);
3077 string message = "Test With Truncation";
3078
3079 uint8_t sha_224_expected[] = {
3080 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3081 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3082 };
3083 uint8_t sha_256_expected[] = {
3084 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3085 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3086 };
3087 uint8_t sha_384_expected[] = {
3088 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3089 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3090 };
3091 uint8_t sha_512_expected[] = {
3092 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3093 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3094 };
3095
3096 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3097 if (SecLevel() != SecurityLevel::STRONGBOX) {
3098 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3099 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3100 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3101 }
3102}
3103
3104INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3105
3106typedef KeyMintAidlTestBase VerificationOperationsTest;
3107
3108/*
Selene Huang31ab4042020-04-29 04:22:39 -07003109 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3110 *
3111 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3112 */
3113TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3114 string key_material = "HelloThisIsAKey";
3115
3116 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003117 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003118 EXPECT_EQ(ErrorCode::OK,
3119 ImportKey(AuthorizationSetBuilder()
3120 .Authorization(TAG_NO_AUTH_REQUIRED)
3121 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3122 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3123 .Digest(Digest::SHA_2_256)
3124 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3125 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3126 EXPECT_EQ(ErrorCode::OK,
3127 ImportKey(AuthorizationSetBuilder()
3128 .Authorization(TAG_NO_AUTH_REQUIRED)
3129 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3130 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3131 .Digest(Digest::SHA_2_256)
3132 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3133 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3134
3135 string message = "This is a message.";
3136 string signature = SignMessage(
3137 signing_key, message,
3138 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3139
3140 // Signing key should not work.
3141 AuthorizationSet out_params;
3142 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3143 Begin(KeyPurpose::VERIFY, signing_key,
3144 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3145
3146 // Verification key should work.
3147 VerifyMessage(verification_key, message, signature,
3148 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3149
3150 CheckedDeleteKey(&signing_key);
3151 CheckedDeleteKey(&verification_key);
3152}
3153
3154INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3155
3156typedef KeyMintAidlTestBase ExportKeyTest;
3157
3158/*
3159 * ExportKeyTest.RsaUnsupportedKeyFormat
3160 *
3161 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3162 */
3163// TODO(seleneh) add ExportKey to GenerateKey
3164// check result
3165
3166class ImportKeyTest : public KeyMintAidlTestBase {
3167 public:
3168 template <TagType tag_type, Tag tag, typename ValueT>
3169 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3170 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003171 for (auto& entry : key_characteristics_) {
3172 if (entry.securityLevel == SecLevel()) {
3173 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3174 << "Tag " << tag << " with value " << expected
3175 << " not found at security level" << entry.securityLevel;
3176 } else {
3177 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3178 << "Tag " << tag << " found at security level " << entry.securityLevel;
3179 }
Selene Huang31ab4042020-04-29 04:22:39 -07003180 }
3181 }
3182
3183 void CheckOrigin() {
3184 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003185 // Origin isn't a crypto param, but it always lives with them.
3186 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003187 }
3188};
3189
3190/*
3191 * ImportKeyTest.RsaSuccess
3192 *
3193 * Verifies that importing and using an RSA key pair works correctly.
3194 */
3195TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003196 uint32_t key_size;
3197 string key;
3198
3199 if (SecLevel() == SecurityLevel::STRONGBOX) {
3200 key_size = 2048;
3201 key = rsa_2048_key;
3202 } else {
3203 key_size = 1024;
3204 key = rsa_key;
3205 }
3206
Selene Huang31ab4042020-04-29 04:22:39 -07003207 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3208 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003209 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003210 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003211 .Padding(PaddingMode::RSA_PSS)
3212 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003213 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003214
3215 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003216 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003217 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3218 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3219 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3220 CheckOrigin();
3221
3222 string message(1024 / 8, 'a');
3223 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3224 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003225 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003226}
3227
3228/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003229 * ImportKeyTest.RsaSuccessWithoutParams
3230 *
3231 * Verifies that importing and using an RSA key pair without specifying parameters
3232 * works correctly.
3233 */
3234TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3235 uint32_t key_size;
3236 string key;
3237
3238 if (SecLevel() == SecurityLevel::STRONGBOX) {
3239 key_size = 2048;
3240 key = rsa_2048_key;
3241 } else {
3242 key_size = 1024;
3243 key = rsa_key;
3244 }
3245
3246 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3247 .Authorization(TAG_NO_AUTH_REQUIRED)
3248 .SigningKey()
3249 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3250 .Digest(Digest::SHA_2_256)
3251 .Padding(PaddingMode::RSA_PSS)
3252 .SetDefaultValidity(),
3253 KeyFormat::PKCS8, key));
3254
3255 // Key size and public exponent are determined from the imported key material.
3256 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3257 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3258
3259 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3260 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3261 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3262 CheckOrigin();
3263
3264 string message(1024 / 8, 'a');
3265 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3266 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003267 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003268}
3269
3270/*
Selene Huang31ab4042020-04-29 04:22:39 -07003271 * ImportKeyTest.RsaKeySizeMismatch
3272 *
3273 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3274 * correct way.
3275 */
3276TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3277 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3278 ImportKey(AuthorizationSetBuilder()
3279 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3280 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003281 .Padding(PaddingMode::NONE)
3282 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003283 KeyFormat::PKCS8, rsa_key));
3284}
3285
3286/*
3287 * ImportKeyTest.RsaPublicExponentMismatch
3288 *
3289 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3290 * fails in the correct way.
3291 */
3292TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3293 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3294 ImportKey(AuthorizationSetBuilder()
3295 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3296 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003297 .Padding(PaddingMode::NONE)
3298 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003299 KeyFormat::PKCS8, rsa_key));
3300}
3301
3302/*
3303 * ImportKeyTest.EcdsaSuccess
3304 *
3305 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3306 */
3307TEST_P(ImportKeyTest, EcdsaSuccess) {
3308 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3309 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003310 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003311 .Digest(Digest::SHA_2_256)
3312 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003313 KeyFormat::PKCS8, ec_256_key));
3314
3315 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003316 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3317 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3318
3319 CheckOrigin();
3320
3321 string message(32, 'a');
3322 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3323 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003324 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003325}
3326
3327/*
3328 * ImportKeyTest.EcdsaP256RFC5915Success
3329 *
3330 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3331 * correctly.
3332 */
3333TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3334 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3335 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003336 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003337 .Digest(Digest::SHA_2_256)
3338 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003339 KeyFormat::PKCS8, ec_256_key_rfc5915));
3340
3341 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003342 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3343 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3344
3345 CheckOrigin();
3346
3347 string message(32, 'a');
3348 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3349 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003350 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003351}
3352
3353/*
3354 * ImportKeyTest.EcdsaP256SEC1Success
3355 *
3356 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3357 */
3358TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3359 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3360 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003361 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003362 .Digest(Digest::SHA_2_256)
3363 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003364 KeyFormat::PKCS8, ec_256_key_sec1));
3365
3366 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003367 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3368 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3369
3370 CheckOrigin();
3371
3372 string message(32, 'a');
3373 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3374 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003375 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003376}
3377
3378/*
3379 * ImportKeyTest.Ecdsa521Success
3380 *
3381 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3382 */
3383TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01003384 if (SecLevel() == SecurityLevel::STRONGBOX) {
3385 GTEST_SKIP() << "Test not applicable to StrongBox device";
3386 }
Selene Huang31ab4042020-04-29 04:22:39 -07003387 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3388 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003389 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003390 .Digest(Digest::SHA_2_256)
3391 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003392 KeyFormat::PKCS8, ec_521_key));
3393
3394 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003395 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3396 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3397 CheckOrigin();
3398
3399 string message(32, 'a');
3400 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3401 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003402 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003403}
3404
3405/*
Selene Huang31ab4042020-04-29 04:22:39 -07003406 * ImportKeyTest.EcdsaCurveMismatch
3407 *
3408 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3409 * the correct way.
3410 */
3411TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3412 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3413 ImportKey(AuthorizationSetBuilder()
3414 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003415 .Digest(Digest::NONE)
3416 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003417 KeyFormat::PKCS8, ec_256_key));
3418}
3419
3420/*
3421 * ImportKeyTest.AesSuccess
3422 *
3423 * Verifies that importing and using an AES key works.
3424 */
3425TEST_P(ImportKeyTest, AesSuccess) {
3426 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3427 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3428 .Authorization(TAG_NO_AUTH_REQUIRED)
3429 .AesEncryptionKey(key.size() * 8)
3430 .EcbMode()
3431 .Padding(PaddingMode::PKCS7),
3432 KeyFormat::RAW, key));
3433
3434 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3435 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3436 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3437 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3438 CheckOrigin();
3439
3440 string message = "Hello World!";
3441 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3442 string ciphertext = EncryptMessage(message, params);
3443 string plaintext = DecryptMessage(ciphertext, params);
3444 EXPECT_EQ(message, plaintext);
3445}
3446
3447/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003448 * ImportKeyTest.AesFailure
3449 *
3450 * Verifies that importing an invalid AES key fails.
3451 */
3452TEST_P(ImportKeyTest, AesFailure) {
3453 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3454 uint32_t bitlen = key.size() * 8;
3455 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003456 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003457 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003458 .Authorization(TAG_NO_AUTH_REQUIRED)
3459 .AesEncryptionKey(key_size)
3460 .EcbMode()
3461 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003462 KeyFormat::RAW, key);
3463 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003464 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3465 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003466 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003467
3468 // Explicit key size matches that of the provided key, but it's not a valid size.
3469 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3470 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3471 ImportKey(AuthorizationSetBuilder()
3472 .Authorization(TAG_NO_AUTH_REQUIRED)
3473 .AesEncryptionKey(long_key.size() * 8)
3474 .EcbMode()
3475 .Padding(PaddingMode::PKCS7),
3476 KeyFormat::RAW, long_key));
3477 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3478 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3479 ImportKey(AuthorizationSetBuilder()
3480 .Authorization(TAG_NO_AUTH_REQUIRED)
3481 .AesEncryptionKey(short_key.size() * 8)
3482 .EcbMode()
3483 .Padding(PaddingMode::PKCS7),
3484 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003485}
3486
3487/*
3488 * ImportKeyTest.TripleDesSuccess
3489 *
3490 * Verifies that importing and using a 3DES key works.
3491 */
3492TEST_P(ImportKeyTest, TripleDesSuccess) {
3493 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3494 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3495 .Authorization(TAG_NO_AUTH_REQUIRED)
3496 .TripleDesEncryptionKey(168)
3497 .EcbMode()
3498 .Padding(PaddingMode::PKCS7),
3499 KeyFormat::RAW, key));
3500
3501 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3502 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3503 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3504 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3505 CheckOrigin();
3506
3507 string message = "Hello World!";
3508 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3509 string ciphertext = EncryptMessage(message, params);
3510 string plaintext = DecryptMessage(ciphertext, params);
3511 EXPECT_EQ(message, plaintext);
3512}
3513
3514/*
3515 * ImportKeyTest.TripleDesFailure
3516 *
3517 * Verifies that importing an invalid 3DES key fails.
3518 */
3519TEST_P(ImportKeyTest, TripleDesFailure) {
3520 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003521 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003522 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003523 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003524 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003525 .Authorization(TAG_NO_AUTH_REQUIRED)
3526 .TripleDesEncryptionKey(key_size)
3527 .EcbMode()
3528 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003529 KeyFormat::RAW, key);
3530 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003531 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3532 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003533 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003534 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003535 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003536 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3537 ImportKey(AuthorizationSetBuilder()
3538 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003539 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003540 .EcbMode()
3541 .Padding(PaddingMode::PKCS7),
3542 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003543 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003544 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3545 ImportKey(AuthorizationSetBuilder()
3546 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003547 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003548 .EcbMode()
3549 .Padding(PaddingMode::PKCS7),
3550 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003551}
3552
3553/*
3554 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003555 *
3556 * Verifies that importing and using an HMAC key works.
3557 */
3558TEST_P(ImportKeyTest, HmacKeySuccess) {
3559 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3560 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3561 .Authorization(TAG_NO_AUTH_REQUIRED)
3562 .HmacKey(key.size() * 8)
3563 .Digest(Digest::SHA_2_256)
3564 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3565 KeyFormat::RAW, key));
3566
3567 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3568 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3569 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3570 CheckOrigin();
3571
3572 string message = "Hello World!";
3573 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3574 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3575}
3576
3577INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3578
3579auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003580 // IKeyMintDevice.aidl
3581 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3582 "020100" // INTEGER length 1 value 0x00 (version)
3583 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3584 "934bf94e2aa28a3f83c9f79297250262"
3585 "fbe3276b5a1c91159bbfa3ef8957aac8"
3586 "4b59b30b455a79c2973480823d8b3863"
3587 "c3deef4a8e243590268d80e18751a0e1"
3588 "30f67ce6a1ace9f79b95e097474febc9"
3589 "81195b1d13a69086c0863f66a7b7fdb4"
3590 "8792227b1ac5e2489febdf087ab54864"
3591 "83033a6f001ca5d1ec1e27f5c30f4cec"
3592 "2642074a39ae68aee552e196627a8e3d"
3593 "867e67a8c01b11e75f13cca0a97ab668"
3594 "b50cda07a8ecb7cd8e3dd7009c963653"
3595 "4f6f239cffe1fc8daa466f78b676c711"
3596 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3597 "99b801597d5220e307eaa5bee507fb94"
3598 "d1fa69f9e519b2de315bac92c36f2ea1"
3599 "fa1df4478c0ddedeae8c70e0233cd098"
3600 "040c" // OCTET STRING length 0x0c (initializationVector)
3601 "d796b02c370f1fa4cc0124f1"
3602 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3603 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3604 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3605 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3606 "3106" // SET length 0x06
3607 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3608 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3609 // } end SET
3610 // } end [1]
3611 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3612 "020120" // INTEGER length 1 value 0x20 (AES)
3613 // } end [2]
3614 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3615 "02020100" // INTEGER length 2 value 0x100
3616 // } end [3]
3617 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3618 "3103" // SET length 0x03 {
3619 "020101" // INTEGER length 1 value 0x01 (ECB)
3620 // } end SET
3621 // } end [4]
3622 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3623 "3103" // SET length 0x03 {
3624 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3625 // } end SET
3626 // } end [5]
3627 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3628 // (noAuthRequired)
3629 "0500" // NULL
3630 // } end [503]
3631 // } end SEQUENCE (AuthorizationList)
3632 // } end SEQUENCE (KeyDescription)
3633 "0420" // OCTET STRING length 0x20 (encryptedKey)
3634 "ccd540855f833a5e1480bfd2d36faf3a"
3635 "eee15df5beabe2691bc82dde2a7aa910"
3636 "0410" // OCTET STRING length 0x10 (tag)
3637 "64c9f689c60ff6223ab6e6999e0eb6e5"
3638 // } SEQUENCE (SecureKeyWrapper)
3639);
Selene Huang31ab4042020-04-29 04:22:39 -07003640
3641auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003642 // IKeyMintDevice.aidl
3643 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3644 "020100" // INTEGER length 1 value 0x00 (version)
3645 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3646 "aad93ed5924f283b4bb5526fbe7a1412"
3647 "f9d9749ec30db9062b29e574a8546f33"
3648 "c88732452f5b8e6a391ee76c39ed1712"
3649 "c61d8df6213dec1cffbc17a8c6d04c7b"
3650 "30893d8daa9b2015213e219468215532"
3651 "07f8f9931c4caba23ed3bee28b36947e"
3652 "47f10e0a5c3dc51c988a628daad3e5e1"
3653 "f4005e79c2d5a96c284b4b8d7e4948f3"
3654 "31e5b85dd5a236f85579f3ea1d1b8484"
3655 "87470bdb0ab4f81a12bee42c99fe0df4"
3656 "bee3759453e69ad1d68a809ce06b949f"
3657 "7694a990429b2fe81e066ff43e56a216"
3658 "02db70757922a4bcc23ab89f1e35da77"
3659 "586775f423e519c2ea394caf48a28d0c"
3660 "8020f1dcf6b3a68ec246f615ae96dae9"
3661 "a079b1f6eb959033c1af5c125fd94168"
3662 "040c" // OCTET STRING length 0x0c (initializationVector)
3663 "6d9721d08589581ab49204a3"
3664 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3665 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3666 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3667 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3668 "3106" // SET length 0x06
3669 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3670 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3671 // } end SET
3672 // } end [1]
3673 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3674 "020120" // INTEGER length 1 value 0x20 (AES)
3675 // } end [2]
3676 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3677 "02020100" // INTEGER length 2 value 0x100
3678 // } end [3]
3679 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3680 "3103" // SET length 0x03 {
3681 "020101" // INTEGER length 1 value 0x01 (ECB)
3682 // } end SET
3683 // } end [4]
3684 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3685 "3103" // SET length 0x03 {
3686 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3687 // } end SET
3688 // } end [5]
3689 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3690 // (noAuthRequired)
3691 "0500" // NULL
3692 // } end [503]
3693 // } end SEQUENCE (AuthorizationList)
3694 // } end SEQUENCE (KeyDescription)
3695 "0420" // OCTET STRING length 0x20 (encryptedKey)
3696 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3697 "c20d1f99a9a024a76f35c8e2cab9b68d"
3698 "0410" // OCTET STRING length 0x10 (tag)
3699 "2560c70109ae67c030f00b98b512a670"
3700 // } SEQUENCE (SecureKeyWrapper)
3701);
Selene Huang31ab4042020-04-29 04:22:39 -07003702
3703auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003704 // RFC 5208 s5
3705 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3706 "020100" // INTEGER length 1 value 0x00 (version)
3707 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3708 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3709 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3710 "0500" // NULL (parameters)
3711 // } SEQUENCE (AlgorithmIdentifier)
3712 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3713 // RFC 8017 A.1.2
3714 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3715 "020100" // INTEGER length 1 value 0x00 (version)
3716 "02820101" // INTEGER length 0x0101 (modulus) value...
3717 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3718 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3719 "7b06e673a837313d56b1c725150a3fef" // 0x30
3720 "86acbddc41bb759c2854eae32d35841e" // 0x40
3721 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3722 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3723 "312d7bd5921ffaea1347c157406fef71" // 0x70
3724 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3725 "f4645c11f5c1374c3886427411c44979" // 0x90
3726 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3727 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3728 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3729 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3730 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3731 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3732 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3733 "55" // 0x101
3734 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3735 "02820100" // INTEGER length 0x100 (privateExponent) value...
3736 "431447b6251908112b1ee76f99f3711a" // 0x10
3737 "52b6630960046c2de70de188d833f8b8" // 0x20
3738 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3739 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3740 "e710b630a03adc683b5d2c43080e52be" // 0x50
3741 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3742 "822bccff087d63c940ba8a45f670feb2" // 0x70
3743 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3744 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3745 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3746 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3747 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3748 "52659d5a5ba05b663737a8696281865b" // 0xd0
3749 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3750 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3751 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3752 "028181" // INTEGER length 0x81 (prime1) value...
3753 "00de392e18d682c829266cc3454e1d61" // 0x10
3754 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3755 "ff841be5bac82a164c5970007047b8c5" // 0x30
3756 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3757 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3758 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3759 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3760 "9e91346130748a6e3c124f9149d71c74" // 0x80
3761 "35"
3762 "028181" // INTEGER length 0x81 (prime2) value...
3763 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3764 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3765 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3766 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3767 "9ed39a2d934c880440aed8832f984316" // 0x50
3768 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3769 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3770 "b880677c068e1be936e81288815252a8" // 0x80
3771 "a1"
3772 "028180" // INTEGER length 0x80 (exponent1) value...
3773 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3774 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3775 "5a063212a4f105a3764743e53281988a" // 0x30
3776 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3777 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3778 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3779 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3780 "4719d6e2b9439823719cd08bcd031781" // 0x80
3781 "028181" // INTEGER length 0x81 (exponent2) value...
3782 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3783 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3784 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3785 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3786 "1254186af30b22c10582a8a43e34fe94" // 0x50
3787 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3788 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3789 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3790 "61"
3791 "028181" // INTEGER length 0x81 (coefficient) value...
3792 "00c931617c77829dfb1270502be9195c" // 0x10
3793 "8f2830885f57dba869536811e6864236" // 0x20
3794 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3795 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3796 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3797 "959356210723287b0affcc9f727044d4" // 0x60
3798 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3799 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3800 "22"
3801 // } SEQUENCE
3802 // } SEQUENCE ()
3803);
Selene Huang31ab4042020-04-29 04:22:39 -07003804
3805string zero_masking_key =
3806 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3807string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3808
3809class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3810
3811TEST_P(ImportWrappedKeyTest, Success) {
3812 auto wrapping_key_desc = AuthorizationSetBuilder()
3813 .RsaEncryptionKey(2048, 65537)
3814 .Digest(Digest::SHA_2_256)
3815 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003816 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3817 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003818
3819 ASSERT_EQ(ErrorCode::OK,
3820 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3821 AuthorizationSetBuilder()
3822 .Digest(Digest::SHA_2_256)
3823 .Padding(PaddingMode::RSA_OAEP)));
3824
3825 string message = "Hello World!";
3826 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3827 string ciphertext = EncryptMessage(message, params);
3828 string plaintext = DecryptMessage(ciphertext, params);
3829 EXPECT_EQ(message, plaintext);
3830}
3831
David Drysdaled2cc8c22021-04-15 13:29:45 +01003832/*
3833 * ImportWrappedKeyTest.SuccessSidsIgnored
3834 *
3835 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3836 * include Tag:USER_SECURE_ID.
3837 */
3838TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3839 auto wrapping_key_desc = AuthorizationSetBuilder()
3840 .RsaEncryptionKey(2048, 65537)
3841 .Digest(Digest::SHA_2_256)
3842 .Padding(PaddingMode::RSA_OAEP)
3843 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3844 .SetDefaultValidity();
3845
3846 int64_t password_sid = 42;
3847 int64_t biometric_sid = 24;
3848 ASSERT_EQ(ErrorCode::OK,
3849 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3850 AuthorizationSetBuilder()
3851 .Digest(Digest::SHA_2_256)
3852 .Padding(PaddingMode::RSA_OAEP),
3853 password_sid, biometric_sid));
3854
3855 string message = "Hello World!";
3856 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3857 string ciphertext = EncryptMessage(message, params);
3858 string plaintext = DecryptMessage(ciphertext, params);
3859 EXPECT_EQ(message, plaintext);
3860}
3861
Selene Huang31ab4042020-04-29 04:22:39 -07003862TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3863 auto wrapping_key_desc = AuthorizationSetBuilder()
3864 .RsaEncryptionKey(2048, 65537)
3865 .Digest(Digest::SHA_2_256)
3866 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003867 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3868 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003869
3870 ASSERT_EQ(ErrorCode::OK,
3871 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3872 AuthorizationSetBuilder()
3873 .Digest(Digest::SHA_2_256)
3874 .Padding(PaddingMode::RSA_OAEP)));
3875}
3876
3877TEST_P(ImportWrappedKeyTest, WrongMask) {
3878 auto wrapping_key_desc = AuthorizationSetBuilder()
3879 .RsaEncryptionKey(2048, 65537)
3880 .Digest(Digest::SHA_2_256)
3881 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003882 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3883 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003884
3885 ASSERT_EQ(
3886 ErrorCode::VERIFICATION_FAILED,
3887 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3888 AuthorizationSetBuilder()
3889 .Digest(Digest::SHA_2_256)
3890 .Padding(PaddingMode::RSA_OAEP)));
3891}
3892
3893TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3894 auto wrapping_key_desc = AuthorizationSetBuilder()
3895 .RsaEncryptionKey(2048, 65537)
3896 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003897 .Padding(PaddingMode::RSA_OAEP)
3898 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003899
3900 ASSERT_EQ(
3901 ErrorCode::INCOMPATIBLE_PURPOSE,
3902 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3903 AuthorizationSetBuilder()
3904 .Digest(Digest::SHA_2_256)
3905 .Padding(PaddingMode::RSA_OAEP)));
3906}
3907
David Drysdaled2cc8c22021-04-15 13:29:45 +01003908TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3909 auto wrapping_key_desc = AuthorizationSetBuilder()
3910 .RsaEncryptionKey(2048, 65537)
3911 .Digest(Digest::SHA_2_256)
3912 .Padding(PaddingMode::RSA_PSS)
3913 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3914 .SetDefaultValidity();
3915
3916 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3917 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3918 AuthorizationSetBuilder()
3919 .Digest(Digest::SHA_2_256)
3920 .Padding(PaddingMode::RSA_OAEP)));
3921}
3922
3923TEST_P(ImportWrappedKeyTest, WrongDigest) {
3924 auto wrapping_key_desc = AuthorizationSetBuilder()
3925 .RsaEncryptionKey(2048, 65537)
3926 .Digest(Digest::SHA_2_512)
3927 .Padding(PaddingMode::RSA_OAEP)
3928 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3929 .SetDefaultValidity();
3930
3931 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3932 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3933 AuthorizationSetBuilder()
3934 .Digest(Digest::SHA_2_256)
3935 .Padding(PaddingMode::RSA_OAEP)));
3936}
3937
Selene Huang31ab4042020-04-29 04:22:39 -07003938INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3939
3940typedef KeyMintAidlTestBase EncryptionOperationsTest;
3941
3942/*
3943 * EncryptionOperationsTest.RsaNoPaddingSuccess
3944 *
David Drysdale59cae642021-05-12 13:52:03 +01003945 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003946 */
3947TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003948 for (uint64_t exponent : {3, 65537}) {
3949 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3950 .Authorization(TAG_NO_AUTH_REQUIRED)
3951 .RsaEncryptionKey(2048, exponent)
3952 .Padding(PaddingMode::NONE)
3953 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003954
David Drysdaled2cc8c22021-04-15 13:29:45 +01003955 string message = string(2048 / 8, 'a');
3956 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003957 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003958 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003959
David Drysdale59cae642021-05-12 13:52:03 +01003960 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003961 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003962
David Drysdaled2cc8c22021-04-15 13:29:45 +01003963 // Unpadded RSA is deterministic
3964 EXPECT_EQ(ciphertext1, ciphertext2);
3965
3966 CheckedDeleteKey();
3967 }
Selene Huang31ab4042020-04-29 04:22:39 -07003968}
3969
3970/*
3971 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3972 *
David Drysdale59cae642021-05-12 13:52:03 +01003973 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003974 */
3975TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3976 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3977 .Authorization(TAG_NO_AUTH_REQUIRED)
3978 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003979 .Padding(PaddingMode::NONE)
3980 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003981
3982 string message = "1";
3983 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3984
David Drysdale59cae642021-05-12 13:52:03 +01003985 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003986 EXPECT_EQ(2048U / 8, ciphertext.size());
3987
3988 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3989 string plaintext = DecryptMessage(ciphertext, params);
3990
3991 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003992}
3993
3994/*
Selene Huang31ab4042020-04-29 04:22:39 -07003995 * EncryptionOperationsTest.RsaOaepSuccess
3996 *
David Drysdale59cae642021-05-12 13:52:03 +01003997 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003998 */
3999TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4000 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4001
4002 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01004003 ASSERT_EQ(ErrorCode::OK,
4004 GenerateKey(AuthorizationSetBuilder()
4005 .Authorization(TAG_NO_AUTH_REQUIRED)
4006 .RsaEncryptionKey(key_size, 65537)
4007 .Padding(PaddingMode::RSA_OAEP)
4008 .Digest(digests)
4009 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
4010 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004011
4012 string message = "Hello";
4013
4014 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01004015 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4016
4017 auto params = AuthorizationSetBuilder()
4018 .Digest(digest)
4019 .Padding(PaddingMode::RSA_OAEP)
4020 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
4021 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004022 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4023 EXPECT_EQ(key_size / 8, ciphertext1.size());
4024
David Drysdale59cae642021-05-12 13:52:03 +01004025 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004026 EXPECT_EQ(key_size / 8, ciphertext2.size());
4027
4028 // OAEP randomizes padding so every result should be different (with astronomically high
4029 // probability).
4030 EXPECT_NE(ciphertext1, ciphertext2);
4031
4032 string plaintext1 = DecryptMessage(ciphertext1, params);
4033 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4034 string plaintext2 = DecryptMessage(ciphertext2, params);
4035 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4036
4037 // Decrypting corrupted ciphertext should fail.
4038 size_t offset_to_corrupt = random() % ciphertext1.size();
4039 char corrupt_byte;
4040 do {
4041 corrupt_byte = static_cast<char>(random() % 256);
4042 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4043 ciphertext1[offset_to_corrupt] = corrupt_byte;
4044
4045 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4046 string result;
4047 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4048 EXPECT_EQ(0U, result.size());
4049 }
4050}
4051
4052/*
4053 * EncryptionOperationsTest.RsaOaepInvalidDigest
4054 *
David Drysdale59cae642021-05-12 13:52:03 +01004055 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07004056 * without a digest.
4057 */
4058TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
4059 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4060 .Authorization(TAG_NO_AUTH_REQUIRED)
4061 .RsaEncryptionKey(2048, 65537)
4062 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004063 .Digest(Digest::NONE)
4064 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004065
4066 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004067 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07004068}
4069
4070/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004071 * EncryptionOperationsTest.RsaOaepInvalidPadding
4072 *
David Drysdale59cae642021-05-12 13:52:03 +01004073 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01004074 * with a padding value that is only suitable for signing/verifying.
4075 */
4076TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
4077 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4078 .Authorization(TAG_NO_AUTH_REQUIRED)
4079 .RsaEncryptionKey(2048, 65537)
4080 .Padding(PaddingMode::RSA_PSS)
4081 .Digest(Digest::NONE)
4082 .SetDefaultValidity()));
4083
4084 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004085 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01004086}
4087
4088/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004089 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07004090 *
David Drysdale59cae642021-05-12 13:52:03 +01004091 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004092 * with a different digest than was used to encrypt.
4093 */
4094TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01004095 if (SecLevel() == SecurityLevel::STRONGBOX) {
4096 GTEST_SKIP() << "Test not applicable to StrongBox device";
4097 }
Selene Huang31ab4042020-04-29 04:22:39 -07004098
4099 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4100 .Authorization(TAG_NO_AUTH_REQUIRED)
4101 .RsaEncryptionKey(1024, 65537)
4102 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004103 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
4104 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004105 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01004106 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07004107 message,
4108 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
4109
4110 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4111 .Digest(Digest::SHA_2_256)
4112 .Padding(PaddingMode::RSA_OAEP)));
4113 string result;
4114 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
4115 EXPECT_EQ(0U, result.size());
4116}
4117
4118/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004119 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
4120 *
David Drysdale59cae642021-05-12 13:52:03 +01004121 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004122 * digests.
4123 */
4124TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
4125 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4126
4127 size_t key_size = 2048; // Need largish key for SHA-512 test.
4128 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4129 .OaepMGFDigest(digests)
4130 .Authorization(TAG_NO_AUTH_REQUIRED)
4131 .RsaEncryptionKey(key_size, 65537)
4132 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004133 .Digest(Digest::SHA_2_256)
4134 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004135
4136 string message = "Hello";
4137
4138 for (auto digest : digests) {
4139 auto params = AuthorizationSetBuilder()
4140 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4141 .Digest(Digest::SHA_2_256)
4142 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01004143 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004144 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4145 EXPECT_EQ(key_size / 8, ciphertext1.size());
4146
David Drysdale59cae642021-05-12 13:52:03 +01004147 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004148 EXPECT_EQ(key_size / 8, ciphertext2.size());
4149
4150 // OAEP randomizes padding so every result should be different (with astronomically high
4151 // probability).
4152 EXPECT_NE(ciphertext1, ciphertext2);
4153
4154 string plaintext1 = DecryptMessage(ciphertext1, params);
4155 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4156 string plaintext2 = DecryptMessage(ciphertext2, params);
4157 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4158
4159 // Decrypting corrupted ciphertext should fail.
4160 size_t offset_to_corrupt = random() % ciphertext1.size();
4161 char corrupt_byte;
4162 do {
4163 corrupt_byte = static_cast<char>(random() % 256);
4164 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4165 ciphertext1[offset_to_corrupt] = corrupt_byte;
4166
4167 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4168 string result;
4169 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4170 EXPECT_EQ(0U, result.size());
4171 }
4172}
4173
4174/*
4175 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4176 *
David Drysdale59cae642021-05-12 13:52:03 +01004177 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004178 * with incompatible MGF digest.
4179 */
4180TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4181 ASSERT_EQ(ErrorCode::OK,
4182 GenerateKey(AuthorizationSetBuilder()
4183 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4184 .Authorization(TAG_NO_AUTH_REQUIRED)
4185 .RsaEncryptionKey(2048, 65537)
4186 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004187 .Digest(Digest::SHA_2_256)
4188 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004189 string message = "Hello World!";
4190
4191 auto params = AuthorizationSetBuilder()
4192 .Padding(PaddingMode::RSA_OAEP)
4193 .Digest(Digest::SHA_2_256)
4194 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004195 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004196}
4197
4198/*
4199 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4200 *
4201 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4202 * with unsupported MGF digest.
4203 */
4204TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4205 ASSERT_EQ(ErrorCode::OK,
4206 GenerateKey(AuthorizationSetBuilder()
4207 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4208 .Authorization(TAG_NO_AUTH_REQUIRED)
4209 .RsaEncryptionKey(2048, 65537)
4210 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004211 .Digest(Digest::SHA_2_256)
4212 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004213 string message = "Hello World!";
4214
4215 auto params = AuthorizationSetBuilder()
4216 .Padding(PaddingMode::RSA_OAEP)
4217 .Digest(Digest::SHA_2_256)
4218 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004219 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004220}
4221
4222/*
Selene Huang31ab4042020-04-29 04:22:39 -07004223 * EncryptionOperationsTest.RsaPkcs1Success
4224 *
4225 * Verifies that RSA PKCS encryption/decrypts works.
4226 */
4227TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4228 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4229 .Authorization(TAG_NO_AUTH_REQUIRED)
4230 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004231 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4232 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004233
4234 string message = "Hello World!";
4235 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004236 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004237 EXPECT_EQ(2048U / 8, ciphertext1.size());
4238
David Drysdale59cae642021-05-12 13:52:03 +01004239 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004240 EXPECT_EQ(2048U / 8, ciphertext2.size());
4241
4242 // PKCS1 v1.5 randomizes padding so every result should be different.
4243 EXPECT_NE(ciphertext1, ciphertext2);
4244
4245 string plaintext = DecryptMessage(ciphertext1, params);
4246 EXPECT_EQ(message, plaintext);
4247
4248 // Decrypting corrupted ciphertext should fail.
4249 size_t offset_to_corrupt = random() % ciphertext1.size();
4250 char corrupt_byte;
4251 do {
4252 corrupt_byte = static_cast<char>(random() % 256);
4253 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4254 ciphertext1[offset_to_corrupt] = corrupt_byte;
4255
4256 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4257 string result;
4258 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4259 EXPECT_EQ(0U, result.size());
4260}
4261
4262/*
Selene Huang31ab4042020-04-29 04:22:39 -07004263 * EncryptionOperationsTest.EcdsaEncrypt
4264 *
4265 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4266 */
4267TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4268 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4269 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004270 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004271 .Digest(Digest::NONE)
4272 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004273 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4274 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4275 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4276}
4277
4278/*
4279 * EncryptionOperationsTest.HmacEncrypt
4280 *
4281 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4282 */
4283TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4284 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4285 .Authorization(TAG_NO_AUTH_REQUIRED)
4286 .HmacKey(128)
4287 .Digest(Digest::SHA_2_256)
4288 .Padding(PaddingMode::NONE)
4289 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4290 auto params = AuthorizationSetBuilder()
4291 .Digest(Digest::SHA_2_256)
4292 .Padding(PaddingMode::NONE)
4293 .Authorization(TAG_MAC_LENGTH, 128);
4294 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4295 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4296}
4297
4298/*
4299 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4300 *
4301 * Verifies that AES ECB mode works.
4302 */
4303TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4304 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4305 .Authorization(TAG_NO_AUTH_REQUIRED)
4306 .AesEncryptionKey(128)
4307 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4308 .Padding(PaddingMode::NONE)));
4309
4310 ASSERT_GT(key_blob_.size(), 0U);
4311 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4312
4313 // Two-block message.
4314 string message = "12345678901234567890123456789012";
4315 string ciphertext1 = EncryptMessage(message, params);
4316 EXPECT_EQ(message.size(), ciphertext1.size());
4317
4318 string ciphertext2 = EncryptMessage(string(message), params);
4319 EXPECT_EQ(message.size(), ciphertext2.size());
4320
4321 // ECB is deterministic.
4322 EXPECT_EQ(ciphertext1, ciphertext2);
4323
4324 string plaintext = DecryptMessage(ciphertext1, params);
4325 EXPECT_EQ(message, plaintext);
4326}
4327
4328/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004329 * EncryptionOperationsTest.AesEcbUnknownTag
4330 *
4331 * Verifies that AES ECB operations ignore unknown tags.
4332 */
4333TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4334 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4335 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4336 KeyParameter unknown_param;
4337 unknown_param.tag = unknown_tag;
4338
4339 vector<KeyCharacteristics> key_characteristics;
4340 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4341 .Authorization(TAG_NO_AUTH_REQUIRED)
4342 .AesEncryptionKey(128)
4343 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4344 .Padding(PaddingMode::NONE)
4345 .Authorization(unknown_param),
4346 &key_blob_, &key_characteristics));
4347 ASSERT_GT(key_blob_.size(), 0U);
4348
4349 // Unknown tags should not be returned in key characteristics.
4350 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4351 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4352 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4353 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4354
4355 // Encrypt without mentioning the unknown parameter.
4356 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4357 string message = "12345678901234567890123456789012";
4358 string ciphertext = EncryptMessage(message, params);
4359 EXPECT_EQ(message.size(), ciphertext.size());
4360
4361 // Decrypt including the unknown parameter.
4362 auto decrypt_params = AuthorizationSetBuilder()
4363 .BlockMode(BlockMode::ECB)
4364 .Padding(PaddingMode::NONE)
4365 .Authorization(unknown_param);
4366 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4367 EXPECT_EQ(message, plaintext);
4368}
4369
4370/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004371 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004372 *
4373 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4374 */
4375TEST_P(EncryptionOperationsTest, AesWrongMode) {
4376 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4377 .Authorization(TAG_NO_AUTH_REQUIRED)
4378 .AesEncryptionKey(128)
4379 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4380 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004381 ASSERT_GT(key_blob_.size(), 0U);
4382
Selene Huang31ab4042020-04-29 04:22:39 -07004383 EXPECT_EQ(
4384 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4385 Begin(KeyPurpose::ENCRYPT,
4386 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4387}
4388
4389/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004390 * EncryptionOperationsTest.AesWrongPadding
4391 *
4392 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4393 */
4394TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4395 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4396 .Authorization(TAG_NO_AUTH_REQUIRED)
4397 .AesEncryptionKey(128)
4398 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4399 .Padding(PaddingMode::NONE)));
4400 ASSERT_GT(key_blob_.size(), 0U);
4401
4402 EXPECT_EQ(
4403 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4404 Begin(KeyPurpose::ENCRYPT,
4405 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4406}
4407
4408/*
4409 * EncryptionOperationsTest.AesInvalidParams
4410 *
4411 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4412 */
4413TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4414 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4415 .Authorization(TAG_NO_AUTH_REQUIRED)
4416 .AesEncryptionKey(128)
4417 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4418 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4419 .Padding(PaddingMode::NONE)
4420 .Padding(PaddingMode::PKCS7)));
4421 ASSERT_GT(key_blob_.size(), 0U);
4422
4423 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4424 .BlockMode(BlockMode::CBC)
4425 .BlockMode(BlockMode::ECB)
4426 .Padding(PaddingMode::NONE));
4427 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4428 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4429
4430 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4431 .BlockMode(BlockMode::ECB)
4432 .Padding(PaddingMode::NONE)
4433 .Padding(PaddingMode::PKCS7));
4434 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4435 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4436}
4437
4438/*
Selene Huang31ab4042020-04-29 04:22:39 -07004439 * EncryptionOperationsTest.AesWrongPurpose
4440 *
4441 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4442 * specified.
4443 */
4444TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4445 auto err = GenerateKey(AuthorizationSetBuilder()
4446 .Authorization(TAG_NO_AUTH_REQUIRED)
4447 .AesKey(128)
4448 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4449 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4450 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4451 .Padding(PaddingMode::NONE));
4452 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4453 ASSERT_GT(key_blob_.size(), 0U);
4454
4455 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4456 .BlockMode(BlockMode::GCM)
4457 .Padding(PaddingMode::NONE)
4458 .Authorization(TAG_MAC_LENGTH, 128));
4459 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4460
4461 CheckedDeleteKey();
4462
4463 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4464 .Authorization(TAG_NO_AUTH_REQUIRED)
4465 .AesKey(128)
4466 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4467 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4468 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4469 .Padding(PaddingMode::NONE)));
4470
4471 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4472 .BlockMode(BlockMode::GCM)
4473 .Padding(PaddingMode::NONE)
4474 .Authorization(TAG_MAC_LENGTH, 128));
4475 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4476}
4477
4478/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004479 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004480 *
4481 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4482 * multiple of the block size and no padding is specified.
4483 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004484TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4485 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4486 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4487 .Authorization(TAG_NO_AUTH_REQUIRED)
4488 .AesEncryptionKey(128)
4489 .Authorization(TAG_BLOCK_MODE, blockMode)
4490 .Padding(PaddingMode::NONE)));
4491 // Message is slightly shorter than two blocks.
4492 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004493
David Drysdaled2cc8c22021-04-15 13:29:45 +01004494 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4495 AuthorizationSet out_params;
4496 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4497 string ciphertext;
4498 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4499 EXPECT_EQ(0U, ciphertext.size());
4500
4501 CheckedDeleteKey();
4502 }
Selene Huang31ab4042020-04-29 04:22:39 -07004503}
4504
4505/*
4506 * EncryptionOperationsTest.AesEcbPkcs7Padding
4507 *
4508 * Verifies that AES PKCS7 padding works for any message length.
4509 */
4510TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4511 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4512 .Authorization(TAG_NO_AUTH_REQUIRED)
4513 .AesEncryptionKey(128)
4514 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4515 .Padding(PaddingMode::PKCS7)));
4516
4517 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4518
4519 // Try various message lengths; all should work.
4520 for (size_t i = 0; i < 32; ++i) {
4521 string message(i, 'a');
4522 string ciphertext = EncryptMessage(message, params);
4523 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4524 string plaintext = DecryptMessage(ciphertext, params);
4525 EXPECT_EQ(message, plaintext);
4526 }
4527}
4528
4529/*
4530 * EncryptionOperationsTest.AesEcbWrongPadding
4531 *
4532 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4533 * specified.
4534 */
4535TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4536 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4537 .Authorization(TAG_NO_AUTH_REQUIRED)
4538 .AesEncryptionKey(128)
4539 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4540 .Padding(PaddingMode::NONE)));
4541
4542 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4543
4544 // Try various message lengths; all should fail
4545 for (size_t i = 0; i < 32; ++i) {
4546 string message(i, 'a');
4547 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4548 }
4549}
4550
4551/*
4552 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4553 *
4554 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4555 */
4556TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4557 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4558 .Authorization(TAG_NO_AUTH_REQUIRED)
4559 .AesEncryptionKey(128)
4560 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4561 .Padding(PaddingMode::PKCS7)));
4562
4563 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4564
4565 string message = "a";
4566 string ciphertext = EncryptMessage(message, params);
4567 EXPECT_EQ(16U, ciphertext.size());
4568 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07004569
Seth Moore7a55ae32021-06-23 14:28:11 -07004570 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
4571 ++ciphertext[ciphertext.size() / 2];
4572
4573 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4574 string plaintext;
4575 ErrorCode error = Finish(message, &plaintext);
4576 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
4577 // This is the expected error, we can exit the test now.
4578 return;
4579 } else {
4580 // Very small chance we got valid decryption, so try again.
4581 ASSERT_EQ(error, ErrorCode::OK);
4582 }
4583 }
4584 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07004585}
4586
4587vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4588 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004589 EXPECT_TRUE(iv);
4590 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004591}
4592
4593/*
4594 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4595 *
4596 * Verifies that AES CTR mode works.
4597 */
4598TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4599 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4600 .Authorization(TAG_NO_AUTH_REQUIRED)
4601 .AesEncryptionKey(128)
4602 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4603 .Padding(PaddingMode::NONE)));
4604
4605 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4606
4607 string message = "123";
4608 AuthorizationSet out_params;
4609 string ciphertext1 = EncryptMessage(message, params, &out_params);
4610 vector<uint8_t> iv1 = CopyIv(out_params);
4611 EXPECT_EQ(16U, iv1.size());
4612
4613 EXPECT_EQ(message.size(), ciphertext1.size());
4614
4615 out_params.Clear();
4616 string ciphertext2 = EncryptMessage(message, params, &out_params);
4617 vector<uint8_t> iv2 = CopyIv(out_params);
4618 EXPECT_EQ(16U, iv2.size());
4619
4620 // IVs should be random, so ciphertexts should differ.
4621 EXPECT_NE(ciphertext1, ciphertext2);
4622
4623 auto params_iv1 =
4624 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4625 auto params_iv2 =
4626 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4627
4628 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4629 EXPECT_EQ(message, plaintext);
4630 plaintext = DecryptMessage(ciphertext2, params_iv2);
4631 EXPECT_EQ(message, plaintext);
4632
4633 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4634 plaintext = DecryptMessage(ciphertext1, params_iv2);
4635 EXPECT_NE(message, plaintext);
4636 plaintext = DecryptMessage(ciphertext2, params_iv1);
4637 EXPECT_NE(message, plaintext);
4638}
4639
4640/*
4641 * EncryptionOperationsTest.AesIncremental
4642 *
4643 * Verifies that AES works, all modes, when provided data in various size increments.
4644 */
4645TEST_P(EncryptionOperationsTest, AesIncremental) {
4646 auto block_modes = {
4647 BlockMode::ECB,
4648 BlockMode::CBC,
4649 BlockMode::CTR,
4650 BlockMode::GCM,
4651 };
4652
4653 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4654 .Authorization(TAG_NO_AUTH_REQUIRED)
4655 .AesEncryptionKey(128)
4656 .BlockMode(block_modes)
4657 .Padding(PaddingMode::NONE)
4658 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4659
4660 for (int increment = 1; increment <= 240; ++increment) {
4661 for (auto block_mode : block_modes) {
4662 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004663 auto params =
4664 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4665 if (block_mode == BlockMode::GCM) {
4666 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4667 }
Selene Huang31ab4042020-04-29 04:22:39 -07004668
4669 AuthorizationSet output_params;
4670 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4671
4672 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004673 string to_send;
4674 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004675 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004676 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004677 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4678 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004679
4680 switch (block_mode) {
4681 case BlockMode::GCM:
4682 EXPECT_EQ(message.size() + 16, ciphertext.size());
4683 break;
4684 case BlockMode::CTR:
4685 EXPECT_EQ(message.size(), ciphertext.size());
4686 break;
4687 case BlockMode::CBC:
4688 case BlockMode::ECB:
4689 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4690 break;
4691 }
4692
4693 auto iv = output_params.GetTagValue(TAG_NONCE);
4694 switch (block_mode) {
4695 case BlockMode::CBC:
4696 case BlockMode::GCM:
4697 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004698 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4699 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4700 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004701 break;
4702
4703 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004704 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004705 break;
4706 }
4707
4708 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4709 << "Decrypt begin() failed for block mode " << block_mode;
4710
4711 string plaintext;
4712 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004713 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004714 }
4715 ErrorCode error = Finish(to_send, &plaintext);
4716 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4717 << " and increment " << increment;
4718 if (error == ErrorCode::OK) {
4719 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4720 << block_mode << " and increment " << increment;
4721 }
4722 }
4723 }
4724}
4725
4726struct AesCtrSp80038aTestVector {
4727 const char* key;
4728 const char* nonce;
4729 const char* plaintext;
4730 const char* ciphertext;
4731};
4732
4733// These test vectors are taken from
4734// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4735static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4736 // AES-128
4737 {
4738 "2b7e151628aed2a6abf7158809cf4f3c",
4739 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4740 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4741 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4742 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4743 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4744 },
4745 // AES-192
4746 {
4747 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4748 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4749 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4750 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4751 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4752 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4753 },
4754 // AES-256
4755 {
4756 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4757 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4758 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4759 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4760 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4761 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4762 },
4763};
4764
4765/*
4766 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4767 *
4768 * Verifies AES CTR implementation against SP800-38A test vectors.
4769 */
4770TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4771 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4772 for (size_t i = 0; i < 3; i++) {
4773 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4774 const string key = hex2str(test.key);
4775 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4776 InvalidSizes.end())
4777 continue;
4778 const string nonce = hex2str(test.nonce);
4779 const string plaintext = hex2str(test.plaintext);
4780 const string ciphertext = hex2str(test.ciphertext);
4781 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4782 }
4783}
4784
4785/*
4786 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4787 *
4788 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4789 */
4790TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4791 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4792 .Authorization(TAG_NO_AUTH_REQUIRED)
4793 .AesEncryptionKey(128)
4794 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4795 .Padding(PaddingMode::PKCS7)));
4796 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4797 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4798}
4799
4800/*
4801 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4802 *
4803 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4804 */
4805TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4806 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4807 .Authorization(TAG_NO_AUTH_REQUIRED)
4808 .AesEncryptionKey(128)
4809 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4810 .Authorization(TAG_CALLER_NONCE)
4811 .Padding(PaddingMode::NONE)));
4812
4813 auto params = AuthorizationSetBuilder()
4814 .BlockMode(BlockMode::CTR)
4815 .Padding(PaddingMode::NONE)
4816 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4817 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4818
4819 params = AuthorizationSetBuilder()
4820 .BlockMode(BlockMode::CTR)
4821 .Padding(PaddingMode::NONE)
4822 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4823 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4824
4825 params = AuthorizationSetBuilder()
4826 .BlockMode(BlockMode::CTR)
4827 .Padding(PaddingMode::NONE)
4828 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4829 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4830}
4831
4832/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004833 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004834 *
4835 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4836 */
4837TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4838 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4839 .Authorization(TAG_NO_AUTH_REQUIRED)
4840 .AesEncryptionKey(128)
4841 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4842 .Padding(PaddingMode::NONE)));
4843 // Two-block message.
4844 string message = "12345678901234567890123456789012";
4845 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4846 AuthorizationSet out_params;
4847 string ciphertext1 = EncryptMessage(message, params, &out_params);
4848 vector<uint8_t> iv1 = CopyIv(out_params);
4849 EXPECT_EQ(message.size(), ciphertext1.size());
4850
4851 out_params.Clear();
4852
4853 string ciphertext2 = EncryptMessage(message, params, &out_params);
4854 vector<uint8_t> iv2 = CopyIv(out_params);
4855 EXPECT_EQ(message.size(), ciphertext2.size());
4856
4857 // IVs should be random, so ciphertexts should differ.
4858 EXPECT_NE(ciphertext1, ciphertext2);
4859
4860 params.push_back(TAG_NONCE, iv1);
4861 string plaintext = DecryptMessage(ciphertext1, params);
4862 EXPECT_EQ(message, plaintext);
4863}
4864
4865/*
4866 * EncryptionOperationsTest.AesCallerNonce
4867 *
4868 * Verifies that AES caller-provided nonces work correctly.
4869 */
4870TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4871 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4872 .Authorization(TAG_NO_AUTH_REQUIRED)
4873 .AesEncryptionKey(128)
4874 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4875 .Authorization(TAG_CALLER_NONCE)
4876 .Padding(PaddingMode::NONE)));
4877
4878 string message = "12345678901234567890123456789012";
4879
4880 // Don't specify nonce, should get a random one.
4881 AuthorizationSetBuilder params =
4882 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4883 AuthorizationSet out_params;
4884 string ciphertext = EncryptMessage(message, params, &out_params);
4885 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004886 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004887
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004888 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004889 string plaintext = DecryptMessage(ciphertext, params);
4890 EXPECT_EQ(message, plaintext);
4891
4892 // Now specify a nonce, should also work.
4893 params = AuthorizationSetBuilder()
4894 .BlockMode(BlockMode::CBC)
4895 .Padding(PaddingMode::NONE)
4896 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4897 out_params.Clear();
4898 ciphertext = EncryptMessage(message, params, &out_params);
4899
4900 // Decrypt with correct nonce.
4901 plaintext = DecryptMessage(ciphertext, params);
4902 EXPECT_EQ(message, plaintext);
4903
4904 // Try with wrong nonce.
4905 params = AuthorizationSetBuilder()
4906 .BlockMode(BlockMode::CBC)
4907 .Padding(PaddingMode::NONE)
4908 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4909 plaintext = DecryptMessage(ciphertext, params);
4910 EXPECT_NE(message, plaintext);
4911}
4912
4913/*
4914 * EncryptionOperationsTest.AesCallerNonceProhibited
4915 *
4916 * Verifies that caller-provided nonces are not permitted when not specified in the key
4917 * authorizations.
4918 */
4919TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4920 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4921 .Authorization(TAG_NO_AUTH_REQUIRED)
4922 .AesEncryptionKey(128)
4923 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4924 .Padding(PaddingMode::NONE)));
4925
4926 string message = "12345678901234567890123456789012";
4927
4928 // Don't specify nonce, should get a random one.
4929 AuthorizationSetBuilder params =
4930 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4931 AuthorizationSet out_params;
4932 string ciphertext = EncryptMessage(message, params, &out_params);
4933 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004934 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004935
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004936 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004937 string plaintext = DecryptMessage(ciphertext, params);
4938 EXPECT_EQ(message, plaintext);
4939
4940 // Now specify a nonce, should fail
4941 params = AuthorizationSetBuilder()
4942 .BlockMode(BlockMode::CBC)
4943 .Padding(PaddingMode::NONE)
4944 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4945 out_params.Clear();
4946 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4947}
4948
4949/*
4950 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4951 *
4952 * Verifies that AES GCM mode works.
4953 */
4954TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4955 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4956 .Authorization(TAG_NO_AUTH_REQUIRED)
4957 .AesEncryptionKey(128)
4958 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4959 .Padding(PaddingMode::NONE)
4960 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4961
4962 string aad = "foobar";
4963 string message = "123456789012345678901234567890123456";
4964
4965 auto begin_params = AuthorizationSetBuilder()
4966 .BlockMode(BlockMode::GCM)
4967 .Padding(PaddingMode::NONE)
4968 .Authorization(TAG_MAC_LENGTH, 128);
4969
Selene Huang31ab4042020-04-29 04:22:39 -07004970 // Encrypt
4971 AuthorizationSet begin_out_params;
4972 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4973 << "Begin encrypt";
4974 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004975 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4976 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004977 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4978
4979 // Grab nonce
4980 begin_params.push_back(begin_out_params);
4981
4982 // Decrypt.
4983 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004984 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004985 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004986 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004987 EXPECT_EQ(message.length(), plaintext.length());
4988 EXPECT_EQ(message, plaintext);
4989}
4990
4991/*
4992 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4993 *
4994 * Verifies that AES GCM mode works, even when there's a long delay
4995 * between operations.
4996 */
4997TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4998 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4999 .Authorization(TAG_NO_AUTH_REQUIRED)
5000 .AesEncryptionKey(128)
5001 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5002 .Padding(PaddingMode::NONE)
5003 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5004
5005 string aad = "foobar";
5006 string message = "123456789012345678901234567890123456";
5007
5008 auto begin_params = AuthorizationSetBuilder()
5009 .BlockMode(BlockMode::GCM)
5010 .Padding(PaddingMode::NONE)
5011 .Authorization(TAG_MAC_LENGTH, 128);
5012
Selene Huang31ab4042020-04-29 04:22:39 -07005013 // Encrypt
5014 AuthorizationSet begin_out_params;
5015 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5016 << "Begin encrypt";
5017 string ciphertext;
5018 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005019 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005020 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005021 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005022
5023 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5024
5025 // Grab nonce
5026 begin_params.push_back(begin_out_params);
5027
5028 // Decrypt.
5029 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5030 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005031 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005032 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005033 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005034 sleep(5);
5035 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5036 EXPECT_EQ(message.length(), plaintext.length());
5037 EXPECT_EQ(message, plaintext);
5038}
5039
5040/*
5041 * EncryptionOperationsTest.AesGcmDifferentNonces
5042 *
5043 * Verifies that encrypting the same data with different nonces produces different outputs.
5044 */
5045TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
5046 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5047 .Authorization(TAG_NO_AUTH_REQUIRED)
5048 .AesEncryptionKey(128)
5049 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5050 .Padding(PaddingMode::NONE)
5051 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5052 .Authorization(TAG_CALLER_NONCE)));
5053
5054 string aad = "foobar";
5055 string message = "123456789012345678901234567890123456";
5056 string nonce1 = "000000000000";
5057 string nonce2 = "111111111111";
5058 string nonce3 = "222222222222";
5059
5060 string ciphertext1 =
5061 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
5062 string ciphertext2 =
5063 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
5064 string ciphertext3 =
5065 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
5066
5067 ASSERT_NE(ciphertext1, ciphertext2);
5068 ASSERT_NE(ciphertext1, ciphertext3);
5069 ASSERT_NE(ciphertext2, ciphertext3);
5070}
5071
5072/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005073 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
5074 *
5075 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
5076 */
5077TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
5078 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5079 .Authorization(TAG_NO_AUTH_REQUIRED)
5080 .AesEncryptionKey(128)
5081 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5082 .Padding(PaddingMode::NONE)
5083 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5084
5085 string aad = "foobar";
5086 string message = "123456789012345678901234567890123456";
5087
5088 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5089 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5090 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5091
5092 ASSERT_NE(ciphertext1, ciphertext2);
5093 ASSERT_NE(ciphertext1, ciphertext3);
5094 ASSERT_NE(ciphertext2, ciphertext3);
5095}
5096
5097/*
Selene Huang31ab4042020-04-29 04:22:39 -07005098 * EncryptionOperationsTest.AesGcmTooShortTag
5099 *
5100 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
5101 */
5102TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
5103 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5104 .Authorization(TAG_NO_AUTH_REQUIRED)
5105 .AesEncryptionKey(128)
5106 .BlockMode(BlockMode::GCM)
5107 .Padding(PaddingMode::NONE)
5108 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5109 string message = "123456789012345678901234567890123456";
5110 auto params = AuthorizationSetBuilder()
5111 .BlockMode(BlockMode::GCM)
5112 .Padding(PaddingMode::NONE)
5113 .Authorization(TAG_MAC_LENGTH, 96);
5114
5115 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
5116}
5117
5118/*
5119 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
5120 *
5121 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
5122 */
5123TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
5124 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5125 .Authorization(TAG_NO_AUTH_REQUIRED)
5126 .AesEncryptionKey(128)
5127 .BlockMode(BlockMode::GCM)
5128 .Padding(PaddingMode::NONE)
5129 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5130 string aad = "foobar";
5131 string message = "123456789012345678901234567890123456";
5132 auto params = AuthorizationSetBuilder()
5133 .BlockMode(BlockMode::GCM)
5134 .Padding(PaddingMode::NONE)
5135 .Authorization(TAG_MAC_LENGTH, 128);
5136
Selene Huang31ab4042020-04-29 04:22:39 -07005137 // Encrypt
5138 AuthorizationSet begin_out_params;
5139 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5140 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005141 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005142
5143 AuthorizationSet finish_out_params;
5144 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005145 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5146 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005147
5148 params = AuthorizationSetBuilder()
5149 .Authorizations(begin_out_params)
5150 .BlockMode(BlockMode::GCM)
5151 .Padding(PaddingMode::NONE)
5152 .Authorization(TAG_MAC_LENGTH, 96);
5153
5154 // Decrypt.
5155 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5156}
5157
5158/*
5159 * EncryptionOperationsTest.AesGcmCorruptKey
5160 *
5161 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5162 */
5163TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5164 const uint8_t nonce_bytes[] = {
5165 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5166 };
5167 string nonce = make_string(nonce_bytes);
5168 const uint8_t ciphertext_bytes[] = {
5169 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5170 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5171 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5172 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5173 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5174 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5175 };
5176 string ciphertext = make_string(ciphertext_bytes);
5177
5178 auto params = AuthorizationSetBuilder()
5179 .BlockMode(BlockMode::GCM)
5180 .Padding(PaddingMode::NONE)
5181 .Authorization(TAG_MAC_LENGTH, 128)
5182 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5183
5184 auto import_params = AuthorizationSetBuilder()
5185 .Authorization(TAG_NO_AUTH_REQUIRED)
5186 .AesEncryptionKey(128)
5187 .BlockMode(BlockMode::GCM)
5188 .Padding(PaddingMode::NONE)
5189 .Authorization(TAG_CALLER_NONCE)
5190 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5191
5192 // Import correct key and decrypt
5193 const uint8_t key_bytes[] = {
5194 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5195 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5196 };
5197 string key = make_string(key_bytes);
5198 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5199 string plaintext = DecryptMessage(ciphertext, params);
5200 CheckedDeleteKey();
5201
5202 // Corrupt key and attempt to decrypt
5203 key[0] = 0;
5204 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5205 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5206 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5207 CheckedDeleteKey();
5208}
5209
5210/*
5211 * EncryptionOperationsTest.AesGcmAadNoData
5212 *
5213 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5214 * encrypt.
5215 */
5216TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5217 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5218 .Authorization(TAG_NO_AUTH_REQUIRED)
5219 .AesEncryptionKey(128)
5220 .BlockMode(BlockMode::GCM)
5221 .Padding(PaddingMode::NONE)
5222 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5223
5224 string aad = "1234567890123456";
5225 auto params = AuthorizationSetBuilder()
5226 .BlockMode(BlockMode::GCM)
5227 .Padding(PaddingMode::NONE)
5228 .Authorization(TAG_MAC_LENGTH, 128);
5229
Selene Huang31ab4042020-04-29 04:22:39 -07005230 // Encrypt
5231 AuthorizationSet begin_out_params;
5232 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5233 string ciphertext;
5234 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005235 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5236 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005237 EXPECT_TRUE(finish_out_params.empty());
5238
5239 // Grab nonce
5240 params.push_back(begin_out_params);
5241
5242 // Decrypt.
5243 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005244 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005245 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005246 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005247
5248 EXPECT_TRUE(finish_out_params.empty());
5249
5250 EXPECT_EQ("", plaintext);
5251}
5252
5253/*
5254 * EncryptionOperationsTest.AesGcmMultiPartAad
5255 *
5256 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5257 * chunks.
5258 */
5259TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5260 const size_t tag_bits = 128;
5261 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5262 .Authorization(TAG_NO_AUTH_REQUIRED)
5263 .AesEncryptionKey(128)
5264 .BlockMode(BlockMode::GCM)
5265 .Padding(PaddingMode::NONE)
5266 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5267
5268 string message = "123456789012345678901234567890123456";
5269 auto begin_params = AuthorizationSetBuilder()
5270 .BlockMode(BlockMode::GCM)
5271 .Padding(PaddingMode::NONE)
5272 .Authorization(TAG_MAC_LENGTH, tag_bits);
5273 AuthorizationSet begin_out_params;
5274
Selene Huang31ab4042020-04-29 04:22:39 -07005275 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5276
5277 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005278 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5279 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005280 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005281 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5282 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005283
Selene Huang31ab4042020-04-29 04:22:39 -07005284 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005285 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005286
5287 // Grab nonce.
5288 begin_params.push_back(begin_out_params);
5289
5290 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005291 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005292 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005293 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005294 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005295 EXPECT_EQ(message, plaintext);
5296}
5297
5298/*
5299 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5300 *
5301 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5302 */
5303TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5304 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5305 .Authorization(TAG_NO_AUTH_REQUIRED)
5306 .AesEncryptionKey(128)
5307 .BlockMode(BlockMode::GCM)
5308 .Padding(PaddingMode::NONE)
5309 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5310
5311 string message = "123456789012345678901234567890123456";
5312 auto begin_params = AuthorizationSetBuilder()
5313 .BlockMode(BlockMode::GCM)
5314 .Padding(PaddingMode::NONE)
5315 .Authorization(TAG_MAC_LENGTH, 128);
5316 AuthorizationSet begin_out_params;
5317
Selene Huang31ab4042020-04-29 04:22:39 -07005318 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5319
Shawn Willden92d79c02021-02-19 07:31:55 -07005320 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005321 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005322 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5323 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005324
David Drysdaled2cc8c22021-04-15 13:29:45 +01005325 // The failure should have already cancelled the operation.
5326 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5327
Shawn Willden92d79c02021-02-19 07:31:55 -07005328 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005329}
5330
5331/*
5332 * EncryptionOperationsTest.AesGcmBadAad
5333 *
5334 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5335 */
5336TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5337 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5338 .Authorization(TAG_NO_AUTH_REQUIRED)
5339 .AesEncryptionKey(128)
5340 .BlockMode(BlockMode::GCM)
5341 .Padding(PaddingMode::NONE)
5342 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5343
5344 string message = "12345678901234567890123456789012";
5345 auto begin_params = AuthorizationSetBuilder()
5346 .BlockMode(BlockMode::GCM)
5347 .Padding(PaddingMode::NONE)
5348 .Authorization(TAG_MAC_LENGTH, 128);
5349
Selene Huang31ab4042020-04-29 04:22:39 -07005350 // Encrypt
5351 AuthorizationSet begin_out_params;
5352 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005353 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005354 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005355 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005356
5357 // Grab nonce
5358 begin_params.push_back(begin_out_params);
5359
Selene Huang31ab4042020-04-29 04:22:39 -07005360 // Decrypt.
5361 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005362 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005363 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005364 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005365}
5366
5367/*
5368 * EncryptionOperationsTest.AesGcmWrongNonce
5369 *
5370 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5371 */
5372TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5373 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5374 .Authorization(TAG_NO_AUTH_REQUIRED)
5375 .AesEncryptionKey(128)
5376 .BlockMode(BlockMode::GCM)
5377 .Padding(PaddingMode::NONE)
5378 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5379
5380 string message = "12345678901234567890123456789012";
5381 auto begin_params = AuthorizationSetBuilder()
5382 .BlockMode(BlockMode::GCM)
5383 .Padding(PaddingMode::NONE)
5384 .Authorization(TAG_MAC_LENGTH, 128);
5385
Selene Huang31ab4042020-04-29 04:22:39 -07005386 // Encrypt
5387 AuthorizationSet begin_out_params;
5388 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005389 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005390 string ciphertext;
5391 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005392 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005393
5394 // Wrong nonce
5395 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5396
5397 // Decrypt.
5398 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005399 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005400 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005401 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005402
5403 // With wrong nonce, should have gotten garbage plaintext (or none).
5404 EXPECT_NE(message, plaintext);
5405}
5406
5407/*
5408 * EncryptionOperationsTest.AesGcmCorruptTag
5409 *
5410 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5411 */
5412TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5413 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5414 .Authorization(TAG_NO_AUTH_REQUIRED)
5415 .AesEncryptionKey(128)
5416 .BlockMode(BlockMode::GCM)
5417 .Padding(PaddingMode::NONE)
5418 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5419
5420 string aad = "1234567890123456";
5421 string message = "123456789012345678901234567890123456";
5422
5423 auto params = AuthorizationSetBuilder()
5424 .BlockMode(BlockMode::GCM)
5425 .Padding(PaddingMode::NONE)
5426 .Authorization(TAG_MAC_LENGTH, 128);
5427
Selene Huang31ab4042020-04-29 04:22:39 -07005428 // Encrypt
5429 AuthorizationSet begin_out_params;
5430 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005431 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005432 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005433 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005434
5435 // Corrupt tag
5436 ++(*ciphertext.rbegin());
5437
5438 // Grab nonce
5439 params.push_back(begin_out_params);
5440
5441 // Decrypt.
5442 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005443 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005444 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005445 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005446}
5447
5448/*
5449 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5450 *
5451 * Verifies that 3DES is basically functional.
5452 */
5453TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5454 auto auths = AuthorizationSetBuilder()
5455 .TripleDesEncryptionKey(168)
5456 .BlockMode(BlockMode::ECB)
5457 .Authorization(TAG_NO_AUTH_REQUIRED)
5458 .Padding(PaddingMode::NONE);
5459
5460 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5461 // Two-block message.
5462 string message = "1234567890123456";
5463 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5464 string ciphertext1 = EncryptMessage(message, inParams);
5465 EXPECT_EQ(message.size(), ciphertext1.size());
5466
5467 string ciphertext2 = EncryptMessage(string(message), inParams);
5468 EXPECT_EQ(message.size(), ciphertext2.size());
5469
5470 // ECB is deterministic.
5471 EXPECT_EQ(ciphertext1, ciphertext2);
5472
5473 string plaintext = DecryptMessage(ciphertext1, inParams);
5474 EXPECT_EQ(message, plaintext);
5475}
5476
5477/*
5478 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5479 *
5480 * Verifies that CBC keys reject ECB usage.
5481 */
5482TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5483 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5484 .TripleDesEncryptionKey(168)
5485 .BlockMode(BlockMode::CBC)
5486 .Authorization(TAG_NO_AUTH_REQUIRED)
5487 .Padding(PaddingMode::NONE)));
5488
5489 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5490 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5491}
5492
5493/*
5494 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5495 *
5496 * Tests ECB mode with PKCS#7 padding, various message sizes.
5497 */
5498TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5499 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5500 .TripleDesEncryptionKey(168)
5501 .BlockMode(BlockMode::ECB)
5502 .Authorization(TAG_NO_AUTH_REQUIRED)
5503 .Padding(PaddingMode::PKCS7)));
5504
5505 for (size_t i = 0; i < 32; ++i) {
5506 string message(i, 'a');
5507 auto inParams =
5508 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5509 string ciphertext = EncryptMessage(message, inParams);
5510 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5511 string plaintext = DecryptMessage(ciphertext, inParams);
5512 EXPECT_EQ(message, plaintext);
5513 }
5514}
5515
5516/*
5517 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5518 *
5519 * Verifies that keys configured for no padding reject PKCS7 padding
5520 */
5521TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5522 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5523 .TripleDesEncryptionKey(168)
5524 .BlockMode(BlockMode::ECB)
5525 .Authorization(TAG_NO_AUTH_REQUIRED)
5526 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005527 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5528 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005529}
5530
5531/*
5532 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5533 *
5534 * Verifies that corrupted padding is detected.
5535 */
5536TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5537 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5538 .TripleDesEncryptionKey(168)
5539 .BlockMode(BlockMode::ECB)
5540 .Authorization(TAG_NO_AUTH_REQUIRED)
5541 .Padding(PaddingMode::PKCS7)));
5542
5543 string message = "a";
5544 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5545 EXPECT_EQ(8U, ciphertext.size());
5546 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005547
5548 AuthorizationSetBuilder begin_params;
5549 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5550 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07005551
5552 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5553 ++ciphertext[ciphertext.size() / 2];
5554
5555 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5556 string plaintext;
5557 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5558 ErrorCode error = Finish(&plaintext);
5559 if (error == ErrorCode::INVALID_ARGUMENT) {
5560 // This is the expected error, we can exit the test now.
5561 return;
5562 } else {
5563 // Very small chance we got valid decryption, so try again.
5564 ASSERT_EQ(error, ErrorCode::OK);
5565 }
5566 }
5567 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005568}
5569
5570struct TripleDesTestVector {
5571 const char* name;
5572 const KeyPurpose purpose;
5573 const BlockMode block_mode;
5574 const PaddingMode padding_mode;
5575 const char* key;
5576 const char* iv;
5577 const char* input;
5578 const char* output;
5579};
5580
5581// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5582// of the NIST vectors are multiples of the block size.
5583static const TripleDesTestVector kTripleDesTestVectors[] = {
5584 {
5585 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5586 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5587 "", // IV
5588 "329d86bdf1bc5af4", // input
5589 "d946c2756d78633f", // output
5590 },
5591 {
5592 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5593 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5594 "", // IV
5595 "6b1540781b01ce1997adae102dbf3c5b", // input
5596 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5597 },
5598 {
5599 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5600 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5601 "", // IV
5602 "6daad94ce08acfe7", // input
5603 "660e7d32dcc90e79", // output
5604 },
5605 {
5606 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5607 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5608 "", // IV
5609 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5610 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5611 },
5612 {
5613 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5614 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5615 "43f791134c5647ba", // IV
5616 "dcc153cef81d6f24", // input
5617 "92538bd8af18d3ba", // output
5618 },
5619 {
5620 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5621 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5622 "c2e999cb6249023c", // IV
5623 "c689aee38a301bb316da75db36f110b5", // input
5624 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5625 },
5626 {
5627 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5628 PaddingMode::PKCS7,
5629 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5630 "c2e999cb6249023c", // IV
5631 "c689aee38a301bb316da75db36f110b500", // input
5632 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5633 },
5634 {
5635 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5636 PaddingMode::PKCS7,
5637 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5638 "c2e999cb6249023c", // IV
5639 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5640 "c689aee38a301bb316da75db36f110b500", // output
5641 },
5642 {
5643 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5644 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5645 "41746c7e442d3681", // IV
5646 "c53a7b0ec40600fe", // input
5647 "d4f00eb455de1034", // output
5648 },
5649 {
5650 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5651 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5652 "3982bc02c3727d45", // IV
5653 "6006f10adef52991fcc777a1238bbb65", // input
5654 "edae09288e9e3bc05746d872b48e3b29", // output
5655 },
5656};
5657
5658/*
5659 * EncryptionOperationsTest.TripleDesTestVector
5660 *
5661 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5662 */
5663TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5664 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5665 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5666 SCOPED_TRACE(test->name);
5667 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5668 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5669 hex2str(test->output));
5670 }
5671}
5672
5673/*
5674 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5675 *
5676 * Validates CBC mode functionality.
5677 */
5678TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5679 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5680 .TripleDesEncryptionKey(168)
5681 .BlockMode(BlockMode::CBC)
5682 .Authorization(TAG_NO_AUTH_REQUIRED)
5683 .Padding(PaddingMode::NONE)));
5684
5685 ASSERT_GT(key_blob_.size(), 0U);
5686
5687 // Two-block message.
5688 string message = "1234567890123456";
5689 vector<uint8_t> iv1;
5690 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5691 EXPECT_EQ(message.size(), ciphertext1.size());
5692
5693 vector<uint8_t> iv2;
5694 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5695 EXPECT_EQ(message.size(), ciphertext2.size());
5696
5697 // IVs should be random, so ciphertexts should differ.
5698 EXPECT_NE(iv1, iv2);
5699 EXPECT_NE(ciphertext1, ciphertext2);
5700
5701 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5702 EXPECT_EQ(message, plaintext);
5703}
5704
5705/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005706 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5707 *
5708 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5709 */
5710TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5711 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5712 .TripleDesEncryptionKey(168)
5713 .BlockMode(BlockMode::CBC)
5714 .Authorization(TAG_NO_AUTH_REQUIRED)
5715 .Authorization(TAG_CALLER_NONCE)
5716 .Padding(PaddingMode::NONE)));
5717 auto params = AuthorizationSetBuilder()
5718 .BlockMode(BlockMode::CBC)
5719 .Padding(PaddingMode::NONE)
5720 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5721 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5722}
5723
5724/*
Selene Huang31ab4042020-04-29 04:22:39 -07005725 * EncryptionOperationsTest.TripleDesCallerIv
5726 *
5727 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5728 */
5729TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5730 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5731 .TripleDesEncryptionKey(168)
5732 .BlockMode(BlockMode::CBC)
5733 .Authorization(TAG_NO_AUTH_REQUIRED)
5734 .Authorization(TAG_CALLER_NONCE)
5735 .Padding(PaddingMode::NONE)));
5736 string message = "1234567890123456";
5737 vector<uint8_t> iv;
5738 // Don't specify IV, should get a random one.
5739 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5740 EXPECT_EQ(message.size(), ciphertext1.size());
5741 EXPECT_EQ(8U, iv.size());
5742
5743 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5744 EXPECT_EQ(message, plaintext);
5745
5746 // Now specify an IV, should also work.
5747 iv = AidlBuf("abcdefgh");
5748 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5749
5750 // Decrypt with correct IV.
5751 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5752 EXPECT_EQ(message, plaintext);
5753
5754 // Now try with wrong IV.
5755 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5756 EXPECT_NE(message, plaintext);
5757}
5758
5759/*
5760 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5761 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005762 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005763 */
5764TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5765 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5766 .TripleDesEncryptionKey(168)
5767 .BlockMode(BlockMode::CBC)
5768 .Authorization(TAG_NO_AUTH_REQUIRED)
5769 .Padding(PaddingMode::NONE)));
5770
5771 string message = "12345678901234567890123456789012";
5772 vector<uint8_t> iv;
5773 // Don't specify nonce, should get a random one.
5774 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5775 EXPECT_EQ(message.size(), ciphertext1.size());
5776 EXPECT_EQ(8U, iv.size());
5777
5778 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5779 EXPECT_EQ(message, plaintext);
5780
5781 // Now specify a nonce, should fail.
5782 auto input_params = AuthorizationSetBuilder()
5783 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5784 .BlockMode(BlockMode::CBC)
5785 .Padding(PaddingMode::NONE);
5786 AuthorizationSet output_params;
5787 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5788 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5789}
5790
5791/*
5792 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5793 *
5794 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5795 */
5796TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5797 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5798 .TripleDesEncryptionKey(168)
5799 .BlockMode(BlockMode::ECB)
5800 .Authorization(TAG_NO_AUTH_REQUIRED)
5801 .Padding(PaddingMode::NONE)));
5802 // Two-block message.
5803 string message = "1234567890123456";
5804 auto begin_params =
5805 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5806 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5807}
5808
5809/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005810 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005811 *
5812 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5813 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005814TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5815 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5816 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5817 .TripleDesEncryptionKey(168)
5818 .BlockMode(blockMode)
5819 .Authorization(TAG_NO_AUTH_REQUIRED)
5820 .Padding(PaddingMode::NONE)));
5821 // Message is slightly shorter than two blocks.
5822 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005823
David Drysdaled2cc8c22021-04-15 13:29:45 +01005824 auto begin_params =
5825 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5826 AuthorizationSet output_params;
5827 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5828 string ciphertext;
5829 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5830
5831 CheckedDeleteKey();
5832 }
Selene Huang31ab4042020-04-29 04:22:39 -07005833}
5834
5835/*
5836 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5837 *
5838 * Verifies that PKCS7 padding works correctly in CBC mode.
5839 */
5840TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5841 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5842 .TripleDesEncryptionKey(168)
5843 .BlockMode(BlockMode::CBC)
5844 .Authorization(TAG_NO_AUTH_REQUIRED)
5845 .Padding(PaddingMode::PKCS7)));
5846
5847 // Try various message lengths; all should work.
5848 for (size_t i = 0; i < 32; ++i) {
5849 string message(i, 'a');
5850 vector<uint8_t> iv;
5851 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5852 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5853 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5854 EXPECT_EQ(message, plaintext);
5855 }
5856}
5857
5858/*
5859 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5860 *
5861 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5862 */
5863TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5864 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5865 .TripleDesEncryptionKey(168)
5866 .BlockMode(BlockMode::CBC)
5867 .Authorization(TAG_NO_AUTH_REQUIRED)
5868 .Padding(PaddingMode::NONE)));
5869
5870 // Try various message lengths; all should fail.
5871 for (size_t i = 0; i < 32; ++i) {
5872 auto begin_params =
5873 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5874 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5875 }
5876}
5877
5878/*
5879 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5880 *
5881 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5882 */
5883TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5884 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5885 .TripleDesEncryptionKey(168)
5886 .BlockMode(BlockMode::CBC)
5887 .Authorization(TAG_NO_AUTH_REQUIRED)
5888 .Padding(PaddingMode::PKCS7)));
5889
5890 string message = "a";
5891 vector<uint8_t> iv;
5892 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5893 EXPECT_EQ(8U, ciphertext.size());
5894 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005895
5896 auto begin_params = AuthorizationSetBuilder()
5897 .BlockMode(BlockMode::CBC)
5898 .Padding(PaddingMode::PKCS7)
5899 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07005900
5901 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5902 ++ciphertext[ciphertext.size() / 2];
5903 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5904 string plaintext;
5905 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5906 ErrorCode error = Finish(&plaintext);
5907 if (error == ErrorCode::INVALID_ARGUMENT) {
5908 // This is the expected error, we can exit the test now.
5909 return;
5910 } else {
5911 // Very small chance we got valid decryption, so try again.
5912 ASSERT_EQ(error, ErrorCode::OK);
5913 }
5914 }
5915 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005916}
5917
5918/*
5919 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5920 *
5921 * Verifies that 3DES CBC works with many different input sizes.
5922 */
5923TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5924 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5925 .TripleDesEncryptionKey(168)
5926 .BlockMode(BlockMode::CBC)
5927 .Authorization(TAG_NO_AUTH_REQUIRED)
5928 .Padding(PaddingMode::NONE)));
5929
5930 int increment = 7;
5931 string message(240, 'a');
5932 AuthorizationSet input_params =
5933 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5934 AuthorizationSet output_params;
5935 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5936
5937 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005938 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005939 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005940 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5941 EXPECT_EQ(message.size(), ciphertext.size());
5942
5943 // Move TAG_NONCE into input_params
5944 input_params = output_params;
5945 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5946 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5947 output_params.Clear();
5948
5949 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5950 string plaintext;
5951 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005952 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005953 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5954 EXPECT_EQ(ciphertext.size(), plaintext.size());
5955 EXPECT_EQ(message, plaintext);
5956}
5957
5958INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5959
5960typedef KeyMintAidlTestBase MaxOperationsTest;
5961
5962/*
5963 * MaxOperationsTest.TestLimitAes
5964 *
5965 * Verifies that the max uses per boot tag works correctly with AES keys.
5966 */
5967TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01005968 if (SecLevel() == SecurityLevel::STRONGBOX) {
5969 GTEST_SKIP() << "Test not applicable to StrongBox device";
5970 }
Selene Huang31ab4042020-04-29 04:22:39 -07005971
5972 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5973 .Authorization(TAG_NO_AUTH_REQUIRED)
5974 .AesEncryptionKey(128)
5975 .EcbMode()
5976 .Padding(PaddingMode::NONE)
5977 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5978
5979 string message = "1234567890123456";
5980
5981 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5982
5983 EncryptMessage(message, params);
5984 EncryptMessage(message, params);
5985 EncryptMessage(message, params);
5986
5987 // Fourth time should fail.
5988 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5989}
5990
5991/*
Qi Wud22ec842020-11-26 13:27:53 +08005992 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005993 *
5994 * Verifies that the max uses per boot tag works correctly with RSA keys.
5995 */
5996TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01005997 if (SecLevel() == SecurityLevel::STRONGBOX) {
5998 GTEST_SKIP() << "Test not applicable to StrongBox device";
5999 }
Selene Huang31ab4042020-04-29 04:22:39 -07006000
6001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6002 .Authorization(TAG_NO_AUTH_REQUIRED)
6003 .RsaSigningKey(1024, 65537)
6004 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006005 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
6006 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006007
6008 string message = "1234567890123456";
6009
6010 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6011
6012 SignMessage(message, params);
6013 SignMessage(message, params);
6014 SignMessage(message, params);
6015
6016 // Fourth time should fail.
6017 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6018}
6019
6020INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6021
Qi Wud22ec842020-11-26 13:27:53 +08006022typedef KeyMintAidlTestBase UsageCountLimitTest;
6023
6024/*
Qi Wubeefae42021-01-28 23:16:37 +08006025 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006026 *
Qi Wubeefae42021-01-28 23:16:37 +08006027 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006028 */
Qi Wubeefae42021-01-28 23:16:37 +08006029TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006030 if (SecLevel() == SecurityLevel::STRONGBOX) {
6031 GTEST_SKIP() << "Test not applicable to StrongBox device";
6032 }
Qi Wud22ec842020-11-26 13:27:53 +08006033
6034 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6035 .Authorization(TAG_NO_AUTH_REQUIRED)
6036 .AesEncryptionKey(128)
6037 .EcbMode()
6038 .Padding(PaddingMode::NONE)
6039 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
6040
6041 // Check the usage count limit tag appears in the authorizations.
6042 AuthorizationSet auths;
6043 for (auto& entry : key_characteristics_) {
6044 auths.push_back(AuthorizationSet(entry.authorizations));
6045 }
6046 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6047 << "key usage count limit " << 1U << " missing";
6048
6049 string message = "1234567890123456";
6050 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6051
Qi Wubeefae42021-01-28 23:16:37 +08006052 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6053 AuthorizationSet keystore_auths =
6054 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6055
Qi Wud22ec842020-11-26 13:27:53 +08006056 // First usage of AES key should work.
6057 EncryptMessage(message, params);
6058
Qi Wud22ec842020-11-26 13:27:53 +08006059 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6060 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6061 // must be invalidated from secure storage (such as RPMB partition).
6062 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6063 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006064 // Usage count limit tag is enforced by keystore, keymint does nothing.
6065 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08006066 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6067 }
6068}
6069
6070/*
Qi Wubeefae42021-01-28 23:16:37 +08006071 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006072 *
Qi Wubeefae42021-01-28 23:16:37 +08006073 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006074 */
Qi Wubeefae42021-01-28 23:16:37 +08006075TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006076 if (SecLevel() == SecurityLevel::STRONGBOX) {
6077 GTEST_SKIP() << "Test not applicable to StrongBox device";
6078 }
Qi Wubeefae42021-01-28 23:16:37 +08006079
6080 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6081 .Authorization(TAG_NO_AUTH_REQUIRED)
6082 .AesEncryptionKey(128)
6083 .EcbMode()
6084 .Padding(PaddingMode::NONE)
6085 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
6086
6087 // Check the usage count limit tag appears in the authorizations.
6088 AuthorizationSet auths;
6089 for (auto& entry : key_characteristics_) {
6090 auths.push_back(AuthorizationSet(entry.authorizations));
6091 }
6092 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6093 << "key usage count limit " << 3U << " missing";
6094
6095 string message = "1234567890123456";
6096 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6097
6098 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6099 AuthorizationSet keystore_auths =
6100 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6101
6102 EncryptMessage(message, params);
6103 EncryptMessage(message, params);
6104 EncryptMessage(message, params);
6105
6106 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6107 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6108 // must be invalidated from secure storage (such as RPMB partition).
6109 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6110 } else {
6111 // Usage count limit tag is enforced by keystore, keymint does nothing.
6112 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
6113 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6114 }
6115}
6116
6117/*
6118 * UsageCountLimitTest.TestSingleUseRsa
6119 *
6120 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
6121 */
6122TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006123 if (SecLevel() == SecurityLevel::STRONGBOX) {
6124 GTEST_SKIP() << "Test not applicable to StrongBox device";
6125 }
Qi Wud22ec842020-11-26 13:27:53 +08006126
6127 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6128 .Authorization(TAG_NO_AUTH_REQUIRED)
6129 .RsaSigningKey(1024, 65537)
6130 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006131 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6132 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08006133
6134 // Check the usage count limit tag appears in the authorizations.
6135 AuthorizationSet auths;
6136 for (auto& entry : key_characteristics_) {
6137 auths.push_back(AuthorizationSet(entry.authorizations));
6138 }
6139 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6140 << "key usage count limit " << 1U << " missing";
6141
6142 string message = "1234567890123456";
6143 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6144
Qi Wubeefae42021-01-28 23:16:37 +08006145 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6146 AuthorizationSet keystore_auths =
6147 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6148
Qi Wud22ec842020-11-26 13:27:53 +08006149 // First usage of RSA key should work.
6150 SignMessage(message, params);
6151
Qi Wud22ec842020-11-26 13:27:53 +08006152 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6153 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6154 // must be invalidated from secure storage (such as RPMB partition).
6155 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6156 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006157 // Usage count limit tag is enforced by keystore, keymint does nothing.
6158 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
6159 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6160 }
6161}
6162
6163/*
6164 * UsageCountLimitTest.TestLimitUseRsa
6165 *
6166 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
6167 */
6168TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006169 if (SecLevel() == SecurityLevel::STRONGBOX) {
6170 GTEST_SKIP() << "Test not applicable to StrongBox device";
6171 }
Qi Wubeefae42021-01-28 23:16:37 +08006172
6173 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6174 .Authorization(TAG_NO_AUTH_REQUIRED)
6175 .RsaSigningKey(1024, 65537)
6176 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006177 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6178 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006179
6180 // Check the usage count limit tag appears in the authorizations.
6181 AuthorizationSet auths;
6182 for (auto& entry : key_characteristics_) {
6183 auths.push_back(AuthorizationSet(entry.authorizations));
6184 }
6185 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6186 << "key usage count limit " << 3U << " missing";
6187
6188 string message = "1234567890123456";
6189 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6190
6191 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6192 AuthorizationSet keystore_auths =
6193 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6194
6195 SignMessage(message, params);
6196 SignMessage(message, params);
6197 SignMessage(message, params);
6198
6199 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6200 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6201 // must be invalidated from secure storage (such as RPMB partition).
6202 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6203 } else {
6204 // Usage count limit tag is enforced by keystore, keymint does nothing.
6205 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006206 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6207 }
6208}
6209
Qi Wu8e727f72021-02-11 02:49:33 +08006210/*
6211 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6212 *
6213 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6214 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6215 * in hardware.
6216 */
6217TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01006218 if (SecLevel() == SecurityLevel::STRONGBOX) {
6219 GTEST_SKIP() << "Test not applicable to StrongBox device";
6220 }
Qi Wu8e727f72021-02-11 02:49:33 +08006221
6222 auto error = GenerateKey(AuthorizationSetBuilder()
6223 .RsaSigningKey(2048, 65537)
6224 .Digest(Digest::NONE)
6225 .Padding(PaddingMode::NONE)
6226 .Authorization(TAG_NO_AUTH_REQUIRED)
6227 .Authorization(TAG_ROLLBACK_RESISTANCE)
6228 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006229 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6230 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08006231 }
David Drysdale513bf122021-10-06 11:53:13 +01006232
6233 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6234 ASSERT_EQ(ErrorCode::OK, error);
6235 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6236 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6237 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6238
6239 // The KeyMint should also enforce single use key in hardware when it supports rollback
6240 // resistance.
6241 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6242 .Authorization(TAG_NO_AUTH_REQUIRED)
6243 .RsaSigningKey(1024, 65537)
6244 .NoDigestOrPadding()
6245 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6246 .SetDefaultValidity()));
6247
6248 // Check the usage count limit tag appears in the hardware authorizations.
6249 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6250 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6251 << "key usage count limit " << 1U << " missing";
6252
6253 string message = "1234567890123456";
6254 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6255
6256 // First usage of RSA key should work.
6257 SignMessage(message, params);
6258
6259 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6260 // must be invalidated from secure storage (such as RPMB partition).
6261 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08006262}
6263
Qi Wud22ec842020-11-26 13:27:53 +08006264INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6265
David Drysdale7de9feb2021-03-05 14:56:19 +00006266typedef KeyMintAidlTestBase GetHardwareInfoTest;
6267
6268TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6269 // Retrieving hardware info should give the same result each time.
6270 KeyMintHardwareInfo info;
6271 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6272 KeyMintHardwareInfo info2;
6273 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6274 EXPECT_EQ(info, info2);
6275}
6276
6277INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6278
Selene Huang31ab4042020-04-29 04:22:39 -07006279typedef KeyMintAidlTestBase AddEntropyTest;
6280
6281/*
6282 * AddEntropyTest.AddEntropy
6283 *
6284 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6285 * is actually added.
6286 */
6287TEST_P(AddEntropyTest, AddEntropy) {
6288 string data = "foo";
6289 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6290}
6291
6292/*
6293 * AddEntropyTest.AddEmptyEntropy
6294 *
6295 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6296 */
6297TEST_P(AddEntropyTest, AddEmptyEntropy) {
6298 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6299}
6300
6301/*
6302 * AddEntropyTest.AddLargeEntropy
6303 *
6304 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6305 */
6306TEST_P(AddEntropyTest, AddLargeEntropy) {
6307 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6308}
6309
David Drysdalebb3d85e2021-04-13 11:15:51 +01006310/*
6311 * AddEntropyTest.AddTooLargeEntropy
6312 *
6313 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6314 */
6315TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6316 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6317 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6318}
6319
Selene Huang31ab4042020-04-29 04:22:39 -07006320INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6321
Selene Huang31ab4042020-04-29 04:22:39 -07006322typedef KeyMintAidlTestBase KeyDeletionTest;
6323
6324/**
6325 * KeyDeletionTest.DeleteKey
6326 *
6327 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6328 * valid key blob.
6329 */
6330TEST_P(KeyDeletionTest, DeleteKey) {
6331 auto error = GenerateKey(AuthorizationSetBuilder()
6332 .RsaSigningKey(2048, 65537)
6333 .Digest(Digest::NONE)
6334 .Padding(PaddingMode::NONE)
6335 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006336 .Authorization(TAG_ROLLBACK_RESISTANCE)
6337 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006338 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6339 GTEST_SKIP() << "Rollback resistance not supported";
6340 }
Selene Huang31ab4042020-04-29 04:22:39 -07006341
6342 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006343 ASSERT_EQ(ErrorCode::OK, error);
6344 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6345 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006346
David Drysdale513bf122021-10-06 11:53:13 +01006347 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07006348
David Drysdale513bf122021-10-06 11:53:13 +01006349 string message = "12345678901234567890123456789012";
6350 AuthorizationSet begin_out_params;
6351 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6352 Begin(KeyPurpose::SIGN, key_blob_,
6353 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6354 &begin_out_params));
6355 AbortIfNeeded();
6356 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006357}
6358
6359/**
6360 * KeyDeletionTest.DeleteInvalidKey
6361 *
6362 * This test checks that the HAL excepts invalid key blobs..
6363 */
6364TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6365 // Generate key just to check if rollback protection is implemented
6366 auto error = GenerateKey(AuthorizationSetBuilder()
6367 .RsaSigningKey(2048, 65537)
6368 .Digest(Digest::NONE)
6369 .Padding(PaddingMode::NONE)
6370 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006371 .Authorization(TAG_ROLLBACK_RESISTANCE)
6372 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006373 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6374 GTEST_SKIP() << "Rollback resistance not supported";
6375 }
Selene Huang31ab4042020-04-29 04:22:39 -07006376
6377 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006378 ASSERT_EQ(ErrorCode::OK, error);
6379 AuthorizationSet enforced(SecLevelAuthorizations());
6380 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006381
David Drysdale513bf122021-10-06 11:53:13 +01006382 // Delete the key we don't care about the result at this point.
6383 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07006384
David Drysdale513bf122021-10-06 11:53:13 +01006385 // Now create an invalid key blob and delete it.
6386 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07006387
David Drysdale513bf122021-10-06 11:53:13 +01006388 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07006389}
6390
6391/**
6392 * KeyDeletionTest.DeleteAllKeys
6393 *
6394 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6395 *
6396 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6397 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6398 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6399 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6400 * credentials stored in Keystore/Keymint.
6401 */
6402TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01006403 if (!arm_deleteAllKeys) {
6404 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
6405 return;
6406 }
Selene Huang31ab4042020-04-29 04:22:39 -07006407 auto error = GenerateKey(AuthorizationSetBuilder()
6408 .RsaSigningKey(2048, 65537)
6409 .Digest(Digest::NONE)
6410 .Padding(PaddingMode::NONE)
6411 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06006412 .Authorization(TAG_ROLLBACK_RESISTANCE)
6413 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006414 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6415 GTEST_SKIP() << "Rollback resistance not supported";
6416 }
Selene Huang31ab4042020-04-29 04:22:39 -07006417
6418 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006419 ASSERT_EQ(ErrorCode::OK, error);
6420 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6421 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006422
David Drysdale513bf122021-10-06 11:53:13 +01006423 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07006424
David Drysdale513bf122021-10-06 11:53:13 +01006425 string message = "12345678901234567890123456789012";
6426 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07006427
David Drysdale513bf122021-10-06 11:53:13 +01006428 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6429 Begin(KeyPurpose::SIGN, key_blob_,
6430 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6431 &begin_out_params));
6432 AbortIfNeeded();
6433 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006434}
6435
6436INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6437
David Drysdaled2cc8c22021-04-15 13:29:45 +01006438typedef KeyMintAidlTestBase KeyUpgradeTest;
6439
6440/**
6441 * KeyUpgradeTest.UpgradeInvalidKey
6442 *
6443 * This test checks that the HAL excepts invalid key blobs..
6444 */
6445TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6446 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6447
6448 std::vector<uint8_t> new_blob;
6449 Status result = keymint_->upgradeKey(key_blob,
6450 AuthorizationSetBuilder()
6451 .Authorization(TAG_APPLICATION_ID, "clientid")
6452 .Authorization(TAG_APPLICATION_DATA, "appdata")
6453 .vector_data(),
6454 &new_blob);
6455 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6456}
6457
6458INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6459
Selene Huang31ab4042020-04-29 04:22:39 -07006460using UpgradeKeyTest = KeyMintAidlTestBase;
6461
6462/*
6463 * UpgradeKeyTest.UpgradeKey
6464 *
6465 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6466 */
6467TEST_P(UpgradeKeyTest, UpgradeKey) {
6468 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6469 .AesEncryptionKey(128)
6470 .Padding(PaddingMode::NONE)
6471 .Authorization(TAG_NO_AUTH_REQUIRED)));
6472
6473 auto result = UpgradeKey(key_blob_);
6474
6475 // Key doesn't need upgrading. Should get okay, but no new key blob.
6476 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6477}
6478
6479INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6480
6481using ClearOperationsTest = KeyMintAidlTestBase;
6482
6483/*
6484 * ClearSlotsTest.TooManyOperations
6485 *
6486 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6487 * operations are started without being finished or aborted. Also verifies
6488 * that aborting the operations clears the operations.
6489 *
6490 */
6491TEST_P(ClearOperationsTest, TooManyOperations) {
6492 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6493 .Authorization(TAG_NO_AUTH_REQUIRED)
6494 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006495 .Padding(PaddingMode::NONE)
6496 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006497
6498 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6499 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006500 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006501 AuthorizationSet out_params;
6502 ErrorCode result;
6503 size_t i;
6504
6505 for (i = 0; i < max_operations; i++) {
6506 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6507 if (ErrorCode::OK != result) {
6508 break;
6509 }
6510 }
6511 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6512 // Try again just in case there's a weird overflow bug
6513 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6514 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6515 for (size_t j = 0; j < i; j++) {
6516 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6517 << "Aboort failed for i = " << j << std::endl;
6518 }
6519 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6520 AbortIfNeeded();
6521}
6522
6523INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6524
6525typedef KeyMintAidlTestBase TransportLimitTest;
6526
6527/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006528 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006529 *
6530 * Verifies that passing input data to finish succeeds as expected.
6531 */
6532TEST_P(TransportLimitTest, LargeFinishInput) {
6533 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6534 .Authorization(TAG_NO_AUTH_REQUIRED)
6535 .AesEncryptionKey(128)
6536 .BlockMode(BlockMode::ECB)
6537 .Padding(PaddingMode::NONE)));
6538
6539 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6540 auto cipher_params =
6541 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6542
6543 AuthorizationSet out_params;
6544 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6545
6546 string plain_message = std::string(1 << msg_size, 'x');
6547 string encrypted_message;
6548 auto rc = Finish(plain_message, &encrypted_message);
6549
6550 EXPECT_EQ(ErrorCode::OK, rc);
6551 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6552 << "Encrypt finish returned OK, but did not consume all of the given input";
6553 cipher_params.push_back(out_params);
6554
6555 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6556
6557 string decrypted_message;
6558 rc = Finish(encrypted_message, &decrypted_message);
6559 EXPECT_EQ(ErrorCode::OK, rc);
6560 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6561 << "Decrypt finish returned OK, did not consume all of the given input";
6562 }
6563}
6564
6565INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6566
David Zeuthene0c40892021-01-08 12:54:11 -05006567typedef KeyMintAidlTestBase KeyAgreementTest;
6568
David Drysdalee76045d2021-12-13 16:01:21 +00006569int CurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05006570 switch (curve) {
6571 case EcCurve::P_224:
6572 return NID_secp224r1;
6573 case EcCurve::P_256:
6574 return NID_X9_62_prime256v1;
6575 case EcCurve::P_384:
6576 return NID_secp384r1;
6577 case EcCurve::P_521:
6578 return NID_secp521r1;
6579 }
6580}
6581
6582/*
6583 * KeyAgreementTest.Ecdh
6584 *
6585 * Verifies that ECDH works for all curves
6586 */
6587TEST_P(KeyAgreementTest, Ecdh) {
6588 // Because it's possible to use this API with keys on different curves, we
6589 // check all N^2 combinations where N is the number of supported
6590 // curves.
6591 //
6592 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6593 // lot more curves we can be smart about things and just pick |otherCurve| so
6594 // it's not |curve| and that way we end up with only 2*N runs
6595 //
6596 for (auto curve : ValidCurves()) {
6597 for (auto localCurve : ValidCurves()) {
6598 // Generate EC key locally (with access to private key material)
6599 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
David Drysdalee76045d2021-12-13 16:01:21 +00006600 int curveName = CurveToOpenSslCurveName(localCurve);
David Zeuthene0c40892021-01-08 12:54:11 -05006601 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6602 ASSERT_NE(group, nullptr);
6603 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6604 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6605 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6606 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6607
6608 // Get encoded form of the public part of the locally generated key...
6609 unsigned char* p = nullptr;
6610 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6611 ASSERT_GT(encodedPublicKeySize, 0);
6612 vector<uint8_t> encodedPublicKey(
6613 reinterpret_cast<const uint8_t*>(p),
6614 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6615 OPENSSL_free(p);
6616
6617 // Generate EC key in KeyMint (only access to public key material)
6618 vector<uint8_t> challenge = {0x41, 0x42};
6619 EXPECT_EQ(
6620 ErrorCode::OK,
6621 GenerateKey(AuthorizationSetBuilder()
6622 .Authorization(TAG_NO_AUTH_REQUIRED)
6623 .Authorization(TAG_EC_CURVE, curve)
6624 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6625 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6626 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006627 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6628 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006629 << "Failed to generate key";
6630 ASSERT_GT(cert_chain_.size(), 0);
6631 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6632 ASSERT_NE(kmKeyCert, nullptr);
6633 // Check that keyAgreement (bit 4) is set in KeyUsage
6634 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6635 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6636 ASSERT_NE(kmPkey, nullptr);
6637 if (dump_Attestations) {
6638 for (size_t n = 0; n < cert_chain_.size(); n++) {
6639 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6640 }
6641 }
6642
6643 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6644 if (curve != localCurve) {
6645 // If the keys are using different curves KeyMint should fail with
6646 // ErrorCode:INVALID_ARGUMENT. Check that.
6647 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6648 string ZabFromKeyMintStr;
6649 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6650 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6651 &ZabFromKeyMintStr));
6652
6653 } else {
6654 // Otherwise if the keys are using the same curve, it should work.
6655 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6656 string ZabFromKeyMintStr;
6657 EXPECT_EQ(ErrorCode::OK,
6658 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6659 &ZabFromKeyMintStr));
6660 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6661
6662 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6663 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6664 ASSERT_NE(ctx, nullptr);
6665 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6666 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6667 size_t ZabFromTestLen = 0;
6668 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6669 vector<uint8_t> ZabFromTest;
6670 ZabFromTest.resize(ZabFromTestLen);
6671 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6672
6673 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6674 }
6675
6676 CheckedDeleteKey();
6677 }
6678 }
6679}
6680
6681INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6682
David Drysdaled2cc8c22021-04-15 13:29:45 +01006683using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6684
6685// This is a problematic test, as it can render the device under test permanently unusable.
6686// Re-enable and run at your own risk.
6687TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6688 auto result = DestroyAttestationIds();
6689 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6690}
6691
6692INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6693
Shawn Willdend659c7c2021-02-19 14:51:51 -07006694using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006695
David Drysdaledb0dcf52021-05-18 11:43:31 +01006696/*
6697 * EarlyBootKeyTest.CreateEarlyBootKeys
6698 *
6699 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6700 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006701TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01006702 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006703 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6704 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6705
David Drysdaleadfe6112021-05-27 12:00:53 +01006706 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6707 ASSERT_GT(keyData.blob.size(), 0U);
6708 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6709 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6710 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006711 CheckedDeleteKey(&aesKeyData.blob);
6712 CheckedDeleteKey(&hmacKeyData.blob);
6713 CheckedDeleteKey(&rsaKeyData.blob);
6714 CheckedDeleteKey(&ecdsaKeyData.blob);
6715}
6716
David Drysdaledb0dcf52021-05-18 11:43:31 +01006717/*
David Drysdaleadfe6112021-05-27 12:00:53 +01006718 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6719 *
6720 * Verifies that creating an early boot key with attestation succeeds.
6721 */
6722TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6723 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6724 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6725 builder->AttestationChallenge("challenge");
6726 builder->AttestationApplicationId("app_id");
6727 });
6728
6729 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6730 ASSERT_GT(keyData.blob.size(), 0U);
6731 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6732 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6733 }
6734 CheckedDeleteKey(&aesKeyData.blob);
6735 CheckedDeleteKey(&hmacKeyData.blob);
6736 CheckedDeleteKey(&rsaKeyData.blob);
6737 CheckedDeleteKey(&ecdsaKeyData.blob);
6738}
6739
6740/*
6741 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01006742 *
6743 * Verifies that using early boot keys at a later stage fails.
6744 */
6745TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6746 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6747 .Authorization(TAG_NO_AUTH_REQUIRED)
6748 .Authorization(TAG_EARLY_BOOT_ONLY)
6749 .HmacKey(128)
6750 .Digest(Digest::SHA_2_256)
6751 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6752 AuthorizationSet output_params;
6753 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6754 AuthorizationSetBuilder()
6755 .Digest(Digest::SHA_2_256)
6756 .Authorization(TAG_MAC_LENGTH, 256),
6757 &output_params));
6758}
6759
6760/*
6761 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6762 *
6763 * Verifies that importing early boot keys fails.
6764 */
6765TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6766 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6767 .Authorization(TAG_NO_AUTH_REQUIRED)
6768 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01006769 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01006770 .Digest(Digest::SHA_2_256)
6771 .SetDefaultValidity(),
6772 KeyFormat::PKCS8, ec_256_key));
6773}
6774
David Drysdaled2cc8c22021-04-15 13:29:45 +01006775// 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 +00006776// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6777// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6778// early boot, so you'll have to reboot between runs.
6779TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6780 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6781 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6782 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6783 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6784 EXPECT_TRUE(
6785 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6786 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6787 EXPECT_TRUE(
6788 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6789
6790 // Should be able to use keys, since early boot has not ended
6791 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6792 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6793 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6794 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6795
6796 // End early boot
6797 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6798 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6799
6800 // Should not be able to use already-created keys.
6801 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6802 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6803 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6804 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6805
6806 CheckedDeleteKey(&aesKeyData.blob);
6807 CheckedDeleteKey(&hmacKeyData.blob);
6808 CheckedDeleteKey(&rsaKeyData.blob);
6809 CheckedDeleteKey(&ecdsaKeyData.blob);
6810
6811 // Should not be able to create new keys
6812 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6813 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6814
6815 CheckedDeleteKey(&aesKeyData.blob);
6816 CheckedDeleteKey(&hmacKeyData.blob);
6817 CheckedDeleteKey(&rsaKeyData.blob);
6818 CheckedDeleteKey(&ecdsaKeyData.blob);
6819}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006820
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006821INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6822
Shawn Willdend659c7c2021-02-19 14:51:51 -07006823using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006824
6825// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6826// between runs... and on most test devices there are no enrolled credentials so it can't be
6827// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6828// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6829// a manual test process, which includes unlocking between runs, which is why it's included here.
6830// Well, that and the fact that it's the only test we can do without also making calls into the
6831// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6832// implications might be, so that may or may not be a solution.
6833TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6834 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6835 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6836
6837 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6838 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6839 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6840 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6841
6842 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006843 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006844 ASSERT_EQ(ErrorCode::OK, rc);
6845 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6846 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6847 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6848 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6849
6850 CheckedDeleteKey(&aesKeyData.blob);
6851 CheckedDeleteKey(&hmacKeyData.blob);
6852 CheckedDeleteKey(&rsaKeyData.blob);
6853 CheckedDeleteKey(&ecdsaKeyData.blob);
6854}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006855
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006856INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6857
Janis Danisevskis24c04702020-12-16 18:28:39 -08006858} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006859
6860int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006861 std::cout << "Testing ";
6862 auto halInstances =
6863 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6864 std::cout << "HAL instances:\n";
6865 for (auto& entry : halInstances) {
6866 std::cout << " " << entry << '\n';
6867 }
6868
Selene Huang31ab4042020-04-29 04:22:39 -07006869 ::testing::InitGoogleTest(&argc, argv);
6870 for (int i = 1; i < argc; ++i) {
6871 if (argv[i][0] == '-') {
6872 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006873 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6874 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006875 }
6876 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006877 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6878 dump_Attestations = true;
6879 } else {
6880 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006881 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00006882 if (std::string(argv[i]) == "--skip_boot_pl_check") {
6883 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
6884 // be run in emulated environments that don't have the normal bootloader
6885 // interactions.
6886 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
6887 }
Selene Huang31ab4042020-04-29 04:22:39 -07006888 }
6889 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006890 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006891}