blob: 2e0759040f7ab1e33f329b0f044f8aa542342f3d [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
Seth Moore7a55ae32021-06-23 14:28:11 -070072// The maximum number of times we'll attempt to verify that corruption
73// of an ecrypted blob results in an error. Retries are necessary as there
74// is a small (roughly 1/256) chance that corrupting ciphertext still results
75// in valid PKCS7 padding.
76constexpr size_t kMaxPaddingCorruptionRetries = 8;
77
Selene Huang31ab4042020-04-29 04:22:39 -070078template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000079bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
80 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070081 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080082 if (auto p = authorizationValue(ttag, param)) {
83 return *p == expected_value;
84 }
85 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070086 });
87 return (it != set.end());
88}
89
90template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000091bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070092 auto it = std::find_if(set.begin(), set.end(),
93 [&](const KeyParameter& param) { return param.tag == tag; });
94 return (it != set.end());
95}
96
97constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
98 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
99 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
100 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
101 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
102 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
103 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
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
114string hex2str(string a) {
115 string b;
116 size_t num = a.size() / 2;
117 b.resize(num);
118 for (size_t i = 0; i < num; i++) {
119 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
120 }
121 return b;
122}
123
David Drysdaled2cc8c22021-04-15 13:29:45 +0100124string rsa_key = hex2str(
125 // RFC 5208 s5
126 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
127 "020100" // INTEGER length 1 value 0x00 (version)
128 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
129 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
130 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
131 "0500" // NULL (parameters)
132 // } end SEQUENCE (AlgorithmIdentifier)
133 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
134 // RFC 8017 A.1.2
135 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
136 "020100" // INTEGER length 1 value 0x00 (version)
137 "028181" // INTEGER length 0x81 value (modulus) ...
138 "00c6095409047d8634812d5a218176e4"
139 "5c41d60a75b13901f234226cffe77652"
140 "1c5a77b9e389417b71c0b6a44d13afe4"
141 "e4a2805d46c9da2935adb1ff0c1f24ea"
142 "06e62b20d776430a4d435157233c6f91"
143 "6783c30e310fcbd89b85c2d567711697"
144 "85ac12bca244abda72bfb19fc44d27c8"
145 "1e1d92de284f4061edfd99280745ea6d"
146 "25"
147 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
148 "028180" // INTEGER length 0x80 (privateExponent) value...
149 "1be0f04d9cae3718691f035338308e91"
150 "564b55899ffb5084d2460e6630257e05"
151 "b3ceab02972dfabcd6ce5f6ee2589eb6"
152 "7911ed0fac16e43a444b8c861e544a05"
153 "93365772f8baf6b22fc9e3c5f1024b06"
154 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
155 "ace7240290bef16c0b3f7f3cdd64ce3a"
156 "b5912cf6e32f39ab188358afcccd8081"
157 "0241" // INTEGER length 0x41 (prime1)
158 "00e4b49ef50f765d3b24dde01aceaaf1"
159 "30f2c76670a91a61ae08af497b4a82be"
160 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
161 "8c92bfab137fba2285227b83c342ff7c"
162 "55"
163 "0241" // INTEGER length 0x41 (prime2)
164 "00ddabb5839c4c7f6bf3d4183231f005"
165 "b31aa58affdda5c79e4cce217f6bc930"
166 "dbe563d480706c24e9ebfcab28a6cdef"
167 "d324b77e1bf7251b709092c24ff501fd"
168 "91"
169 "0240" // INTEGER length 0x40 (exponent1)
170 "23d4340eda3445d8cd26c14411da6fdc"
171 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
172 "842c1d280405bc2f6c1bea214a1d742a"
173 "b996b35b63a82a5e470fa88dbf823cdd"
174 "0240" // INTEGER length 0x40 (exponent2)
175 "1b7b57449ad30d1518249a5f56bb9829"
176 "4d4b6ac12ffc86940497a5a5837a6cf9"
177 "46262b494526d328c11e1126380fde04"
178 "c24f916dec250892db09a6d77cdba351"
179 "0240" // INTEGER length 0x40 (coefficient)
180 "7762cd8f4d050da56bd591adb515d24d"
181 "7ccd32cca0d05f866d583514bd7324d5"
182 "f33645e8ed8b4a1cb3cc4a1d67987399"
183 "f2a09f5b3fb68c88d5e5d90ac33492d6"
184 // } end SEQUENCE (PrivateKey)
185 // } end SEQUENCE (PrivateKeyInfo)
186);
Selene Huang31ab4042020-04-29 04:22:39 -0700187
Selene Huange5727e62021-04-13 22:41:20 -0700188/*
189 * DER-encoded PKCS#8 format RSA key. Generated using:
190 *
191 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
192 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100193string rsa_2048_key = hex2str(
194 // RFC 5208 s5
195 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
196 "020100" // INTEGER length 1 value 0x00 (version)
197 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
198 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
199 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
200 "0500" // NULL (parameters)
201 // } end SEQUENCE (AlgorithmIdentifier)
202 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
203 // RFC 8017 A.1.2
204 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
205 "020100" // INTEGER length 1 value 0x00 (version)
206 "02820101" // INTEGER length 0x101 value (modulus) ...
207 "00BEBC342B56D443B1299F9A6A7056E8"
208 "0A897E318476A5A18029E63B2ED739A6"
209 "1791D339F58DC763D9D14911F2EDEC38"
210 "3DEE11F6319B44510E7A3ECD9B79B973"
211 "82E49500ACF8117DC89CAF0E621F7775"
212 "6554A2FD4664BFE7AB8B59AB48340DBF"
213 "A27B93B5A81F6ECDEB02D0759307128D"
214 "F3E3BAD4055C8B840216DFAA5700670E"
215 "6C5126F0962FCB70FF308F25049164CC"
216 "F76CC2DA66A7DD9A81A714C2809D6918"
217 "6133D29D84568E892B6FFBF3199BDB14"
218 "383EE224407F190358F111A949552ABA"
219 "6714227D1BD7F6B20DD0CB88F9467B71"
220 "9339F33BFF35B3870B3F62204E4286B0"
221 "948EA348B524544B5F9838F29EE643B0"
222 "79EEF8A713B220D7806924CDF7295070"
223 "C5"
224 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
225 "02820100" // INTEGER length 0x100 (privateExponent) value...
226 "69F377F35F2F584EF075353CCD1CA997"
227 "38DB3DBC7C7FF35F9366CE176DFD1B13"
228 "5AB10030344ABF5FBECF1D4659FDEF1C"
229 "0FC430834BE1BE3911951377BB3D563A"
230 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
231 "2686C7B4B3C09A7B8354133E6F93F790"
232 "D59EAEB92E84C9A4339302CCE28FDF04"
233 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
234 "6AB706645BF074A4E4090D06FB163124"
235 "365FD5EE7A20D350E9958CC30D91326E"
236 "1B292E9EF5DB408EC42DAF737D201497"
237 "04D0A678A0FB5B5446863B099228A352"
238 "D604BA8091A164D01D5AB05397C71EAD"
239 "20BE2A08FC528FE442817809C787FEE4"
240 "AB97F97B9130D022153EDC6EB6CBE7B0"
241 "F8E3473F2E901209B5DB10F93604DB01"
242 "028181" // INTEGER length 0x81 (prime1)
243 "00E83C0998214941EA4F9293F1B77E2E"
244 "99E6CF305FAF358238E126124FEAF2EB"
245 "9724B2EA7B78E6032343821A80E55D1D"
246 "88FB12D220C3F41A56142FEC85796D19"
247 "17F1E8C774F142B67D3D6E7B7E6B4383"
248 "E94DB5929089DBB346D5BDAB40CC2D96"
249 "EE0409475E175C63BF78CFD744136740"
250 "838127EA723FF3FE7FA368C1311B4A4E"
251 "05"
252 "028181" // INTEGER length 0x81 (prime2)
253 "00D240FCC0F5D7715CDE21CB2DC86EA1"
254 "46132EA3B06F61FF2AF54BF38473F59D"
255 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
256 "B1B58C39F95E4798CCBB43E83D0119AC"
257 "F532F359CA743C85199F0286610E2009"
258 "97D7312917179AC9B67558773212EC96"
259 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
260 "94D94E066A0900B7B70E82A44FB30053"
261 "C1"
262 "028181" // INTEGER length 0x81 (exponent1)
263 "00AD15DA1CBD6A492B66851BA8C316D3"
264 "8AB700E2CFDDD926A658003513C54BAA"
265 "152B30021D667D20078F500F8AD3E7F3"
266 "945D74A891ED1A28EAD0FEEAEC8C14A8"
267 "E834CF46A13D1378C99D18940823CFDD"
268 "27EC5810D59339E0C34198AC638E09C8"
269 "7CBB1B634A9864AE9F4D5EB2D53514F6"
270 "7B4CAEC048C8AB849A02E397618F3271"
271 "35"
272 "028180" // INTEGER length 0x80 (exponent2)
273 "1FA2C1A5331880A92D8F3E281C617108"
274 "BF38244F16E352E69ED417C7153F9EC3"
275 "18F211839C643DCF8B4DD67CE2AC312E"
276 "95178D5D952F06B1BF779F4916924B70"
277 "F582A23F11304E02A5E7565AE22A35E7"
278 "4FECC8B6FDC93F92A1A37703E4CF0E63"
279 "783BD02EB716A7ECBBFA606B10B74D01"
280 "579522E7EF84D91FC522292108D902C1"
281 "028180" // INTEGER length 0x80 (coefficient)
282 "796FE3825F9DCC85DF22D58690065D93"
283 "898ACD65C087BEA8DA3A63BF4549B795"
284 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
285 "0D74F40DED8E1102C52152A31B6165F8"
286 "3A6722AECFCC35A493D7634664B888A0"
287 "8D3EB034F12EA28BFEE346E205D33482"
288 "7F778B16ED40872BD29FCB36536B6E93"
289 "FFB06778696B4A9D81BB0A9423E63DE5"
290 // } end SEQUENCE (PrivateKey)
291 // } end SEQUENCE (PrivateKeyInfo)
292);
Selene Huange5727e62021-04-13 22:41:20 -0700293
David Drysdaled2cc8c22021-04-15 13:29:45 +0100294string ec_256_key = hex2str(
295 // RFC 5208 s5
296 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
297 "020100" // INTEGER length 1 value 0 (version)
298 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
299 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
300 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
301 "0608" // OBJECT IDENTIFIER length 8 (param)
302 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
303 // } end SEQUENCE (AlgorithmIdentifier)
304 "046d" // OCTET STRING length 0x6d (privateKey) holding...
305 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
306 "020101" // INTEGER length 1 value 1 (version)
307 "0420" // OCTET STRING length 0x20 (privateKey)
308 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
309 "941eed09366bc03299986481f3a4d859"
310 "a144" // TAG [1] len 0x44 (publicKey) {
311 "03420004bf85d7720d07c25461683bc6"
312 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
313 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
314 "bcc41c6eb00083cf3376d11fd44949e0"
315 "b2183bfe"
316 // } end SEQUENCE (ECPrivateKey)
317 // } end SEQUENCE (PrivateKeyInfo)
318);
Selene Huang31ab4042020-04-29 04:22:39 -0700319
David Drysdaled2cc8c22021-04-15 13:29:45 +0100320string ec_521_key = hex2str(
321 // RFC 5208 s5
322 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
323 "020100" // INTEGER length 1 value 0 (version)
324 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
325 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
326 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
327 "0605" // OBJECT IDENTIFIER length 5 (param)
328 "2B81040023" // 1.3.132.0.35 (secp521r1)
329 // } end SEQUENCE (AlgorithmIdentifier)
330 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
331 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
332 "020101" // INTEGER length 1 value 1 (version)
333 "0442" // OCTET STRING length 0x42 (privateKey)
334 "0011458C586DB5DAA92AFAB03F4FE46A"
335 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
336 "9D18D7D08B5BCFA0E53C75B064AD51C4"
337 "49BAE0258D54B94B1E885DED08ED4FB2"
338 "5CE9"
339 "A18189" // TAG [1] len 0x89 (publicKey) {
340 "03818600040149EC11C6DF0FA122C6A9"
341 "AFD9754A4FA9513A627CA329E349535A"
342 "5629875A8ADFBE27DCB932C051986377"
343 "108D054C28C6F39B6F2C9AF81802F9F3"
344 "26B842FF2E5F3C00AB7635CFB36157FC"
345 "0882D574A10D839C1A0C049DC5E0D775"
346 "E2EE50671A208431BB45E78E70BEFE93"
347 "0DB34818EE4D5C26259F5C6B8E28A652"
348 "950F9F88D7B4B2C9D9"
349 // } end SEQUENCE (ECPrivateKey)
350 // } end SEQUENCE (PrivateKeyInfo)
351);
Selene Huang31ab4042020-04-29 04:22:39 -0700352
David Drysdaled2cc8c22021-04-15 13:29:45 +0100353string ec_256_key_rfc5915 = hex2str(
354 // RFC 5208 s5
355 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
356 "020100" // INTEGER length 1 value 0 (version)
357 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
358 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
359 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
360 "0608" // OBJECT IDENTIFIER length 8 (param)
361 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
362 // } end SEQUENCE (AlgorithmIdentifier)
363 "0479" // OCTET STRING length 0x79 (privateKey) holding...
364 // RFC 5915 s3
365 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
366 "020101" // INTEGER length 1 value 1 (version)
367 "0420" // OCTET STRING length 0x42 (privateKey)
368 "782370a8c8ce5537baadd04dcff079c8"
369 "158cfa9c67b818b38e8d21c9fa750c1d"
370 "a00a" // TAG [0] length 0xa (parameters)
371 "0608" // OBJECT IDENTIFIER length 8
372 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
373 // } end TAG [0]
374 "a144" // TAG [1] length 0x44 (publicKey) {
375 "0342" // BIT STRING length 0x42
376 "00" // no pad bits
377 "04e2cc561ee701da0ad0ef0d176bb0c9"
378 "19d42e79c393fdc1bd6c4010d85cf2cf"
379 "8e68c905464666f98dad4f01573ba810"
380 "78b3428570a439ba3229fbc026c55068"
381 "2f"
382 // } end SEQUENCE (ECPrivateKey)
383 // } end SEQUENCE (PrivateKeyInfo)
384);
Selene Huang31ab4042020-04-29 04:22:39 -0700385
David Drysdaled2cc8c22021-04-15 13:29:45 +0100386string ec_256_key_sec1 = hex2str(
387 // RFC 5208 s5
388 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
389 "020100" // INTEGER length 1 value 0 (version)
390 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
391 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
392 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
393 "0608" // OBJECT IDENTIFIER length 8 (param)
394 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
395 // } end SEQUENCE (AlgorithmIdentifier)
396 "046d" // OCTET STRING length 0x6d (privateKey) holding...
397 // SEC1-v2 C.4
398 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
399 "020101" // INTEGER length 1 value 0x01 (version)
400 "0420" // OCTET STRING length 0x20 (privateKey)
401 "782370a8c8ce5537baadd04dcff079c8"
402 "158cfa9c67b818b38e8d21c9fa750c1d"
403 "a144" // TAG [1] length 0x44 (publicKey) {
404 "0342" // BIT STRING length 0x42
405 "00" // no pad bits
406 "04e2cc561ee701da0ad0ef0d176bb0c9"
407 "19d42e79c393fdc1bd6c4010d85cf2cf"
408 "8e68c905464666f98dad4f01573ba810"
409 "78b3428570a439ba3229fbc026c55068"
410 "2f"
411 // } end TAG [1] (publicKey)
412 // } end SEQUENCE (PrivateKeyInfo)
413);
Selene Huang31ab4042020-04-29 04:22:39 -0700414
415struct RSA_Delete {
416 void operator()(RSA* p) { RSA_free(p); }
417};
418
Selene Huang31ab4042020-04-29 04:22:39 -0700419std::string make_string(const uint8_t* data, size_t length) {
420 return std::string(reinterpret_cast<const char*>(data), length);
421}
422
423template <size_t N>
424std::string make_string(const uint8_t (&a)[N]) {
425 return make_string(a, N);
426}
427
428class AidlBuf : public vector<uint8_t> {
429 typedef vector<uint8_t> super;
430
431 public:
432 AidlBuf() {}
433 AidlBuf(const super& other) : super(other) {}
434 AidlBuf(super&& other) : super(std::move(other)) {}
435 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
436
437 AidlBuf& operator=(const super& other) {
438 super::operator=(other);
439 return *this;
440 }
441
442 AidlBuf& operator=(super&& other) {
443 super::operator=(std::move(other));
444 return *this;
445 }
446
447 AidlBuf& operator=(const string& other) {
448 resize(other.size());
449 for (size_t i = 0; i < other.size(); ++i) {
450 (*this)[i] = static_cast<uint8_t>(other[i]);
451 }
452 return *this;
453 }
454
455 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
456};
457
David Drysdale4dc01072021-04-01 12:17:35 +0100458string device_suffix(const string& name) {
459 size_t pos = name.find('/');
460 if (pos == string::npos) {
461 return name;
462 }
463 return name.substr(pos + 1);
464}
465
466bool matching_rp_instance(const string& km_name,
467 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
468 string km_suffix = device_suffix(km_name);
469
470 vector<string> rp_names =
471 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
472 for (const string& rp_name : rp_names) {
473 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
474 // KeyMint instance, assume they match.
475 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
476 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
477 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
478 return true;
479 }
480 }
481 return false;
482}
483
Selene Huang31ab4042020-04-29 04:22:39 -0700484} // namespace
485
486class NewKeyGenerationTest : public KeyMintAidlTestBase {
487 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700488 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000489 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700490 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700491
Selene Huang31ab4042020-04-29 04:22:39 -0700492 // Check that some unexpected tags/values are NOT present.
493 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
494 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000495 }
496
497 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
498 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
499 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
500 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
501
502 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000503 }
504
505 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
506 // TODO(swillden): Distinguish which params should be in which auth list.
507 AuthorizationSet auths;
508 for (auto& entry : keyCharacteristics) {
509 auths.push_back(AuthorizationSet(entry.authorizations));
510 }
511 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
512
513 // Verify that App data, ROT and auth timeout are NOT included.
514 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
515 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700516 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
517
David Drysdaled2cc8c22021-04-15 13:29:45 +0100518 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
519 // never adds it.
520 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
521
David Drysdale7de9feb2021-03-05 14:56:19 +0000522 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700523 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000524 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700525 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700526 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000527 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700528 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000529
David Drysdalef5bfa002021-09-27 17:30:41 +0100530 // Should include vendor and boot patchlevels.
531 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
532 EXPECT_TRUE(vendor_pl);
533 EXPECT_EQ(*vendor_pl, vendor_patch_level());
534 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
535 EXPECT_TRUE(boot_pl);
David Drysdalebb3d85e2021-04-13 11:15:51 +0100536
David Drysdale7de9feb2021-03-05 14:56:19 +0000537 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700538 }
539};
540
541/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000542 * NewKeyGenerationTest.Aes
543 *
544 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
545 * have correct characteristics.
546 */
547TEST_P(NewKeyGenerationTest, Aes) {
548 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
549 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
550 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
551 SCOPED_TRACE(testing::Message()
552 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
553 vector<uint8_t> key_blob;
554 vector<KeyCharacteristics> key_characteristics;
555 auto builder = AuthorizationSetBuilder()
556 .AesEncryptionKey(key_size)
557 .BlockMode(block_mode)
558 .Padding(padding_mode)
559 .SetDefaultValidity();
560 if (block_mode == BlockMode::GCM) {
561 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
562 }
563 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
564
565 EXPECT_GT(key_blob.size(), 0U);
566 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100567 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000568
569 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
570
571 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
572 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
573 << "Key size " << key_size << "missing";
574
575 CheckedDeleteKey(&key_blob);
576 }
577 }
578 }
579}
580
581/*
582 * NewKeyGenerationTest.AesInvalidSize
583 *
584 * Verifies that specifying an invalid key size for AES key generation returns
585 * UNSUPPORTED_KEY_SIZE.
586 */
587TEST_P(NewKeyGenerationTest, AesInvalidSize) {
588 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
589 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
590 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
591 SCOPED_TRACE(testing::Message()
592 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
593 vector<uint8_t> key_blob;
594 vector<KeyCharacteristics> key_characteristics;
595 auto builder = AuthorizationSetBuilder()
596 .AesEncryptionKey(key_size)
597 .BlockMode(block_mode)
598 .Padding(padding_mode)
599 .SetDefaultValidity();
600 if (block_mode == BlockMode::GCM) {
601 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
602 }
603 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
604 GenerateKey(builder, &key_blob, &key_characteristics));
605 }
606 }
607 }
608
609 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
610 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
611 vector<uint8_t> key_blob;
612 vector<KeyCharacteristics> key_characteristics;
613 // No key size specified
614 auto builder = AuthorizationSetBuilder()
615 .Authorization(TAG_ALGORITHM, Algorithm::AES)
616 .BlockMode(block_mode)
617 .Padding(padding_mode)
618 .SetDefaultValidity();
619 if (block_mode == BlockMode::GCM) {
620 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
621 }
622 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
623 GenerateKey(builder, &key_blob, &key_characteristics));
624 }
625 }
626}
627
628/*
629 * NewKeyGenerationTest.AesInvalidPadding
630 *
631 * Verifies that specifying an invalid padding on AES keys gives a failure
632 * somewhere along the way.
633 */
634TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
635 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
636 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
637 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
638 SCOPED_TRACE(testing::Message()
639 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000640 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800641 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000642 .AesEncryptionKey(key_size)
643 .BlockMode(block_mode)
644 .Padding(padding_mode)
645 .SetDefaultValidity();
646 if (block_mode == BlockMode::GCM) {
647 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
648 }
649
Tommy Chiu3950b452021-05-03 22:01:46 +0800650 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000651 if (result == ErrorCode::OK) {
652 // Key creation was OK but has generated a key that cannot be used.
653 auto params =
654 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800655 if (block_mode == BlockMode::GCM) {
656 params.Authorization(TAG_MAC_LENGTH, 128);
657 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000658 auto result = Begin(KeyPurpose::ENCRYPT, params);
659 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100660 result == ErrorCode::INVALID_KEY_BLOB)
661 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000662 } else {
663 // The KeyMint implementation detected that the generated key
664 // is unusable.
665 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
666 }
667 }
668 }
669 }
670}
671
672/*
673 * NewKeyGenerationTest.AesGcmMissingMinMac
674 *
675 * Verifies that specifying an invalid key size for AES key generation returns
676 * UNSUPPORTED_KEY_SIZE.
677 */
678TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
679 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
680 BlockMode block_mode = BlockMode::GCM;
681 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
682 SCOPED_TRACE(testing::Message()
683 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
684 vector<uint8_t> key_blob;
685 vector<KeyCharacteristics> key_characteristics;
686 // No MIN_MAC_LENGTH provided.
687 auto builder = AuthorizationSetBuilder()
688 .AesEncryptionKey(key_size)
689 .BlockMode(block_mode)
690 .Padding(padding_mode)
691 .SetDefaultValidity();
692 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
693 GenerateKey(builder, &key_blob, &key_characteristics));
694 }
695 }
696}
697
698/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100699 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
700 *
701 * Verifies that specifying an invalid min MAC size for AES key generation returns
702 * UNSUPPORTED_MIN_MAC_LENGTH.
703 */
704TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
705 for (size_t min_mac_len : {88, 136}) {
706 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
707 BlockMode block_mode = BlockMode::GCM;
708 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
709 SCOPED_TRACE(testing::Message()
710 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
711 vector<uint8_t> key_blob;
712 vector<KeyCharacteristics> key_characteristics;
713 auto builder = AuthorizationSetBuilder()
714 .AesEncryptionKey(key_size)
715 .BlockMode(block_mode)
716 .Padding(padding_mode)
717 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
718 .SetDefaultValidity();
719 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
720 GenerateKey(builder, &key_blob, &key_characteristics));
721 }
722 }
723 }
724}
725
726/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000727 * NewKeyGenerationTest.TripleDes
728 *
729 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
730 * have correct characteristics.
731 */
732TEST_P(NewKeyGenerationTest, TripleDes) {
733 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
734 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
735 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
736 SCOPED_TRACE(testing::Message()
737 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
738 vector<uint8_t> key_blob;
739 vector<KeyCharacteristics> key_characteristics;
740 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
741 .TripleDesEncryptionKey(key_size)
742 .BlockMode(block_mode)
743 .Padding(padding_mode)
744 .Authorization(TAG_NO_AUTH_REQUIRED)
745 .SetDefaultValidity(),
746 &key_blob, &key_characteristics));
747
748 EXPECT_GT(key_blob.size(), 0U);
749 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100750 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000751
752 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
753
754 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
755 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
756 << "Key size " << key_size << "missing";
757
758 CheckedDeleteKey(&key_blob);
759 }
760 }
761 }
762}
763
764/*
765 * NewKeyGenerationTest.TripleDesWithAttestation
766 *
767 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
768 * have correct characteristics.
769 *
770 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
771 * put in a certificate) but which isn't an error.
772 */
773TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
774 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
775 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
776 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
777 SCOPED_TRACE(testing::Message()
778 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
779
780 auto challenge = "hello";
781 auto app_id = "foo";
782
783 vector<uint8_t> key_blob;
784 vector<KeyCharacteristics> key_characteristics;
785 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
786 .TripleDesEncryptionKey(key_size)
787 .BlockMode(block_mode)
788 .Padding(padding_mode)
789 .Authorization(TAG_NO_AUTH_REQUIRED)
790 .AttestationChallenge(challenge)
791 .AttestationApplicationId(app_id)
792 .SetDefaultValidity(),
793 &key_blob, &key_characteristics));
794
795 EXPECT_GT(key_blob.size(), 0U);
796 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100797 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000798
799 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
800
801 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
802 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
803 << "Key size " << key_size << "missing";
804
805 CheckedDeleteKey(&key_blob);
806 }
807 }
808 }
809}
810
811/*
812 * NewKeyGenerationTest.TripleDesInvalidSize
813 *
814 * Verifies that specifying an invalid key size for 3-DES key generation returns
815 * UNSUPPORTED_KEY_SIZE.
816 */
817TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
818 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
819 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
820 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
821 SCOPED_TRACE(testing::Message()
822 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
823 vector<uint8_t> key_blob;
824 vector<KeyCharacteristics> key_characteristics;
825 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
826 GenerateKey(AuthorizationSetBuilder()
827 .TripleDesEncryptionKey(key_size)
828 .BlockMode(block_mode)
829 .Padding(padding_mode)
830 .Authorization(TAG_NO_AUTH_REQUIRED)
831 .SetDefaultValidity(),
832 &key_blob, &key_characteristics));
833 }
834 }
835 }
836
837 // Omitting the key size fails.
838 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
839 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
840 SCOPED_TRACE(testing::Message()
841 << "3DES-default-" << block_mode << "-" << padding_mode);
842 vector<uint8_t> key_blob;
843 vector<KeyCharacteristics> key_characteristics;
844 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
845 GenerateKey(AuthorizationSetBuilder()
846 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
847 .BlockMode(block_mode)
848 .Padding(padding_mode)
849 .Authorization(TAG_NO_AUTH_REQUIRED)
850 .SetDefaultValidity(),
851 &key_blob, &key_characteristics));
852 }
853 }
854}
855
856/*
Selene Huang31ab4042020-04-29 04:22:39 -0700857 * NewKeyGenerationTest.Rsa
858 *
859 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
860 * have correct characteristics.
861 */
862TEST_P(NewKeyGenerationTest, Rsa) {
863 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
864 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700865 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700866 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
867 .RsaSigningKey(key_size, 65537)
868 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800869 .Padding(PaddingMode::NONE)
870 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700871 &key_blob, &key_characteristics));
872
873 ASSERT_GT(key_blob.size(), 0U);
874 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100875 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700876
Shawn Willden7f424372021-01-10 18:06:50 -0700877 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700878
879 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
880 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
881 << "Key size " << key_size << "missing";
882 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
883
884 CheckedDeleteKey(&key_blob);
885 }
886}
887
888/*
Qi Wud22ec842020-11-26 13:27:53 +0800889 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700890 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100891 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
892 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700893 */
894TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700895 auto challenge = "hello";
896 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700897
Selene Huang6e46f142021-04-20 19:20:11 -0700898 auto subject = "cert subj 2";
899 vector<uint8_t> subject_der(make_name_from_str(subject));
900
901 uint64_t serial_int = 66;
902 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
903
Selene Huang4f64c222021-04-13 19:54:36 -0700904 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700905 vector<uint8_t> key_blob;
906 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700907 ASSERT_EQ(ErrorCode::OK,
908 GenerateKey(AuthorizationSetBuilder()
909 .RsaSigningKey(key_size, 65537)
910 .Digest(Digest::NONE)
911 .Padding(PaddingMode::NONE)
912 .AttestationChallenge(challenge)
913 .AttestationApplicationId(app_id)
914 .Authorization(TAG_NO_AUTH_REQUIRED)
915 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
916 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
917 .SetDefaultValidity(),
918 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700919
920 ASSERT_GT(key_blob.size(), 0U);
921 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100922 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700923
924 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
925
926 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
927 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
928 << "Key size " << key_size << "missing";
929 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
930
Selene Huang6e46f142021-04-20 19:20:11 -0700931 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700932 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700933 ASSERT_GT(cert_chain_.size(), 0);
934
935 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
936 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
937 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
938 sw_enforced, hw_enforced, SecLevel(),
939 cert_chain_[0].encodedCertificate));
940
941 CheckedDeleteKey(&key_blob);
942 }
943}
944
945/*
David Drysdale4dc01072021-04-01 12:17:35 +0100946 * NewKeyGenerationTest.RsaWithRpkAttestation
947 *
948 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
949 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +0100950 *
951 * This test is disabled because the KeyMint specification does not require that implementations
952 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
953 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +0100954 */
David Drysdale0fce69d2021-04-13 17:22:13 +0100955TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +0100956 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
957 // instance.
958 std::shared_ptr<IRemotelyProvisionedComponent> rp;
959 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
960 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
961
962 // Generate a P-256 keypair to use as an attestation key.
963 MacedPublicKey macedPubKey;
964 std::vector<uint8_t> privateKeyBlob;
965 auto status =
966 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
967 ASSERT_TRUE(status.isOk());
968 vector<uint8_t> coseKeyData;
969 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
970
971 AttestationKey attestation_key;
972 attestation_key.keyBlob = std::move(privateKeyBlob);
973 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
974
975 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
976 auto challenge = "hello";
977 auto app_id = "foo";
978
979 vector<uint8_t> key_blob;
980 vector<KeyCharacteristics> key_characteristics;
981 ASSERT_EQ(ErrorCode::OK,
982 GenerateKey(AuthorizationSetBuilder()
983 .RsaSigningKey(key_size, 65537)
984 .Digest(Digest::NONE)
985 .Padding(PaddingMode::NONE)
986 .AttestationChallenge(challenge)
987 .AttestationApplicationId(app_id)
988 .Authorization(TAG_NO_AUTH_REQUIRED)
989 .SetDefaultValidity(),
990 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
991
992 ASSERT_GT(key_blob.size(), 0U);
993 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100994 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +0100995
996 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
997
998 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
999 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1000 << "Key size " << key_size << "missing";
1001 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1002
1003 // Attestation by itself is not valid (last entry is not self-signed).
1004 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1005
1006 // The signature over the attested key should correspond to the P256 public key.
1007 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1008 ASSERT_TRUE(key_cert.get());
1009 EVP_PKEY_Ptr signing_pubkey;
1010 p256_pub_key(coseKeyData, &signing_pubkey);
1011 ASSERT_TRUE(signing_pubkey.get());
1012
1013 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1014 << "Verification of attested certificate failed "
1015 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1016
1017 CheckedDeleteKey(&key_blob);
1018 }
1019}
1020
1021/*
Selene Huang4f64c222021-04-13 19:54:36 -07001022 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1023 *
1024 * Verifies that keymint attestation for RSA encryption keys with challenge and
1025 * app id is also successful.
1026 */
1027TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1028 auto key_size = 2048;
1029 auto challenge = "hello";
1030 auto app_id = "foo";
1031
Selene Huang6e46f142021-04-20 19:20:11 -07001032 auto subject = "subj 2";
1033 vector<uint8_t> subject_der(make_name_from_str(subject));
1034
1035 uint64_t serial_int = 111166;
1036 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1037
Selene Huang4f64c222021-04-13 19:54:36 -07001038 vector<uint8_t> key_blob;
1039 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001040 ASSERT_EQ(ErrorCode::OK,
1041 GenerateKey(AuthorizationSetBuilder()
1042 .RsaEncryptionKey(key_size, 65537)
1043 .Padding(PaddingMode::NONE)
1044 .AttestationChallenge(challenge)
1045 .AttestationApplicationId(app_id)
1046 .Authorization(TAG_NO_AUTH_REQUIRED)
1047 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1048 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1049 .SetDefaultValidity(),
1050 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001051
1052 ASSERT_GT(key_blob.size(), 0U);
1053 AuthorizationSet auths;
1054 for (auto& entry : key_characteristics) {
1055 auths.push_back(AuthorizationSet(entry.authorizations));
1056 }
1057
1058 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1059 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1060
1061 // Verify that App data and ROT are NOT included.
1062 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1063 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1064
1065 // Check that some unexpected tags/values are NOT present.
1066 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1067 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1068
1069 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1070
1071 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1072 ASSERT_TRUE(os_ver);
1073 EXPECT_EQ(*os_ver, os_version());
1074
1075 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1076
1077 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1078 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1079 << "Key size " << key_size << "missing";
1080 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1081
Selene Huang6e46f142021-04-20 19:20:11 -07001082 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001083 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1084 ASSERT_GT(cert_chain_.size(), 0);
1085
1086 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1087 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1088 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1089 sw_enforced, hw_enforced, SecLevel(),
1090 cert_chain_[0].encodedCertificate));
1091
1092 CheckedDeleteKey(&key_blob);
1093}
1094
1095/*
1096 * NewKeyGenerationTest.RsaWithSelfSign
1097 *
1098 * Verifies that attesting to RSA key generation is successful, and returns
1099 * self signed certificate if no challenge is provided. And signing etc
1100 * works as expected.
1101 */
1102TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001103 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1104 vector<uint8_t> subject_der(make_name_from_str(subject));
1105
1106 uint64_t serial_int = 0;
1107 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1108
Selene Huang4f64c222021-04-13 19:54:36 -07001109 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1110 vector<uint8_t> key_blob;
1111 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001112 ASSERT_EQ(ErrorCode::OK,
1113 GenerateKey(AuthorizationSetBuilder()
1114 .RsaSigningKey(key_size, 65537)
1115 .Digest(Digest::NONE)
1116 .Padding(PaddingMode::NONE)
1117 .Authorization(TAG_NO_AUTH_REQUIRED)
1118 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1119 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1120 .SetDefaultValidity(),
1121 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001122
1123 ASSERT_GT(key_blob.size(), 0U);
1124 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001125 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001126
1127 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1128
1129 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1130 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1131 << "Key size " << key_size << "missing";
1132 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1133
Selene Huang6e46f142021-04-20 19:20:11 -07001134 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001135 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1136 ASSERT_EQ(cert_chain_.size(), 1);
1137
1138 CheckedDeleteKey(&key_blob);
1139 }
1140}
1141
1142/*
1143 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1144 *
1145 * Verifies that attesting to RSA checks for missing app ID.
1146 */
1147TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1148 auto challenge = "hello";
1149 vector<uint8_t> key_blob;
1150 vector<KeyCharacteristics> key_characteristics;
1151
1152 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1153 GenerateKey(AuthorizationSetBuilder()
1154 .RsaSigningKey(2048, 65537)
1155 .Digest(Digest::NONE)
1156 .Padding(PaddingMode::NONE)
1157 .AttestationChallenge(challenge)
1158 .Authorization(TAG_NO_AUTH_REQUIRED)
1159 .SetDefaultValidity(),
1160 &key_blob, &key_characteristics));
1161}
1162
1163/*
1164 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1165 *
1166 * Verifies that attesting to RSA ignores app id if challenge is missing.
1167 */
1168TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1169 auto key_size = 2048;
1170 auto app_id = "foo";
1171
Selene Huang6e46f142021-04-20 19:20:11 -07001172 auto subject = "cert subj 2";
1173 vector<uint8_t> subject_der(make_name_from_str(subject));
1174
1175 uint64_t serial_int = 1;
1176 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1177
Selene Huang4f64c222021-04-13 19:54:36 -07001178 vector<uint8_t> key_blob;
1179 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001180 ASSERT_EQ(ErrorCode::OK,
1181 GenerateKey(AuthorizationSetBuilder()
1182 .RsaSigningKey(key_size, 65537)
1183 .Digest(Digest::NONE)
1184 .Padding(PaddingMode::NONE)
1185 .AttestationApplicationId(app_id)
1186 .Authorization(TAG_NO_AUTH_REQUIRED)
1187 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1188 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1189 .SetDefaultValidity(),
1190 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001191
1192 ASSERT_GT(key_blob.size(), 0U);
1193 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001194 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001195
1196 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1197
1198 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1199 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1200 << "Key size " << key_size << "missing";
1201 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1202
Selene Huang6e46f142021-04-20 19:20:11 -07001203 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001204 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1205 ASSERT_EQ(cert_chain_.size(), 1);
1206
1207 CheckedDeleteKey(&key_blob);
1208}
1209
1210/*
Qi Wud22ec842020-11-26 13:27:53 +08001211 * NewKeyGenerationTest.LimitedUsageRsa
1212 *
1213 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1214 * resulting keys have correct characteristics.
1215 */
1216TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1217 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1218 vector<uint8_t> key_blob;
1219 vector<KeyCharacteristics> key_characteristics;
1220 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1221 .RsaSigningKey(key_size, 65537)
1222 .Digest(Digest::NONE)
1223 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001224 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1225 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001226 &key_blob, &key_characteristics));
1227
1228 ASSERT_GT(key_blob.size(), 0U);
1229 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001230 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001231
1232 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1233
1234 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1235 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1236 << "Key size " << key_size << "missing";
1237 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1238
1239 // Check the usage count limit tag appears in the authorizations.
1240 AuthorizationSet auths;
1241 for (auto& entry : key_characteristics) {
1242 auths.push_back(AuthorizationSet(entry.authorizations));
1243 }
1244 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1245 << "key usage count limit " << 1U << " missing";
1246
1247 CheckedDeleteKey(&key_blob);
1248 }
1249}
1250
1251/*
Qi Wubeefae42021-01-28 23:16:37 +08001252 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1253 *
1254 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1255 * resulting keys have correct characteristics and attestation.
1256 */
1257TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001258 auto challenge = "hello";
1259 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001260
Selene Huang6e46f142021-04-20 19:20:11 -07001261 auto subject = "cert subj 2";
1262 vector<uint8_t> subject_der(make_name_from_str(subject));
1263
1264 uint64_t serial_int = 66;
1265 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1266
Selene Huang4f64c222021-04-13 19:54:36 -07001267 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001268 vector<uint8_t> key_blob;
1269 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001270 ASSERT_EQ(ErrorCode::OK,
1271 GenerateKey(AuthorizationSetBuilder()
1272 .RsaSigningKey(key_size, 65537)
1273 .Digest(Digest::NONE)
1274 .Padding(PaddingMode::NONE)
1275 .AttestationChallenge(challenge)
1276 .AttestationApplicationId(app_id)
1277 .Authorization(TAG_NO_AUTH_REQUIRED)
1278 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1279 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1280 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1281 .SetDefaultValidity(),
1282 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001283
1284 ASSERT_GT(key_blob.size(), 0U);
1285 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001286 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001287
1288 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1289
1290 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1291 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1292 << "Key size " << key_size << "missing";
1293 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1294
1295 // Check the usage count limit tag appears in the authorizations.
1296 AuthorizationSet auths;
1297 for (auto& entry : key_characteristics) {
1298 auths.push_back(AuthorizationSet(entry.authorizations));
1299 }
1300 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1301 << "key usage count limit " << 1U << " missing";
1302
1303 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001304 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001305 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001306 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001307
1308 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1309 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1310 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1311 sw_enforced, hw_enforced, SecLevel(),
1312 cert_chain_[0].encodedCertificate));
1313
1314 CheckedDeleteKey(&key_blob);
1315 }
1316}
1317
1318/*
Selene Huang31ab4042020-04-29 04:22:39 -07001319 * NewKeyGenerationTest.NoInvalidRsaSizes
1320 *
1321 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1322 */
1323TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1324 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1325 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001326 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001327 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1328 GenerateKey(AuthorizationSetBuilder()
1329 .RsaSigningKey(key_size, 65537)
1330 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001331 .Padding(PaddingMode::NONE)
1332 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001333 &key_blob, &key_characteristics));
1334 }
1335}
1336
1337/*
1338 * NewKeyGenerationTest.RsaNoDefaultSize
1339 *
1340 * Verifies that failing to specify a key size for RSA key generation returns
1341 * UNSUPPORTED_KEY_SIZE.
1342 */
1343TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1344 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1345 GenerateKey(AuthorizationSetBuilder()
1346 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1347 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001348 .SigningKey()
1349 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001350}
1351
1352/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001353 * NewKeyGenerationTest.RsaMissingParams
1354 *
1355 * Verifies that omitting optional tags works.
1356 */
1357TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1358 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1359 ASSERT_EQ(ErrorCode::OK,
1360 GenerateKey(
1361 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1362 CheckedDeleteKey();
1363 }
1364}
1365
1366/*
Selene Huang31ab4042020-04-29 04:22:39 -07001367 * NewKeyGenerationTest.Ecdsa
1368 *
1369 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1370 * have correct characteristics.
1371 */
1372TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001373 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001374 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001375 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001376 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001377 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001378 .Digest(Digest::NONE)
1379 .SetDefaultValidity(),
1380 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001381 ASSERT_GT(key_blob.size(), 0U);
1382 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001383 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001384
Shawn Willden7f424372021-01-10 18:06:50 -07001385 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001386
1387 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001388 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001389
1390 CheckedDeleteKey(&key_blob);
1391 }
1392}
1393
1394/*
Selene Huang4f64c222021-04-13 19:54:36 -07001395 * NewKeyGenerationTest.EcdsaAttestation
1396 *
1397 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1398 * an attestation will be generated.
1399 */
1400TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1401 auto challenge = "hello";
1402 auto app_id = "foo";
1403
Selene Huang6e46f142021-04-20 19:20:11 -07001404 auto subject = "cert subj 2";
1405 vector<uint8_t> subject_der(make_name_from_str(subject));
1406
1407 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1408 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1409
David Drysdaledf09e542021-06-08 15:46:11 +01001410 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001411 vector<uint8_t> key_blob;
1412 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001413 ASSERT_EQ(ErrorCode::OK,
1414 GenerateKey(AuthorizationSetBuilder()
1415 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001416 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001417 .Digest(Digest::NONE)
1418 .AttestationChallenge(challenge)
1419 .AttestationApplicationId(app_id)
1420 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1421 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1422 .SetDefaultValidity(),
1423 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001424 ASSERT_GT(key_blob.size(), 0U);
1425 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001426 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001427
1428 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1429
1430 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001431 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001432
1433 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1434 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001435 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001436
1437 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1438 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1439 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1440 sw_enforced, hw_enforced, SecLevel(),
1441 cert_chain_[0].encodedCertificate));
1442
1443 CheckedDeleteKey(&key_blob);
1444 }
1445}
1446
1447/*
David Drysdale37af4b32021-05-14 16:46:59 +01001448 * NewKeyGenerationTest.EcdsaAttestationTags
1449 *
1450 * Verifies that creation of an attested ECDSA key includes various tags in the
1451 * attestation extension.
1452 */
1453TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1454 auto challenge = "hello";
1455 auto app_id = "foo";
1456 auto subject = "cert subj 2";
1457 vector<uint8_t> subject_der(make_name_from_str(subject));
1458 uint64_t serial_int = 0x1010;
1459 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1460 const AuthorizationSetBuilder base_builder =
1461 AuthorizationSetBuilder()
1462 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001463 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001464 .Digest(Digest::NONE)
1465 .AttestationChallenge(challenge)
1466 .AttestationApplicationId(app_id)
1467 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1468 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1469 .SetDefaultValidity();
1470
1471 // Various tags that map to fields in the attestation extension ASN.1 schema.
1472 auto extra_tags = AuthorizationSetBuilder()
1473 .Authorization(TAG_ROLLBACK_RESISTANCE)
1474 .Authorization(TAG_EARLY_BOOT_ONLY)
1475 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1476 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1477 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1478 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1479 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1480 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1481 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1482 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1483 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1484 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
1485 for (const KeyParameter& tag : extra_tags) {
1486 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1487 vector<uint8_t> key_blob;
1488 vector<KeyCharacteristics> key_characteristics;
1489 AuthorizationSetBuilder builder = base_builder;
1490 builder.push_back(tag);
1491 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1492 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1493 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1494 continue;
1495 }
Seth Mooreb393b082021-07-12 14:18:28 -07001496 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1497 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001498 continue;
1499 }
1500 ASSERT_EQ(result, ErrorCode::OK);
1501 ASSERT_GT(key_blob.size(), 0U);
1502
1503 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1504 ASSERT_GT(cert_chain_.size(), 0);
1505 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1506
1507 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1508 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001509 // Some tags are optional, so don't require them to be in the enforcements.
1510 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001511 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1512 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1513 }
1514
1515 // Verifying the attestation record will check for the specific tag because
1516 // it's included in the authorizations.
1517 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1518 SecLevel(), cert_chain_[0].encodedCertificate));
1519
1520 CheckedDeleteKey(&key_blob);
1521 }
1522
1523 // Device attestation IDs should be rejected for normal attestation requests; these fields
1524 // are only used for device unique attestation.
1525 auto invalid_tags = AuthorizationSetBuilder()
1526 .Authorization(TAG_ATTESTATION_ID_BRAND, "brand")
1527 .Authorization(TAG_ATTESTATION_ID_DEVICE, "device")
1528 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "product")
1529 .Authorization(TAG_ATTESTATION_ID_SERIAL, "serial")
1530 .Authorization(TAG_ATTESTATION_ID_IMEI, "imei")
1531 .Authorization(TAG_ATTESTATION_ID_MEID, "meid")
1532 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer")
1533 .Authorization(TAG_ATTESTATION_ID_MODEL, "model");
1534 for (const KeyParameter& tag : invalid_tags) {
1535 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1536 vector<uint8_t> key_blob;
1537 vector<KeyCharacteristics> key_characteristics;
1538 AuthorizationSetBuilder builder =
1539 AuthorizationSetBuilder()
1540 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001541 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001542 .Digest(Digest::NONE)
1543 .AttestationChallenge(challenge)
1544 .AttestationApplicationId(app_id)
1545 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1546 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1547 .SetDefaultValidity();
1548 builder.push_back(tag);
1549 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1550 GenerateKey(builder, &key_blob, &key_characteristics));
1551 }
1552}
1553
1554/*
1555 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1556 *
1557 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1558 */
1559TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1560 auto challenge = "hello";
1561 auto attest_app_id = "foo";
1562 auto subject = "cert subj 2";
1563 vector<uint8_t> subject_der(make_name_from_str(subject));
1564 uint64_t serial_int = 0x1010;
1565 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1566
1567 // Earlier versions of the attestation extension schema included a slot:
1568 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1569 // This should never have been included, and should never be filled in.
1570 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1571 // to confirm that this field never makes it into the attestation extension.
1572 vector<uint8_t> key_blob;
1573 vector<KeyCharacteristics> key_characteristics;
1574 auto result = GenerateKey(AuthorizationSetBuilder()
1575 .Authorization(TAG_NO_AUTH_REQUIRED)
1576 .EcdsaSigningKey(EcCurve::P_256)
1577 .Digest(Digest::NONE)
1578 .AttestationChallenge(challenge)
1579 .AttestationApplicationId(attest_app_id)
1580 .Authorization(TAG_APPLICATION_ID, "client_id")
1581 .Authorization(TAG_APPLICATION_DATA, "appdata")
1582 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1583 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1584 .SetDefaultValidity(),
1585 &key_blob, &key_characteristics);
1586 ASSERT_EQ(result, ErrorCode::OK);
1587 ASSERT_GT(key_blob.size(), 0U);
1588
1589 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1590 ASSERT_GT(cert_chain_.size(), 0);
1591 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1592
1593 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1594 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1595 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1596 SecLevel(), cert_chain_[0].encodedCertificate));
1597
1598 // Check that the app id is not in the cert.
1599 string app_id = "clientid";
1600 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1601 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1602 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1603 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1604 cert_chain_[0].encodedCertificate.end());
1605
1606 CheckedDeleteKey(&key_blob);
1607}
1608
1609/*
Selene Huang4f64c222021-04-13 19:54:36 -07001610 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1611 *
1612 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1613 * the key will generate a self signed attestation.
1614 */
1615TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001616 auto subject = "cert subj 2";
1617 vector<uint8_t> subject_der(make_name_from_str(subject));
1618
1619 uint64_t serial_int = 0x123456FFF1234;
1620 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1621
David Drysdaledf09e542021-06-08 15:46:11 +01001622 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001623 vector<uint8_t> key_blob;
1624 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001625 ASSERT_EQ(ErrorCode::OK,
1626 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001627 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001628 .Digest(Digest::NONE)
1629 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1630 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1631 .SetDefaultValidity(),
1632 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001633 ASSERT_GT(key_blob.size(), 0U);
1634 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001635 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001636
1637 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1638
1639 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001640 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001641
1642 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001643 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001644 ASSERT_EQ(cert_chain_.size(), 1);
1645
1646 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1647 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1648
1649 CheckedDeleteKey(&key_blob);
1650 }
1651}
1652
1653/*
1654 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1655 *
1656 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1657 * app id must also be provided or else it will fail.
1658 */
1659TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1660 auto challenge = "hello";
1661 vector<uint8_t> key_blob;
1662 vector<KeyCharacteristics> key_characteristics;
1663
1664 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1665 GenerateKey(AuthorizationSetBuilder()
1666 .EcdsaSigningKey(EcCurve::P_256)
1667 .Digest(Digest::NONE)
1668 .AttestationChallenge(challenge)
1669 .SetDefaultValidity(),
1670 &key_blob, &key_characteristics));
1671}
1672
1673/*
1674 * NewKeyGenerationTest.EcdsaIgnoreAppId
1675 *
1676 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1677 * any appid will be ignored, and keymint will generate a self sign certificate.
1678 */
1679TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1680 auto app_id = "foo";
1681
David Drysdaledf09e542021-06-08 15:46:11 +01001682 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001683 vector<uint8_t> key_blob;
1684 vector<KeyCharacteristics> key_characteristics;
1685 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001686 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001687 .Digest(Digest::NONE)
1688 .AttestationApplicationId(app_id)
1689 .SetDefaultValidity(),
1690 &key_blob, &key_characteristics));
1691
1692 ASSERT_GT(key_blob.size(), 0U);
1693 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001694 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001695
1696 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1697
1698 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001699 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001700
1701 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1702 ASSERT_EQ(cert_chain_.size(), 1);
1703
1704 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1705 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1706
1707 CheckedDeleteKey(&key_blob);
1708 }
1709}
1710
1711/*
1712 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1713 *
1714 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1715 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1716 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1717 * to specify how many following bytes will be used to encode the length.
1718 */
1719TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1720 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001721 std::vector<uint32_t> app_id_lengths{143, 258};
1722
1723 for (uint32_t length : app_id_lengths) {
1724 const string app_id(length, 'a');
1725 vector<uint8_t> key_blob;
1726 vector<KeyCharacteristics> key_characteristics;
1727 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1728 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001729 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001730 .Digest(Digest::NONE)
1731 .AttestationChallenge(challenge)
1732 .AttestationApplicationId(app_id)
1733 .SetDefaultValidity(),
1734 &key_blob, &key_characteristics));
1735 ASSERT_GT(key_blob.size(), 0U);
1736 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001737 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001738
1739 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1740
1741 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001742 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001743
1744 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1745 ASSERT_GT(cert_chain_.size(), 0);
1746
1747 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1748 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1749 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1750 sw_enforced, hw_enforced, SecLevel(),
1751 cert_chain_[0].encodedCertificate));
1752
1753 CheckedDeleteKey(&key_blob);
1754 }
1755}
1756
1757/*
Qi Wud22ec842020-11-26 13:27:53 +08001758 * NewKeyGenerationTest.LimitedUsageEcdsa
1759 *
1760 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1761 * resulting keys have correct characteristics.
1762 */
1763TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001764 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001765 vector<uint8_t> key_blob;
1766 vector<KeyCharacteristics> key_characteristics;
1767 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001768 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001769 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001770 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1771 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001772 &key_blob, &key_characteristics));
1773
1774 ASSERT_GT(key_blob.size(), 0U);
1775 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001776 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001777
1778 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1779
1780 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001781 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001782
1783 // Check the usage count limit tag appears in the authorizations.
1784 AuthorizationSet auths;
1785 for (auto& entry : key_characteristics) {
1786 auths.push_back(AuthorizationSet(entry.authorizations));
1787 }
1788 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1789 << "key usage count limit " << 1U << " missing";
1790
1791 CheckedDeleteKey(&key_blob);
1792 }
1793}
1794
1795/*
Selene Huang31ab4042020-04-29 04:22:39 -07001796 * NewKeyGenerationTest.EcdsaDefaultSize
1797 *
David Drysdaledf09e542021-06-08 15:46:11 +01001798 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001799 * UNSUPPORTED_KEY_SIZE.
1800 */
1801TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1802 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1803 GenerateKey(AuthorizationSetBuilder()
1804 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1805 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001806 .Digest(Digest::NONE)
1807 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001808}
1809
1810/*
1811 * NewKeyGenerationTest.EcdsaInvalidSize
1812 *
1813 * Verifies that specifying an invalid key size for EC key generation returns
1814 * UNSUPPORTED_KEY_SIZE.
1815 */
1816TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdaledf09e542021-06-08 15:46:11 +01001817 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001818 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001819 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001820 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001821 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001822 .Digest(Digest::NONE)
1823 .SetDefaultValidity(),
1824 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001825 }
1826
David Drysdaledf09e542021-06-08 15:46:11 +01001827 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1828 GenerateKey(AuthorizationSetBuilder()
1829 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1830 .Authorization(TAG_KEY_SIZE, 190)
1831 .SigningKey()
1832 .Digest(Digest::NONE)
1833 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001834}
1835
1836/*
1837 * NewKeyGenerationTest.EcdsaMismatchKeySize
1838 *
1839 * Verifies that specifying mismatched key size and curve for EC key generation returns
1840 * INVALID_ARGUMENT.
1841 */
1842TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01001843 if (SecLevel() == SecurityLevel::STRONGBOX) {
1844 GTEST_SKIP() << "Test not applicable to StrongBox device";
1845 }
Selene Huang31ab4042020-04-29 04:22:39 -07001846
David Drysdaledf09e542021-06-08 15:46:11 +01001847 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01001848 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01001849 .Authorization(TAG_KEY_SIZE, 224)
1850 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01001851 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01001852 .Digest(Digest::NONE)
1853 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01001854 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07001855}
1856
1857/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001858 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001859 *
1860 * Verifies that keymint does not support any curve designated as unsupported.
1861 */
1862TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1863 Digest digest;
1864 if (SecLevel() == SecurityLevel::STRONGBOX) {
1865 digest = Digest::SHA_2_256;
1866 } else {
1867 digest = Digest::SHA_2_512;
1868 }
1869 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001870 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1871 .EcdsaSigningKey(curve)
1872 .Digest(digest)
1873 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001874 << "Failed to generate key on curve: " << curve;
1875 CheckedDeleteKey();
1876 }
1877}
1878
1879/*
1880 * NewKeyGenerationTest.Hmac
1881 *
1882 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1883 * characteristics.
1884 */
1885TEST_P(NewKeyGenerationTest, Hmac) {
1886 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1887 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001888 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001889 constexpr size_t key_size = 128;
1890 ASSERT_EQ(ErrorCode::OK,
1891 GenerateKey(
1892 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1893 TAG_MIN_MAC_LENGTH, 128),
1894 &key_blob, &key_characteristics));
1895
1896 ASSERT_GT(key_blob.size(), 0U);
1897 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001898 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001899
Shawn Willden7f424372021-01-10 18:06:50 -07001900 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1901 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1902 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1903 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001904
1905 CheckedDeleteKey(&key_blob);
1906 }
1907}
1908
1909/*
Selene Huang4f64c222021-04-13 19:54:36 -07001910 * NewKeyGenerationTest.HmacNoAttestation
1911 *
1912 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1913 * and app id are provided.
1914 */
1915TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1916 auto challenge = "hello";
1917 auto app_id = "foo";
1918
1919 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1920 vector<uint8_t> key_blob;
1921 vector<KeyCharacteristics> key_characteristics;
1922 constexpr size_t key_size = 128;
1923 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1924 .HmacKey(key_size)
1925 .Digest(digest)
1926 .AttestationChallenge(challenge)
1927 .AttestationApplicationId(app_id)
1928 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1929 &key_blob, &key_characteristics));
1930
1931 ASSERT_GT(key_blob.size(), 0U);
1932 ASSERT_EQ(cert_chain_.size(), 0);
1933 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001934 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001935
1936 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1937 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1938 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1939 << "Key size " << key_size << "missing";
1940
1941 CheckedDeleteKey(&key_blob);
1942 }
1943}
1944
1945/*
Qi Wud22ec842020-11-26 13:27:53 +08001946 * NewKeyGenerationTest.LimitedUsageHmac
1947 *
1948 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1949 * resulting keys have correct characteristics.
1950 */
1951TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1952 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1953 vector<uint8_t> key_blob;
1954 vector<KeyCharacteristics> key_characteristics;
1955 constexpr size_t key_size = 128;
1956 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1957 .HmacKey(key_size)
1958 .Digest(digest)
1959 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1960 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1961 &key_blob, &key_characteristics));
1962
1963 ASSERT_GT(key_blob.size(), 0U);
1964 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001965 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001966
1967 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1968 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1969 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1970 << "Key size " << key_size << "missing";
1971
1972 // Check the usage count limit tag appears in the authorizations.
1973 AuthorizationSet auths;
1974 for (auto& entry : key_characteristics) {
1975 auths.push_back(AuthorizationSet(entry.authorizations));
1976 }
1977 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1978 << "key usage count limit " << 1U << " missing";
1979
1980 CheckedDeleteKey(&key_blob);
1981 }
1982}
1983
1984/*
Selene Huang31ab4042020-04-29 04:22:39 -07001985 * NewKeyGenerationTest.HmacCheckKeySizes
1986 *
1987 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1988 */
1989TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1990 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1991 if (key_size < 64 || key_size % 8 != 0) {
1992 // To keep this test from being very slow, we only test a random fraction of
1993 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1994 // them, we expect to run ~40 of them in each run.
1995 if (key_size % 8 == 0 || random() % 10 == 0) {
1996 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1997 GenerateKey(AuthorizationSetBuilder()
1998 .HmacKey(key_size)
1999 .Digest(Digest::SHA_2_256)
2000 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2001 << "HMAC key size " << key_size << " invalid";
2002 }
2003 } else {
2004 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2005 .HmacKey(key_size)
2006 .Digest(Digest::SHA_2_256)
2007 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2008 << "Failed to generate HMAC key of size " << key_size;
2009 CheckedDeleteKey();
2010 }
2011 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002012 if (SecLevel() == SecurityLevel::STRONGBOX) {
2013 // STRONGBOX devices must not support keys larger than 512 bits.
2014 size_t key_size = 520;
2015 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2016 GenerateKey(AuthorizationSetBuilder()
2017 .HmacKey(key_size)
2018 .Digest(Digest::SHA_2_256)
2019 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2020 << "HMAC key size " << key_size << " unexpectedly valid";
2021 }
Selene Huang31ab4042020-04-29 04:22:39 -07002022}
2023
2024/*
2025 * NewKeyGenerationTest.HmacCheckMinMacLengths
2026 *
2027 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2028 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2029 * specific MAC length that failed, so reproducing a failed run will be easy.
2030 */
2031TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2032 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2033 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2034 // To keep this test from being very long, we only test a random fraction of
2035 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2036 // we expect to run ~17 of them in each run.
2037 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2038 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2039 GenerateKey(AuthorizationSetBuilder()
2040 .HmacKey(128)
2041 .Digest(Digest::SHA_2_256)
2042 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2043 << "HMAC min mac length " << min_mac_length << " invalid.";
2044 }
2045 } else {
2046 EXPECT_EQ(ErrorCode::OK,
2047 GenerateKey(AuthorizationSetBuilder()
2048 .HmacKey(128)
2049 .Digest(Digest::SHA_2_256)
2050 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2051 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2052 CheckedDeleteKey();
2053 }
2054 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002055
2056 // Minimum MAC length must be no more than 512 bits.
2057 size_t min_mac_length = 520;
2058 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2059 GenerateKey(AuthorizationSetBuilder()
2060 .HmacKey(128)
2061 .Digest(Digest::SHA_2_256)
2062 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2063 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002064}
2065
2066/*
2067 * NewKeyGenerationTest.HmacMultipleDigests
2068 *
2069 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2070 */
2071TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002072 if (SecLevel() == SecurityLevel::STRONGBOX) {
2073 GTEST_SKIP() << "Test not applicable to StrongBox device";
2074 }
Selene Huang31ab4042020-04-29 04:22:39 -07002075
2076 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2077 GenerateKey(AuthorizationSetBuilder()
2078 .HmacKey(128)
2079 .Digest(Digest::SHA1)
2080 .Digest(Digest::SHA_2_256)
2081 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2082}
2083
2084/*
2085 * NewKeyGenerationTest.HmacDigestNone
2086 *
2087 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2088 */
2089TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2090 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2091 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2092 128)));
2093
2094 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2095 GenerateKey(AuthorizationSetBuilder()
2096 .HmacKey(128)
2097 .Digest(Digest::NONE)
2098 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2099}
2100
Selene Huang4f64c222021-04-13 19:54:36 -07002101/*
2102 * NewKeyGenerationTest.AesNoAttestation
2103 *
2104 * Verifies that attestation parameters to AES keys are ignored and generateKey
2105 * will succeed.
2106 */
2107TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2108 auto challenge = "hello";
2109 auto app_id = "foo";
2110
2111 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2112 .Authorization(TAG_NO_AUTH_REQUIRED)
2113 .AesEncryptionKey(128)
2114 .EcbMode()
2115 .Padding(PaddingMode::PKCS7)
2116 .AttestationChallenge(challenge)
2117 .AttestationApplicationId(app_id)));
2118
2119 ASSERT_EQ(cert_chain_.size(), 0);
2120}
2121
2122/*
2123 * NewKeyGenerationTest.TripleDesNoAttestation
2124 *
2125 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2126 * will be successful. No attestation should be generated.
2127 */
2128TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2129 auto challenge = "hello";
2130 auto app_id = "foo";
2131
2132 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2133 .TripleDesEncryptionKey(168)
2134 .BlockMode(BlockMode::ECB)
2135 .Authorization(TAG_NO_AUTH_REQUIRED)
2136 .Padding(PaddingMode::NONE)
2137 .AttestationChallenge(challenge)
2138 .AttestationApplicationId(app_id)));
2139 ASSERT_EQ(cert_chain_.size(), 0);
2140}
2141
Selene Huang31ab4042020-04-29 04:22:39 -07002142INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2143
2144typedef KeyMintAidlTestBase SigningOperationsTest;
2145
2146/*
2147 * SigningOperationsTest.RsaSuccess
2148 *
2149 * Verifies that raw RSA signature operations succeed.
2150 */
2151TEST_P(SigningOperationsTest, RsaSuccess) {
2152 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2153 .RsaSigningKey(2048, 65537)
2154 .Digest(Digest::NONE)
2155 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002156 .Authorization(TAG_NO_AUTH_REQUIRED)
2157 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002158 string message = "12345678901234567890123456789012";
2159 string signature = SignMessage(
2160 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002161 LocalVerifyMessage(message, signature,
2162 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2163}
2164
2165/*
2166 * SigningOperationsTest.RsaAllPaddingsAndDigests
2167 *
2168 * Verifies RSA signature/verification for all padding modes and digests.
2169 */
2170TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2171 auto authorizations = AuthorizationSetBuilder()
2172 .Authorization(TAG_NO_AUTH_REQUIRED)
2173 .RsaSigningKey(2048, 65537)
2174 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2175 .Padding(PaddingMode::NONE)
2176 .Padding(PaddingMode::RSA_PSS)
2177 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2178 .SetDefaultValidity();
2179
2180 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2181
2182 string message(128, 'a');
2183 string corrupt_message(message);
2184 ++corrupt_message[corrupt_message.size() / 2];
2185
2186 for (auto padding :
2187 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2188 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2189 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2190 // Digesting only makes sense with padding.
2191 continue;
2192 }
2193
2194 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2195 // PSS requires digesting.
2196 continue;
2197 }
2198
2199 string signature =
2200 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2201 LocalVerifyMessage(message, signature,
2202 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2203 }
2204 }
Selene Huang31ab4042020-04-29 04:22:39 -07002205}
2206
2207/*
2208 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2209 *
Shawn Willden7f424372021-01-10 18:06:50 -07002210 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002211 */
2212TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2213 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2214 .Authorization(TAG_NO_AUTH_REQUIRED)
2215 .RsaSigningKey(2048, 65537)
2216 .Digest(Digest::NONE)
2217 .Padding(PaddingMode::NONE)
2218 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002219 .Authorization(TAG_APPLICATION_DATA, "appdata")
2220 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002221
2222 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2223
Selene Huang31ab4042020-04-29 04:22:39 -07002224 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2225 Begin(KeyPurpose::SIGN,
2226 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2227 AbortIfNeeded();
2228 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2229 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2230 .Digest(Digest::NONE)
2231 .Padding(PaddingMode::NONE)
2232 .Authorization(TAG_APPLICATION_ID, "clientid")));
2233 AbortIfNeeded();
2234 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2235 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2236 .Digest(Digest::NONE)
2237 .Padding(PaddingMode::NONE)
2238 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2239 AbortIfNeeded();
2240 EXPECT_EQ(ErrorCode::OK,
2241 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2242 .Digest(Digest::NONE)
2243 .Padding(PaddingMode::NONE)
2244 .Authorization(TAG_APPLICATION_DATA, "appdata")
2245 .Authorization(TAG_APPLICATION_ID, "clientid")));
2246 AbortIfNeeded();
2247}
2248
2249/*
2250 * SigningOperationsTest.RsaPssSha256Success
2251 *
2252 * Verifies that RSA-PSS signature operations succeed.
2253 */
2254TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2255 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2256 .RsaSigningKey(2048, 65537)
2257 .Digest(Digest::SHA_2_256)
2258 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002259 .Authorization(TAG_NO_AUTH_REQUIRED)
2260 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002261 // Use large message, which won't work without digesting.
2262 string message(1024, 'a');
2263 string signature = SignMessage(
2264 message,
2265 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2266}
2267
2268/*
2269 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2270 *
2271 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2272 * supports only unpadded operations.
2273 */
2274TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2275 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2276 .RsaSigningKey(2048, 65537)
2277 .Digest(Digest::NONE)
2278 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002279 .Padding(PaddingMode::NONE)
2280 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002281 string message = "12345678901234567890123456789012";
2282 string signature;
2283
2284 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2285 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2286 .Digest(Digest::NONE)
2287 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2288}
2289
2290/*
2291 * SigningOperationsTest.NoUserConfirmation
2292 *
2293 * Verifies that keymint rejects signing operations for keys with
2294 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2295 * presented.
2296 */
2297TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002298 if (SecLevel() == SecurityLevel::STRONGBOX) {
2299 GTEST_SKIP() << "Test not applicable to StrongBox device";
2300 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002301 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2302 .RsaSigningKey(1024, 65537)
2303 .Digest(Digest::NONE)
2304 .Padding(PaddingMode::NONE)
2305 .Authorization(TAG_NO_AUTH_REQUIRED)
2306 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2307 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002308
2309 const string message = "12345678901234567890123456789012";
2310 EXPECT_EQ(ErrorCode::OK,
2311 Begin(KeyPurpose::SIGN,
2312 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2313 string signature;
2314 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2315}
2316
2317/*
2318 * SigningOperationsTest.RsaPkcs1Sha256Success
2319 *
2320 * Verifies that digested RSA-PKCS1 signature operations succeed.
2321 */
2322TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2323 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2324 .RsaSigningKey(2048, 65537)
2325 .Digest(Digest::SHA_2_256)
2326 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002327 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2328 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002329 string message(1024, 'a');
2330 string signature = SignMessage(message, AuthorizationSetBuilder()
2331 .Digest(Digest::SHA_2_256)
2332 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2333}
2334
2335/*
2336 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2337 *
2338 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2339 */
2340TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2341 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2342 .RsaSigningKey(2048, 65537)
2343 .Digest(Digest::NONE)
2344 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002345 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2346 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002347 string message(53, 'a');
2348 string signature = SignMessage(message, AuthorizationSetBuilder()
2349 .Digest(Digest::NONE)
2350 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2351}
2352
2353/*
2354 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2355 *
2356 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2357 * given a too-long message.
2358 */
2359TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2360 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2361 .RsaSigningKey(2048, 65537)
2362 .Digest(Digest::NONE)
2363 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002364 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2365 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002366 string message(257, 'a');
2367
2368 EXPECT_EQ(ErrorCode::OK,
2369 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2370 .Digest(Digest::NONE)
2371 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2372 string signature;
2373 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2374}
2375
2376/*
2377 * SigningOperationsTest.RsaPssSha512TooSmallKey
2378 *
2379 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2380 * used with a key that is too small for the message.
2381 *
2382 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2383 * keymint specification requires that salt_size == digest_size, so the message will be
2384 * digest_size * 2 +
2385 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2386 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2387 * for a 1024-bit key.
2388 */
2389TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01002390 if (SecLevel() == SecurityLevel::STRONGBOX) {
2391 GTEST_SKIP() << "Test not applicable to StrongBox device";
2392 }
Selene Huang31ab4042020-04-29 04:22:39 -07002393 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2394 .RsaSigningKey(1024, 65537)
2395 .Digest(Digest::SHA_2_512)
2396 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002397 .Padding(PaddingMode::RSA_PSS)
2398 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002399 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2400 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2401 .Digest(Digest::SHA_2_512)
2402 .Padding(PaddingMode::RSA_PSS)));
2403}
2404
2405/*
2406 * SigningOperationsTest.RsaNoPaddingTooLong
2407 *
2408 * Verifies that raw RSA signature operations fail with the correct error code when
2409 * given a too-long message.
2410 */
2411TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2412 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2413 .RsaSigningKey(2048, 65537)
2414 .Digest(Digest::NONE)
2415 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002416 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2417 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002418 // One byte too long
2419 string message(2048 / 8 + 1, 'a');
2420 ASSERT_EQ(ErrorCode::OK,
2421 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2422 .Digest(Digest::NONE)
2423 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2424 string result;
2425 ErrorCode finish_error_code = Finish(message, &result);
2426 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2427 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2428
2429 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2430 message = string(128 * 1024, 'a');
2431 ASSERT_EQ(ErrorCode::OK,
2432 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2433 .Digest(Digest::NONE)
2434 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2435 finish_error_code = Finish(message, &result);
2436 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2437 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2438}
2439
2440/*
2441 * SigningOperationsTest.RsaAbort
2442 *
2443 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2444 * test, but the behavior should be algorithm and purpose-independent.
2445 */
2446TEST_P(SigningOperationsTest, RsaAbort) {
2447 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2448 .RsaSigningKey(2048, 65537)
2449 .Digest(Digest::NONE)
2450 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002451 .Padding(PaddingMode::NONE)
2452 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002453
2454 ASSERT_EQ(ErrorCode::OK,
2455 Begin(KeyPurpose::SIGN,
2456 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2457 EXPECT_EQ(ErrorCode::OK, Abort());
2458
2459 // Another abort should fail
2460 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2461
2462 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002463 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002464}
2465
2466/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002467 * SigningOperationsTest.RsaNonUniqueParams
2468 *
2469 * Verifies that an operation with multiple padding modes is rejected.
2470 */
2471TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2472 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2473 .RsaSigningKey(2048, 65537)
2474 .Digest(Digest::NONE)
2475 .Digest(Digest::SHA1)
2476 .Authorization(TAG_NO_AUTH_REQUIRED)
2477 .Padding(PaddingMode::NONE)
2478 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2479 .SetDefaultValidity()));
2480
2481 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2482 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2483 .Digest(Digest::NONE)
2484 .Padding(PaddingMode::NONE)
2485 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2486
Tommy Chiuc93c4392021-05-11 18:36:50 +08002487 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2488 .Digest(Digest::NONE)
2489 .Digest(Digest::SHA1)
2490 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2491 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002492
2493 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2494 Begin(KeyPurpose::SIGN,
2495 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2496}
2497
2498/*
Selene Huang31ab4042020-04-29 04:22:39 -07002499 * SigningOperationsTest.RsaUnsupportedPadding
2500 *
2501 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2502 * with a padding mode inappropriate for RSA.
2503 */
2504TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2505 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2506 .RsaSigningKey(2048, 65537)
2507 .Authorization(TAG_NO_AUTH_REQUIRED)
2508 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002509 .Padding(PaddingMode::PKCS7)
2510 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002511 ASSERT_EQ(
2512 ErrorCode::UNSUPPORTED_PADDING_MODE,
2513 Begin(KeyPurpose::SIGN,
2514 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002515 CheckedDeleteKey();
2516
2517 ASSERT_EQ(ErrorCode::OK,
2518 GenerateKey(
2519 AuthorizationSetBuilder()
2520 .RsaSigningKey(2048, 65537)
2521 .Authorization(TAG_NO_AUTH_REQUIRED)
2522 .Digest(Digest::SHA_2_256 /* supported digest */)
2523 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2524 .SetDefaultValidity()));
2525 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2526 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2527 .Digest(Digest::SHA_2_256)
2528 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002529}
2530
2531/*
2532 * SigningOperationsTest.RsaPssNoDigest
2533 *
2534 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2535 */
2536TEST_P(SigningOperationsTest, RsaNoDigest) {
2537 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2538 .RsaSigningKey(2048, 65537)
2539 .Authorization(TAG_NO_AUTH_REQUIRED)
2540 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002541 .Padding(PaddingMode::RSA_PSS)
2542 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002543 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2544 Begin(KeyPurpose::SIGN,
2545 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2546
2547 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2548 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2549}
2550
2551/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002552 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002553 *
2554 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2555 * supported in some cases (as validated in other tests), but a mode must be specified.
2556 */
2557TEST_P(SigningOperationsTest, RsaNoPadding) {
2558 // Padding must be specified
2559 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2560 .RsaKey(2048, 65537)
2561 .Authorization(TAG_NO_AUTH_REQUIRED)
2562 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002563 .Digest(Digest::NONE)
2564 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002565 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2566 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2567}
2568
2569/*
2570 * SigningOperationsTest.RsaShortMessage
2571 *
2572 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2573 */
2574TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2575 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2576 .Authorization(TAG_NO_AUTH_REQUIRED)
2577 .RsaSigningKey(2048, 65537)
2578 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002579 .Padding(PaddingMode::NONE)
2580 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002581
2582 // Barely shorter
2583 string message(2048 / 8 - 1, 'a');
2584 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2585
2586 // Much shorter
2587 message = "a";
2588 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2589}
2590
2591/*
2592 * SigningOperationsTest.RsaSignWithEncryptionKey
2593 *
2594 * Verifies that RSA encryption keys cannot be used to sign.
2595 */
2596TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2597 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2598 .Authorization(TAG_NO_AUTH_REQUIRED)
2599 .RsaEncryptionKey(2048, 65537)
2600 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002601 .Padding(PaddingMode::NONE)
2602 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002603 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2604 Begin(KeyPurpose::SIGN,
2605 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2606}
2607
2608/*
2609 * SigningOperationsTest.RsaSignTooLargeMessage
2610 *
2611 * Verifies that attempting a raw signature of a message which is the same length as the key,
2612 * but numerically larger than the public modulus, fails with the correct error.
2613 */
2614TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2615 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2616 .Authorization(TAG_NO_AUTH_REQUIRED)
2617 .RsaSigningKey(2048, 65537)
2618 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002619 .Padding(PaddingMode::NONE)
2620 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002621
2622 // Largest possible message will always be larger than the public modulus.
2623 string message(2048 / 8, static_cast<char>(0xff));
2624 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2625 .Authorization(TAG_NO_AUTH_REQUIRED)
2626 .Digest(Digest::NONE)
2627 .Padding(PaddingMode::NONE)));
2628 string signature;
2629 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2630}
2631
2632/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01002633 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2634 *
2635 * Verifies ECDSA signature/verification for all digests and curves.
2636 */
2637TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2638 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2639
2640 string message = "1234567890";
2641 string corrupt_message = "2234567890";
2642 for (auto curve : ValidCurves()) {
2643 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2644 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2645 .Authorization(TAG_NO_AUTH_REQUIRED)
2646 .EcdsaSigningKey(curve)
2647 .Digest(digests)
2648 .SetDefaultValidity());
2649 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2650 if (error != ErrorCode::OK) {
2651 continue;
2652 }
2653
2654 for (auto digest : digests) {
2655 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2656 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2657 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2658 }
2659
2660 auto rc = DeleteKey();
2661 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2662 }
2663}
2664
2665/*
Selene Huang31ab4042020-04-29 04:22:39 -07002666 * SigningOperationsTest.EcdsaAllCurves
2667 *
2668 * Verifies that ECDSA operations succeed with all possible curves.
2669 */
2670TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2671 for (auto curve : ValidCurves()) {
2672 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2673 .Authorization(TAG_NO_AUTH_REQUIRED)
2674 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002675 .Digest(Digest::SHA_2_256)
2676 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002677 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2678 if (error != ErrorCode::OK) continue;
2679
2680 string message(1024, 'a');
2681 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2682 CheckedDeleteKey();
2683 }
2684}
2685
2686/*
2687 * SigningOperationsTest.EcdsaNoDigestHugeData
2688 *
2689 * Verifies that ECDSA operations support very large messages, even without digesting. This
2690 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2691 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2692 * the framework.
2693 */
2694TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2695 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2696 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002697 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002698 .Digest(Digest::NONE)
2699 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002700 string message(1 * 1024, 'a');
2701 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2702}
2703
2704/*
2705 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2706 *
2707 * Verifies that using an EC key requires the correct app ID/data.
2708 */
2709TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2710 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2711 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002712 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002713 .Digest(Digest::NONE)
2714 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002715 .Authorization(TAG_APPLICATION_DATA, "appdata")
2716 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002717
2718 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2719
Selene Huang31ab4042020-04-29 04:22:39 -07002720 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2721 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2722 AbortIfNeeded();
2723 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2724 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2725 .Digest(Digest::NONE)
2726 .Authorization(TAG_APPLICATION_ID, "clientid")));
2727 AbortIfNeeded();
2728 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2729 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2730 .Digest(Digest::NONE)
2731 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2732 AbortIfNeeded();
2733 EXPECT_EQ(ErrorCode::OK,
2734 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2735 .Digest(Digest::NONE)
2736 .Authorization(TAG_APPLICATION_DATA, "appdata")
2737 .Authorization(TAG_APPLICATION_ID, "clientid")));
2738 AbortIfNeeded();
2739}
2740
2741/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002742 * SigningOperationsTest.EcdsaIncompatibleDigest
2743 *
2744 * Verifies that using an EC key requires compatible digest.
2745 */
2746TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2747 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2748 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002749 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002750 .Digest(Digest::NONE)
2751 .Digest(Digest::SHA1)
2752 .SetDefaultValidity()));
2753 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2754 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2755 AbortIfNeeded();
2756}
2757
2758/*
Selene Huang31ab4042020-04-29 04:22:39 -07002759 * SigningOperationsTest.AesEcbSign
2760 *
2761 * Verifies that attempts to use AES keys to sign fail in the correct way.
2762 */
2763TEST_P(SigningOperationsTest, AesEcbSign) {
2764 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2765 .Authorization(TAG_NO_AUTH_REQUIRED)
2766 .SigningKey()
2767 .AesEncryptionKey(128)
2768 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2769
2770 AuthorizationSet out_params;
2771 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2772 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2773 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2774 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2775}
2776
2777/*
2778 * SigningOperationsTest.HmacAllDigests
2779 *
2780 * Verifies that HMAC works with all digests.
2781 */
2782TEST_P(SigningOperationsTest, HmacAllDigests) {
2783 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2784 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2785 .Authorization(TAG_NO_AUTH_REQUIRED)
2786 .HmacKey(128)
2787 .Digest(digest)
2788 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2789 << "Failed to create HMAC key with digest " << digest;
2790 string message = "12345678901234567890123456789012";
2791 string signature = MacMessage(message, digest, 160);
2792 EXPECT_EQ(160U / 8U, signature.size())
2793 << "Failed to sign with HMAC key with digest " << digest;
2794 CheckedDeleteKey();
2795 }
2796}
2797
2798/*
2799 * SigningOperationsTest.HmacSha256TooLargeMacLength
2800 *
2801 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2802 * digest size.
2803 */
2804TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2805 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2806 .Authorization(TAG_NO_AUTH_REQUIRED)
2807 .HmacKey(128)
2808 .Digest(Digest::SHA_2_256)
2809 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2810 AuthorizationSet output_params;
2811 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2812 AuthorizationSetBuilder()
2813 .Digest(Digest::SHA_2_256)
2814 .Authorization(TAG_MAC_LENGTH, 264),
2815 &output_params));
2816}
2817
2818/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002819 * SigningOperationsTest.HmacSha256InvalidMacLength
2820 *
2821 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2822 * not a multiple of 8.
2823 */
2824TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2825 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2826 .Authorization(TAG_NO_AUTH_REQUIRED)
2827 .HmacKey(128)
2828 .Digest(Digest::SHA_2_256)
2829 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2830 AuthorizationSet output_params;
2831 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2832 AuthorizationSetBuilder()
2833 .Digest(Digest::SHA_2_256)
2834 .Authorization(TAG_MAC_LENGTH, 161),
2835 &output_params));
2836}
2837
2838/*
Selene Huang31ab4042020-04-29 04:22:39 -07002839 * SigningOperationsTest.HmacSha256TooSmallMacLength
2840 *
2841 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2842 * specified minimum MAC length.
2843 */
2844TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2845 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2846 .Authorization(TAG_NO_AUTH_REQUIRED)
2847 .HmacKey(128)
2848 .Digest(Digest::SHA_2_256)
2849 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2850 AuthorizationSet output_params;
2851 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2852 AuthorizationSetBuilder()
2853 .Digest(Digest::SHA_2_256)
2854 .Authorization(TAG_MAC_LENGTH, 120),
2855 &output_params));
2856}
2857
2858/*
2859 * SigningOperationsTest.HmacRfc4231TestCase3
2860 *
2861 * Validates against the test vectors from RFC 4231 test case 3.
2862 */
2863TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2864 string key(20, 0xaa);
2865 string message(50, 0xdd);
2866 uint8_t sha_224_expected[] = {
2867 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2868 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2869 };
2870 uint8_t sha_256_expected[] = {
2871 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2872 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2873 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2874 };
2875 uint8_t sha_384_expected[] = {
2876 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2877 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2878 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2879 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2880 };
2881 uint8_t sha_512_expected[] = {
2882 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2883 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2884 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2885 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2886 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2887 };
2888
2889 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2890 if (SecLevel() != SecurityLevel::STRONGBOX) {
2891 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2892 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2893 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2894 }
2895}
2896
2897/*
2898 * SigningOperationsTest.HmacRfc4231TestCase5
2899 *
2900 * Validates against the test vectors from RFC 4231 test case 5.
2901 */
2902TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2903 string key(20, 0x0c);
2904 string message = "Test With Truncation";
2905
2906 uint8_t sha_224_expected[] = {
2907 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2908 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2909 };
2910 uint8_t sha_256_expected[] = {
2911 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2912 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2913 };
2914 uint8_t sha_384_expected[] = {
2915 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2916 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2917 };
2918 uint8_t sha_512_expected[] = {
2919 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2920 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2921 };
2922
2923 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2924 if (SecLevel() != SecurityLevel::STRONGBOX) {
2925 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2926 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2927 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2928 }
2929}
2930
2931INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2932
2933typedef KeyMintAidlTestBase VerificationOperationsTest;
2934
2935/*
Selene Huang31ab4042020-04-29 04:22:39 -07002936 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2937 *
2938 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2939 */
2940TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2941 string key_material = "HelloThisIsAKey";
2942
2943 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002944 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002945 EXPECT_EQ(ErrorCode::OK,
2946 ImportKey(AuthorizationSetBuilder()
2947 .Authorization(TAG_NO_AUTH_REQUIRED)
2948 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2949 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2950 .Digest(Digest::SHA_2_256)
2951 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2952 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2953 EXPECT_EQ(ErrorCode::OK,
2954 ImportKey(AuthorizationSetBuilder()
2955 .Authorization(TAG_NO_AUTH_REQUIRED)
2956 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2957 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2958 .Digest(Digest::SHA_2_256)
2959 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2960 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2961
2962 string message = "This is a message.";
2963 string signature = SignMessage(
2964 signing_key, message,
2965 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2966
2967 // Signing key should not work.
2968 AuthorizationSet out_params;
2969 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2970 Begin(KeyPurpose::VERIFY, signing_key,
2971 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2972
2973 // Verification key should work.
2974 VerifyMessage(verification_key, message, signature,
2975 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2976
2977 CheckedDeleteKey(&signing_key);
2978 CheckedDeleteKey(&verification_key);
2979}
2980
2981INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2982
2983typedef KeyMintAidlTestBase ExportKeyTest;
2984
2985/*
2986 * ExportKeyTest.RsaUnsupportedKeyFormat
2987 *
2988 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2989 */
2990// TODO(seleneh) add ExportKey to GenerateKey
2991// check result
2992
2993class ImportKeyTest : public KeyMintAidlTestBase {
2994 public:
2995 template <TagType tag_type, Tag tag, typename ValueT>
2996 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2997 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002998 for (auto& entry : key_characteristics_) {
2999 if (entry.securityLevel == SecLevel()) {
3000 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3001 << "Tag " << tag << " with value " << expected
3002 << " not found at security level" << entry.securityLevel;
3003 } else {
3004 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3005 << "Tag " << tag << " found at security level " << entry.securityLevel;
3006 }
Selene Huang31ab4042020-04-29 04:22:39 -07003007 }
3008 }
3009
3010 void CheckOrigin() {
3011 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003012 // Origin isn't a crypto param, but it always lives with them.
3013 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003014 }
3015};
3016
3017/*
3018 * ImportKeyTest.RsaSuccess
3019 *
3020 * Verifies that importing and using an RSA key pair works correctly.
3021 */
3022TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003023 uint32_t key_size;
3024 string key;
3025
3026 if (SecLevel() == SecurityLevel::STRONGBOX) {
3027 key_size = 2048;
3028 key = rsa_2048_key;
3029 } else {
3030 key_size = 1024;
3031 key = rsa_key;
3032 }
3033
Selene Huang31ab4042020-04-29 04:22:39 -07003034 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3035 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003036 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003037 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003038 .Padding(PaddingMode::RSA_PSS)
3039 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003040 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003041
3042 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003043 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003044 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3045 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3046 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3047 CheckOrigin();
3048
3049 string message(1024 / 8, 'a');
3050 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3051 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003052 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003053}
3054
3055/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003056 * ImportKeyTest.RsaSuccessWithoutParams
3057 *
3058 * Verifies that importing and using an RSA key pair without specifying parameters
3059 * works correctly.
3060 */
3061TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3062 uint32_t key_size;
3063 string key;
3064
3065 if (SecLevel() == SecurityLevel::STRONGBOX) {
3066 key_size = 2048;
3067 key = rsa_2048_key;
3068 } else {
3069 key_size = 1024;
3070 key = rsa_key;
3071 }
3072
3073 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3074 .Authorization(TAG_NO_AUTH_REQUIRED)
3075 .SigningKey()
3076 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3077 .Digest(Digest::SHA_2_256)
3078 .Padding(PaddingMode::RSA_PSS)
3079 .SetDefaultValidity(),
3080 KeyFormat::PKCS8, key));
3081
3082 // Key size and public exponent are determined from the imported key material.
3083 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3084 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3085
3086 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3087 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3088 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3089 CheckOrigin();
3090
3091 string message(1024 / 8, 'a');
3092 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3093 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003094 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003095}
3096
3097/*
Selene Huang31ab4042020-04-29 04:22:39 -07003098 * ImportKeyTest.RsaKeySizeMismatch
3099 *
3100 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3101 * correct way.
3102 */
3103TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3104 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3105 ImportKey(AuthorizationSetBuilder()
3106 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3107 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003108 .Padding(PaddingMode::NONE)
3109 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003110 KeyFormat::PKCS8, rsa_key));
3111}
3112
3113/*
3114 * ImportKeyTest.RsaPublicExponentMismatch
3115 *
3116 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3117 * fails in the correct way.
3118 */
3119TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3120 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3121 ImportKey(AuthorizationSetBuilder()
3122 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3123 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003124 .Padding(PaddingMode::NONE)
3125 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003126 KeyFormat::PKCS8, rsa_key));
3127}
3128
3129/*
3130 * ImportKeyTest.EcdsaSuccess
3131 *
3132 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3133 */
3134TEST_P(ImportKeyTest, EcdsaSuccess) {
3135 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3136 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003137 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003138 .Digest(Digest::SHA_2_256)
3139 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003140 KeyFormat::PKCS8, ec_256_key));
3141
3142 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003143 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3144 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3145
3146 CheckOrigin();
3147
3148 string message(32, 'a');
3149 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3150 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003151 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003152}
3153
3154/*
3155 * ImportKeyTest.EcdsaP256RFC5915Success
3156 *
3157 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3158 * correctly.
3159 */
3160TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3161 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3162 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003163 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003164 .Digest(Digest::SHA_2_256)
3165 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003166 KeyFormat::PKCS8, ec_256_key_rfc5915));
3167
3168 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003169 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3170 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3171
3172 CheckOrigin();
3173
3174 string message(32, 'a');
3175 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3176 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003177 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003178}
3179
3180/*
3181 * ImportKeyTest.EcdsaP256SEC1Success
3182 *
3183 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3184 */
3185TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3186 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3187 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003188 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003189 .Digest(Digest::SHA_2_256)
3190 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003191 KeyFormat::PKCS8, ec_256_key_sec1));
3192
3193 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003194 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3195 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3196
3197 CheckOrigin();
3198
3199 string message(32, 'a');
3200 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3201 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003202 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003203}
3204
3205/*
3206 * ImportKeyTest.Ecdsa521Success
3207 *
3208 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3209 */
3210TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01003211 if (SecLevel() == SecurityLevel::STRONGBOX) {
3212 GTEST_SKIP() << "Test not applicable to StrongBox device";
3213 }
Selene Huang31ab4042020-04-29 04:22:39 -07003214 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3215 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003216 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003217 .Digest(Digest::SHA_2_256)
3218 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003219 KeyFormat::PKCS8, ec_521_key));
3220
3221 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003222 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3223 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3224 CheckOrigin();
3225
3226 string message(32, 'a');
3227 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3228 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003229 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003230}
3231
3232/*
Selene Huang31ab4042020-04-29 04:22:39 -07003233 * ImportKeyTest.EcdsaCurveMismatch
3234 *
3235 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3236 * the correct way.
3237 */
3238TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3239 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3240 ImportKey(AuthorizationSetBuilder()
3241 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003242 .Digest(Digest::NONE)
3243 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003244 KeyFormat::PKCS8, ec_256_key));
3245}
3246
3247/*
3248 * ImportKeyTest.AesSuccess
3249 *
3250 * Verifies that importing and using an AES key works.
3251 */
3252TEST_P(ImportKeyTest, AesSuccess) {
3253 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3254 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3255 .Authorization(TAG_NO_AUTH_REQUIRED)
3256 .AesEncryptionKey(key.size() * 8)
3257 .EcbMode()
3258 .Padding(PaddingMode::PKCS7),
3259 KeyFormat::RAW, key));
3260
3261 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3262 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3263 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3264 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3265 CheckOrigin();
3266
3267 string message = "Hello World!";
3268 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3269 string ciphertext = EncryptMessage(message, params);
3270 string plaintext = DecryptMessage(ciphertext, params);
3271 EXPECT_EQ(message, plaintext);
3272}
3273
3274/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003275 * ImportKeyTest.AesFailure
3276 *
3277 * Verifies that importing an invalid AES key fails.
3278 */
3279TEST_P(ImportKeyTest, AesFailure) {
3280 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3281 uint32_t bitlen = key.size() * 8;
3282 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003283 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003284 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003285 .Authorization(TAG_NO_AUTH_REQUIRED)
3286 .AesEncryptionKey(key_size)
3287 .EcbMode()
3288 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003289 KeyFormat::RAW, key);
3290 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003291 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3292 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003293 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003294
3295 // Explicit key size matches that of the provided key, but it's not a valid size.
3296 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3297 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3298 ImportKey(AuthorizationSetBuilder()
3299 .Authorization(TAG_NO_AUTH_REQUIRED)
3300 .AesEncryptionKey(long_key.size() * 8)
3301 .EcbMode()
3302 .Padding(PaddingMode::PKCS7),
3303 KeyFormat::RAW, long_key));
3304 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3305 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3306 ImportKey(AuthorizationSetBuilder()
3307 .Authorization(TAG_NO_AUTH_REQUIRED)
3308 .AesEncryptionKey(short_key.size() * 8)
3309 .EcbMode()
3310 .Padding(PaddingMode::PKCS7),
3311 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003312}
3313
3314/*
3315 * ImportKeyTest.TripleDesSuccess
3316 *
3317 * Verifies that importing and using a 3DES key works.
3318 */
3319TEST_P(ImportKeyTest, TripleDesSuccess) {
3320 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3321 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3322 .Authorization(TAG_NO_AUTH_REQUIRED)
3323 .TripleDesEncryptionKey(168)
3324 .EcbMode()
3325 .Padding(PaddingMode::PKCS7),
3326 KeyFormat::RAW, key));
3327
3328 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3329 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3330 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3331 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3332 CheckOrigin();
3333
3334 string message = "Hello World!";
3335 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3336 string ciphertext = EncryptMessage(message, params);
3337 string plaintext = DecryptMessage(ciphertext, params);
3338 EXPECT_EQ(message, plaintext);
3339}
3340
3341/*
3342 * ImportKeyTest.TripleDesFailure
3343 *
3344 * Verifies that importing an invalid 3DES key fails.
3345 */
3346TEST_P(ImportKeyTest, TripleDesFailure) {
3347 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003348 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003349 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003350 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003351 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003352 .Authorization(TAG_NO_AUTH_REQUIRED)
3353 .TripleDesEncryptionKey(key_size)
3354 .EcbMode()
3355 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003356 KeyFormat::RAW, key);
3357 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003358 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3359 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003360 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003361 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003362 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003363 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3364 ImportKey(AuthorizationSetBuilder()
3365 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003366 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003367 .EcbMode()
3368 .Padding(PaddingMode::PKCS7),
3369 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003370 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003371 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3372 ImportKey(AuthorizationSetBuilder()
3373 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003374 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003375 .EcbMode()
3376 .Padding(PaddingMode::PKCS7),
3377 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003378}
3379
3380/*
3381 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003382 *
3383 * Verifies that importing and using an HMAC key works.
3384 */
3385TEST_P(ImportKeyTest, HmacKeySuccess) {
3386 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3387 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3388 .Authorization(TAG_NO_AUTH_REQUIRED)
3389 .HmacKey(key.size() * 8)
3390 .Digest(Digest::SHA_2_256)
3391 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3392 KeyFormat::RAW, key));
3393
3394 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3395 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3396 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3397 CheckOrigin();
3398
3399 string message = "Hello World!";
3400 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3401 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3402}
3403
3404INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3405
3406auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003407 // IKeyMintDevice.aidl
3408 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3409 "020100" // INTEGER length 1 value 0x00 (version)
3410 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3411 "934bf94e2aa28a3f83c9f79297250262"
3412 "fbe3276b5a1c91159bbfa3ef8957aac8"
3413 "4b59b30b455a79c2973480823d8b3863"
3414 "c3deef4a8e243590268d80e18751a0e1"
3415 "30f67ce6a1ace9f79b95e097474febc9"
3416 "81195b1d13a69086c0863f66a7b7fdb4"
3417 "8792227b1ac5e2489febdf087ab54864"
3418 "83033a6f001ca5d1ec1e27f5c30f4cec"
3419 "2642074a39ae68aee552e196627a8e3d"
3420 "867e67a8c01b11e75f13cca0a97ab668"
3421 "b50cda07a8ecb7cd8e3dd7009c963653"
3422 "4f6f239cffe1fc8daa466f78b676c711"
3423 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3424 "99b801597d5220e307eaa5bee507fb94"
3425 "d1fa69f9e519b2de315bac92c36f2ea1"
3426 "fa1df4478c0ddedeae8c70e0233cd098"
3427 "040c" // OCTET STRING length 0x0c (initializationVector)
3428 "d796b02c370f1fa4cc0124f1"
3429 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3430 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3431 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3432 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3433 "3106" // SET length 0x06
3434 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3435 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3436 // } end SET
3437 // } end [1]
3438 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3439 "020120" // INTEGER length 1 value 0x20 (AES)
3440 // } end [2]
3441 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3442 "02020100" // INTEGER length 2 value 0x100
3443 // } end [3]
3444 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3445 "3103" // SET length 0x03 {
3446 "020101" // INTEGER length 1 value 0x01 (ECB)
3447 // } end SET
3448 // } end [4]
3449 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3450 "3103" // SET length 0x03 {
3451 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3452 // } end SET
3453 // } end [5]
3454 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3455 // (noAuthRequired)
3456 "0500" // NULL
3457 // } end [503]
3458 // } end SEQUENCE (AuthorizationList)
3459 // } end SEQUENCE (KeyDescription)
3460 "0420" // OCTET STRING length 0x20 (encryptedKey)
3461 "ccd540855f833a5e1480bfd2d36faf3a"
3462 "eee15df5beabe2691bc82dde2a7aa910"
3463 "0410" // OCTET STRING length 0x10 (tag)
3464 "64c9f689c60ff6223ab6e6999e0eb6e5"
3465 // } SEQUENCE (SecureKeyWrapper)
3466);
Selene Huang31ab4042020-04-29 04:22:39 -07003467
3468auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003469 // IKeyMintDevice.aidl
3470 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3471 "020100" // INTEGER length 1 value 0x00 (version)
3472 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3473 "aad93ed5924f283b4bb5526fbe7a1412"
3474 "f9d9749ec30db9062b29e574a8546f33"
3475 "c88732452f5b8e6a391ee76c39ed1712"
3476 "c61d8df6213dec1cffbc17a8c6d04c7b"
3477 "30893d8daa9b2015213e219468215532"
3478 "07f8f9931c4caba23ed3bee28b36947e"
3479 "47f10e0a5c3dc51c988a628daad3e5e1"
3480 "f4005e79c2d5a96c284b4b8d7e4948f3"
3481 "31e5b85dd5a236f85579f3ea1d1b8484"
3482 "87470bdb0ab4f81a12bee42c99fe0df4"
3483 "bee3759453e69ad1d68a809ce06b949f"
3484 "7694a990429b2fe81e066ff43e56a216"
3485 "02db70757922a4bcc23ab89f1e35da77"
3486 "586775f423e519c2ea394caf48a28d0c"
3487 "8020f1dcf6b3a68ec246f615ae96dae9"
3488 "a079b1f6eb959033c1af5c125fd94168"
3489 "040c" // OCTET STRING length 0x0c (initializationVector)
3490 "6d9721d08589581ab49204a3"
3491 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3492 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3493 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3494 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3495 "3106" // SET length 0x06
3496 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3497 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3498 // } end SET
3499 // } end [1]
3500 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3501 "020120" // INTEGER length 1 value 0x20 (AES)
3502 // } end [2]
3503 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3504 "02020100" // INTEGER length 2 value 0x100
3505 // } end [3]
3506 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3507 "3103" // SET length 0x03 {
3508 "020101" // INTEGER length 1 value 0x01 (ECB)
3509 // } end SET
3510 // } end [4]
3511 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3512 "3103" // SET length 0x03 {
3513 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3514 // } end SET
3515 // } end [5]
3516 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3517 // (noAuthRequired)
3518 "0500" // NULL
3519 // } end [503]
3520 // } end SEQUENCE (AuthorizationList)
3521 // } end SEQUENCE (KeyDescription)
3522 "0420" // OCTET STRING length 0x20 (encryptedKey)
3523 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3524 "c20d1f99a9a024a76f35c8e2cab9b68d"
3525 "0410" // OCTET STRING length 0x10 (tag)
3526 "2560c70109ae67c030f00b98b512a670"
3527 // } SEQUENCE (SecureKeyWrapper)
3528);
Selene Huang31ab4042020-04-29 04:22:39 -07003529
3530auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003531 // RFC 5208 s5
3532 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3533 "020100" // INTEGER length 1 value 0x00 (version)
3534 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3535 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3536 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3537 "0500" // NULL (parameters)
3538 // } SEQUENCE (AlgorithmIdentifier)
3539 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3540 // RFC 8017 A.1.2
3541 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3542 "020100" // INTEGER length 1 value 0x00 (version)
3543 "02820101" // INTEGER length 0x0101 (modulus) value...
3544 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3545 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3546 "7b06e673a837313d56b1c725150a3fef" // 0x30
3547 "86acbddc41bb759c2854eae32d35841e" // 0x40
3548 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3549 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3550 "312d7bd5921ffaea1347c157406fef71" // 0x70
3551 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3552 "f4645c11f5c1374c3886427411c44979" // 0x90
3553 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3554 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3555 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3556 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3557 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3558 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3559 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3560 "55" // 0x101
3561 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3562 "02820100" // INTEGER length 0x100 (privateExponent) value...
3563 "431447b6251908112b1ee76f99f3711a" // 0x10
3564 "52b6630960046c2de70de188d833f8b8" // 0x20
3565 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3566 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3567 "e710b630a03adc683b5d2c43080e52be" // 0x50
3568 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3569 "822bccff087d63c940ba8a45f670feb2" // 0x70
3570 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3571 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3572 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3573 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3574 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3575 "52659d5a5ba05b663737a8696281865b" // 0xd0
3576 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3577 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3578 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3579 "028181" // INTEGER length 0x81 (prime1) value...
3580 "00de392e18d682c829266cc3454e1d61" // 0x10
3581 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3582 "ff841be5bac82a164c5970007047b8c5" // 0x30
3583 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3584 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3585 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3586 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3587 "9e91346130748a6e3c124f9149d71c74" // 0x80
3588 "35"
3589 "028181" // INTEGER length 0x81 (prime2) value...
3590 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3591 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3592 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3593 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3594 "9ed39a2d934c880440aed8832f984316" // 0x50
3595 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3596 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3597 "b880677c068e1be936e81288815252a8" // 0x80
3598 "a1"
3599 "028180" // INTEGER length 0x80 (exponent1) value...
3600 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3601 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3602 "5a063212a4f105a3764743e53281988a" // 0x30
3603 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3604 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3605 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3606 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3607 "4719d6e2b9439823719cd08bcd031781" // 0x80
3608 "028181" // INTEGER length 0x81 (exponent2) value...
3609 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3610 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3611 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3612 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3613 "1254186af30b22c10582a8a43e34fe94" // 0x50
3614 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3615 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3616 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3617 "61"
3618 "028181" // INTEGER length 0x81 (coefficient) value...
3619 "00c931617c77829dfb1270502be9195c" // 0x10
3620 "8f2830885f57dba869536811e6864236" // 0x20
3621 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3622 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3623 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3624 "959356210723287b0affcc9f727044d4" // 0x60
3625 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3626 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3627 "22"
3628 // } SEQUENCE
3629 // } SEQUENCE ()
3630);
Selene Huang31ab4042020-04-29 04:22:39 -07003631
3632string zero_masking_key =
3633 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3634string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3635
3636class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3637
3638TEST_P(ImportWrappedKeyTest, Success) {
3639 auto wrapping_key_desc = AuthorizationSetBuilder()
3640 .RsaEncryptionKey(2048, 65537)
3641 .Digest(Digest::SHA_2_256)
3642 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003643 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3644 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003645
3646 ASSERT_EQ(ErrorCode::OK,
3647 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3648 AuthorizationSetBuilder()
3649 .Digest(Digest::SHA_2_256)
3650 .Padding(PaddingMode::RSA_OAEP)));
3651
3652 string message = "Hello World!";
3653 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3654 string ciphertext = EncryptMessage(message, params);
3655 string plaintext = DecryptMessage(ciphertext, params);
3656 EXPECT_EQ(message, plaintext);
3657}
3658
David Drysdaled2cc8c22021-04-15 13:29:45 +01003659/*
3660 * ImportWrappedKeyTest.SuccessSidsIgnored
3661 *
3662 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3663 * include Tag:USER_SECURE_ID.
3664 */
3665TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3666 auto wrapping_key_desc = AuthorizationSetBuilder()
3667 .RsaEncryptionKey(2048, 65537)
3668 .Digest(Digest::SHA_2_256)
3669 .Padding(PaddingMode::RSA_OAEP)
3670 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3671 .SetDefaultValidity();
3672
3673 int64_t password_sid = 42;
3674 int64_t biometric_sid = 24;
3675 ASSERT_EQ(ErrorCode::OK,
3676 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3677 AuthorizationSetBuilder()
3678 .Digest(Digest::SHA_2_256)
3679 .Padding(PaddingMode::RSA_OAEP),
3680 password_sid, biometric_sid));
3681
3682 string message = "Hello World!";
3683 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3684 string ciphertext = EncryptMessage(message, params);
3685 string plaintext = DecryptMessage(ciphertext, params);
3686 EXPECT_EQ(message, plaintext);
3687}
3688
Selene Huang31ab4042020-04-29 04:22:39 -07003689TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3690 auto wrapping_key_desc = AuthorizationSetBuilder()
3691 .RsaEncryptionKey(2048, 65537)
3692 .Digest(Digest::SHA_2_256)
3693 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003694 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3695 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003696
3697 ASSERT_EQ(ErrorCode::OK,
3698 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3699 AuthorizationSetBuilder()
3700 .Digest(Digest::SHA_2_256)
3701 .Padding(PaddingMode::RSA_OAEP)));
3702}
3703
3704TEST_P(ImportWrappedKeyTest, WrongMask) {
3705 auto wrapping_key_desc = AuthorizationSetBuilder()
3706 .RsaEncryptionKey(2048, 65537)
3707 .Digest(Digest::SHA_2_256)
3708 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003709 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3710 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003711
3712 ASSERT_EQ(
3713 ErrorCode::VERIFICATION_FAILED,
3714 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3715 AuthorizationSetBuilder()
3716 .Digest(Digest::SHA_2_256)
3717 .Padding(PaddingMode::RSA_OAEP)));
3718}
3719
3720TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3721 auto wrapping_key_desc = AuthorizationSetBuilder()
3722 .RsaEncryptionKey(2048, 65537)
3723 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003724 .Padding(PaddingMode::RSA_OAEP)
3725 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003726
3727 ASSERT_EQ(
3728 ErrorCode::INCOMPATIBLE_PURPOSE,
3729 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3730 AuthorizationSetBuilder()
3731 .Digest(Digest::SHA_2_256)
3732 .Padding(PaddingMode::RSA_OAEP)));
3733}
3734
David Drysdaled2cc8c22021-04-15 13:29:45 +01003735TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3736 auto wrapping_key_desc = AuthorizationSetBuilder()
3737 .RsaEncryptionKey(2048, 65537)
3738 .Digest(Digest::SHA_2_256)
3739 .Padding(PaddingMode::RSA_PSS)
3740 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3741 .SetDefaultValidity();
3742
3743 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3744 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3745 AuthorizationSetBuilder()
3746 .Digest(Digest::SHA_2_256)
3747 .Padding(PaddingMode::RSA_OAEP)));
3748}
3749
3750TEST_P(ImportWrappedKeyTest, WrongDigest) {
3751 auto wrapping_key_desc = AuthorizationSetBuilder()
3752 .RsaEncryptionKey(2048, 65537)
3753 .Digest(Digest::SHA_2_512)
3754 .Padding(PaddingMode::RSA_OAEP)
3755 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3756 .SetDefaultValidity();
3757
3758 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3759 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3760 AuthorizationSetBuilder()
3761 .Digest(Digest::SHA_2_256)
3762 .Padding(PaddingMode::RSA_OAEP)));
3763}
3764
Selene Huang31ab4042020-04-29 04:22:39 -07003765INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3766
3767typedef KeyMintAidlTestBase EncryptionOperationsTest;
3768
3769/*
3770 * EncryptionOperationsTest.RsaNoPaddingSuccess
3771 *
David Drysdale59cae642021-05-12 13:52:03 +01003772 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003773 */
3774TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003775 for (uint64_t exponent : {3, 65537}) {
3776 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3777 .Authorization(TAG_NO_AUTH_REQUIRED)
3778 .RsaEncryptionKey(2048, exponent)
3779 .Padding(PaddingMode::NONE)
3780 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003781
David Drysdaled2cc8c22021-04-15 13:29:45 +01003782 string message = string(2048 / 8, 'a');
3783 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003784 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003785 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003786
David Drysdale59cae642021-05-12 13:52:03 +01003787 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003788 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003789
David Drysdaled2cc8c22021-04-15 13:29:45 +01003790 // Unpadded RSA is deterministic
3791 EXPECT_EQ(ciphertext1, ciphertext2);
3792
3793 CheckedDeleteKey();
3794 }
Selene Huang31ab4042020-04-29 04:22:39 -07003795}
3796
3797/*
3798 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3799 *
David Drysdale59cae642021-05-12 13:52:03 +01003800 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003801 */
3802TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3803 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3804 .Authorization(TAG_NO_AUTH_REQUIRED)
3805 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003806 .Padding(PaddingMode::NONE)
3807 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003808
3809 string message = "1";
3810 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3811
David Drysdale59cae642021-05-12 13:52:03 +01003812 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003813 EXPECT_EQ(2048U / 8, ciphertext.size());
3814
3815 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3816 string plaintext = DecryptMessage(ciphertext, params);
3817
3818 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003819}
3820
3821/*
Selene Huang31ab4042020-04-29 04:22:39 -07003822 * EncryptionOperationsTest.RsaOaepSuccess
3823 *
David Drysdale59cae642021-05-12 13:52:03 +01003824 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003825 */
3826TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3827 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3828
3829 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01003830 ASSERT_EQ(ErrorCode::OK,
3831 GenerateKey(AuthorizationSetBuilder()
3832 .Authorization(TAG_NO_AUTH_REQUIRED)
3833 .RsaEncryptionKey(key_size, 65537)
3834 .Padding(PaddingMode::RSA_OAEP)
3835 .Digest(digests)
3836 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
3837 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003838
3839 string message = "Hello";
3840
3841 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01003842 SCOPED_TRACE(testing::Message() << "digest-" << digest);
3843
3844 auto params = AuthorizationSetBuilder()
3845 .Digest(digest)
3846 .Padding(PaddingMode::RSA_OAEP)
3847 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
3848 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003849 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3850 EXPECT_EQ(key_size / 8, ciphertext1.size());
3851
David Drysdale59cae642021-05-12 13:52:03 +01003852 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003853 EXPECT_EQ(key_size / 8, ciphertext2.size());
3854
3855 // OAEP randomizes padding so every result should be different (with astronomically high
3856 // probability).
3857 EXPECT_NE(ciphertext1, ciphertext2);
3858
3859 string plaintext1 = DecryptMessage(ciphertext1, params);
3860 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3861 string plaintext2 = DecryptMessage(ciphertext2, params);
3862 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3863
3864 // Decrypting corrupted ciphertext should fail.
3865 size_t offset_to_corrupt = random() % ciphertext1.size();
3866 char corrupt_byte;
3867 do {
3868 corrupt_byte = static_cast<char>(random() % 256);
3869 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3870 ciphertext1[offset_to_corrupt] = corrupt_byte;
3871
3872 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3873 string result;
3874 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3875 EXPECT_EQ(0U, result.size());
3876 }
3877}
3878
3879/*
3880 * EncryptionOperationsTest.RsaOaepInvalidDigest
3881 *
David Drysdale59cae642021-05-12 13:52:03 +01003882 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07003883 * without a digest.
3884 */
3885TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3886 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3887 .Authorization(TAG_NO_AUTH_REQUIRED)
3888 .RsaEncryptionKey(2048, 65537)
3889 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003890 .Digest(Digest::NONE)
3891 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003892
3893 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003894 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07003895}
3896
3897/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003898 * EncryptionOperationsTest.RsaOaepInvalidPadding
3899 *
David Drysdale59cae642021-05-12 13:52:03 +01003900 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01003901 * with a padding value that is only suitable for signing/verifying.
3902 */
3903TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3904 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3905 .Authorization(TAG_NO_AUTH_REQUIRED)
3906 .RsaEncryptionKey(2048, 65537)
3907 .Padding(PaddingMode::RSA_PSS)
3908 .Digest(Digest::NONE)
3909 .SetDefaultValidity()));
3910
3911 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003912 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003913}
3914
3915/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003916 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003917 *
David Drysdale59cae642021-05-12 13:52:03 +01003918 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003919 * with a different digest than was used to encrypt.
3920 */
3921TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01003922 if (SecLevel() == SecurityLevel::STRONGBOX) {
3923 GTEST_SKIP() << "Test not applicable to StrongBox device";
3924 }
Selene Huang31ab4042020-04-29 04:22:39 -07003925
3926 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3927 .Authorization(TAG_NO_AUTH_REQUIRED)
3928 .RsaEncryptionKey(1024, 65537)
3929 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003930 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3931 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003932 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01003933 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07003934 message,
3935 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3936
3937 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3938 .Digest(Digest::SHA_2_256)
3939 .Padding(PaddingMode::RSA_OAEP)));
3940 string result;
3941 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3942 EXPECT_EQ(0U, result.size());
3943}
3944
3945/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003946 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3947 *
David Drysdale59cae642021-05-12 13:52:03 +01003948 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003949 * digests.
3950 */
3951TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3952 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3953
3954 size_t key_size = 2048; // Need largish key for SHA-512 test.
3955 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3956 .OaepMGFDigest(digests)
3957 .Authorization(TAG_NO_AUTH_REQUIRED)
3958 .RsaEncryptionKey(key_size, 65537)
3959 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003960 .Digest(Digest::SHA_2_256)
3961 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003962
3963 string message = "Hello";
3964
3965 for (auto digest : digests) {
3966 auto params = AuthorizationSetBuilder()
3967 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3968 .Digest(Digest::SHA_2_256)
3969 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01003970 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003971 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3972 EXPECT_EQ(key_size / 8, ciphertext1.size());
3973
David Drysdale59cae642021-05-12 13:52:03 +01003974 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003975 EXPECT_EQ(key_size / 8, ciphertext2.size());
3976
3977 // OAEP randomizes padding so every result should be different (with astronomically high
3978 // probability).
3979 EXPECT_NE(ciphertext1, ciphertext2);
3980
3981 string plaintext1 = DecryptMessage(ciphertext1, params);
3982 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3983 string plaintext2 = DecryptMessage(ciphertext2, params);
3984 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3985
3986 // Decrypting corrupted ciphertext should fail.
3987 size_t offset_to_corrupt = random() % ciphertext1.size();
3988 char corrupt_byte;
3989 do {
3990 corrupt_byte = static_cast<char>(random() % 256);
3991 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3992 ciphertext1[offset_to_corrupt] = corrupt_byte;
3993
3994 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3995 string result;
3996 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3997 EXPECT_EQ(0U, result.size());
3998 }
3999}
4000
4001/*
4002 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4003 *
David Drysdale59cae642021-05-12 13:52:03 +01004004 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004005 * with incompatible MGF digest.
4006 */
4007TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4008 ASSERT_EQ(ErrorCode::OK,
4009 GenerateKey(AuthorizationSetBuilder()
4010 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4011 .Authorization(TAG_NO_AUTH_REQUIRED)
4012 .RsaEncryptionKey(2048, 65537)
4013 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004014 .Digest(Digest::SHA_2_256)
4015 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004016 string message = "Hello World!";
4017
4018 auto params = AuthorizationSetBuilder()
4019 .Padding(PaddingMode::RSA_OAEP)
4020 .Digest(Digest::SHA_2_256)
4021 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004022 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004023}
4024
4025/*
4026 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4027 *
4028 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4029 * with unsupported MGF digest.
4030 */
4031TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4032 ASSERT_EQ(ErrorCode::OK,
4033 GenerateKey(AuthorizationSetBuilder()
4034 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4035 .Authorization(TAG_NO_AUTH_REQUIRED)
4036 .RsaEncryptionKey(2048, 65537)
4037 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004038 .Digest(Digest::SHA_2_256)
4039 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004040 string message = "Hello World!";
4041
4042 auto params = AuthorizationSetBuilder()
4043 .Padding(PaddingMode::RSA_OAEP)
4044 .Digest(Digest::SHA_2_256)
4045 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004046 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004047}
4048
4049/*
Selene Huang31ab4042020-04-29 04:22:39 -07004050 * EncryptionOperationsTest.RsaPkcs1Success
4051 *
4052 * Verifies that RSA PKCS encryption/decrypts works.
4053 */
4054TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4055 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4056 .Authorization(TAG_NO_AUTH_REQUIRED)
4057 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004058 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4059 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004060
4061 string message = "Hello World!";
4062 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004063 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004064 EXPECT_EQ(2048U / 8, ciphertext1.size());
4065
David Drysdale59cae642021-05-12 13:52:03 +01004066 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004067 EXPECT_EQ(2048U / 8, ciphertext2.size());
4068
4069 // PKCS1 v1.5 randomizes padding so every result should be different.
4070 EXPECT_NE(ciphertext1, ciphertext2);
4071
4072 string plaintext = DecryptMessage(ciphertext1, params);
4073 EXPECT_EQ(message, plaintext);
4074
4075 // Decrypting corrupted ciphertext should fail.
4076 size_t offset_to_corrupt = random() % ciphertext1.size();
4077 char corrupt_byte;
4078 do {
4079 corrupt_byte = static_cast<char>(random() % 256);
4080 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4081 ciphertext1[offset_to_corrupt] = corrupt_byte;
4082
4083 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4084 string result;
4085 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4086 EXPECT_EQ(0U, result.size());
4087}
4088
4089/*
Selene Huang31ab4042020-04-29 04:22:39 -07004090 * EncryptionOperationsTest.EcdsaEncrypt
4091 *
4092 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4093 */
4094TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4095 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4096 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004097 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004098 .Digest(Digest::NONE)
4099 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004100 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4101 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4102 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4103}
4104
4105/*
4106 * EncryptionOperationsTest.HmacEncrypt
4107 *
4108 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4109 */
4110TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4111 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4112 .Authorization(TAG_NO_AUTH_REQUIRED)
4113 .HmacKey(128)
4114 .Digest(Digest::SHA_2_256)
4115 .Padding(PaddingMode::NONE)
4116 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4117 auto params = AuthorizationSetBuilder()
4118 .Digest(Digest::SHA_2_256)
4119 .Padding(PaddingMode::NONE)
4120 .Authorization(TAG_MAC_LENGTH, 128);
4121 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4122 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4123}
4124
4125/*
4126 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4127 *
4128 * Verifies that AES ECB mode works.
4129 */
4130TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4131 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4132 .Authorization(TAG_NO_AUTH_REQUIRED)
4133 .AesEncryptionKey(128)
4134 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4135 .Padding(PaddingMode::NONE)));
4136
4137 ASSERT_GT(key_blob_.size(), 0U);
4138 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4139
4140 // Two-block message.
4141 string message = "12345678901234567890123456789012";
4142 string ciphertext1 = EncryptMessage(message, params);
4143 EXPECT_EQ(message.size(), ciphertext1.size());
4144
4145 string ciphertext2 = EncryptMessage(string(message), params);
4146 EXPECT_EQ(message.size(), ciphertext2.size());
4147
4148 // ECB is deterministic.
4149 EXPECT_EQ(ciphertext1, ciphertext2);
4150
4151 string plaintext = DecryptMessage(ciphertext1, params);
4152 EXPECT_EQ(message, plaintext);
4153}
4154
4155/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004156 * EncryptionOperationsTest.AesEcbUnknownTag
4157 *
4158 * Verifies that AES ECB operations ignore unknown tags.
4159 */
4160TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4161 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4162 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4163 KeyParameter unknown_param;
4164 unknown_param.tag = unknown_tag;
4165
4166 vector<KeyCharacteristics> key_characteristics;
4167 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4168 .Authorization(TAG_NO_AUTH_REQUIRED)
4169 .AesEncryptionKey(128)
4170 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4171 .Padding(PaddingMode::NONE)
4172 .Authorization(unknown_param),
4173 &key_blob_, &key_characteristics));
4174 ASSERT_GT(key_blob_.size(), 0U);
4175
4176 // Unknown tags should not be returned in key characteristics.
4177 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4178 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4179 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4180 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4181
4182 // Encrypt without mentioning the unknown parameter.
4183 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4184 string message = "12345678901234567890123456789012";
4185 string ciphertext = EncryptMessage(message, params);
4186 EXPECT_EQ(message.size(), ciphertext.size());
4187
4188 // Decrypt including the unknown parameter.
4189 auto decrypt_params = AuthorizationSetBuilder()
4190 .BlockMode(BlockMode::ECB)
4191 .Padding(PaddingMode::NONE)
4192 .Authorization(unknown_param);
4193 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4194 EXPECT_EQ(message, plaintext);
4195}
4196
4197/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004198 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004199 *
4200 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4201 */
4202TEST_P(EncryptionOperationsTest, AesWrongMode) {
4203 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4204 .Authorization(TAG_NO_AUTH_REQUIRED)
4205 .AesEncryptionKey(128)
4206 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4207 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004208 ASSERT_GT(key_blob_.size(), 0U);
4209
Selene Huang31ab4042020-04-29 04:22:39 -07004210 EXPECT_EQ(
4211 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4212 Begin(KeyPurpose::ENCRYPT,
4213 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4214}
4215
4216/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004217 * EncryptionOperationsTest.AesWrongPadding
4218 *
4219 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4220 */
4221TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4222 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4223 .Authorization(TAG_NO_AUTH_REQUIRED)
4224 .AesEncryptionKey(128)
4225 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4226 .Padding(PaddingMode::NONE)));
4227 ASSERT_GT(key_blob_.size(), 0U);
4228
4229 EXPECT_EQ(
4230 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4231 Begin(KeyPurpose::ENCRYPT,
4232 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4233}
4234
4235/*
4236 * EncryptionOperationsTest.AesInvalidParams
4237 *
4238 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4239 */
4240TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4241 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4242 .Authorization(TAG_NO_AUTH_REQUIRED)
4243 .AesEncryptionKey(128)
4244 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4245 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4246 .Padding(PaddingMode::NONE)
4247 .Padding(PaddingMode::PKCS7)));
4248 ASSERT_GT(key_blob_.size(), 0U);
4249
4250 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4251 .BlockMode(BlockMode::CBC)
4252 .BlockMode(BlockMode::ECB)
4253 .Padding(PaddingMode::NONE));
4254 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4255 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4256
4257 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4258 .BlockMode(BlockMode::ECB)
4259 .Padding(PaddingMode::NONE)
4260 .Padding(PaddingMode::PKCS7));
4261 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4262 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4263}
4264
4265/*
Selene Huang31ab4042020-04-29 04:22:39 -07004266 * EncryptionOperationsTest.AesWrongPurpose
4267 *
4268 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4269 * specified.
4270 */
4271TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4272 auto err = GenerateKey(AuthorizationSetBuilder()
4273 .Authorization(TAG_NO_AUTH_REQUIRED)
4274 .AesKey(128)
4275 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4276 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4277 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4278 .Padding(PaddingMode::NONE));
4279 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4280 ASSERT_GT(key_blob_.size(), 0U);
4281
4282 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4283 .BlockMode(BlockMode::GCM)
4284 .Padding(PaddingMode::NONE)
4285 .Authorization(TAG_MAC_LENGTH, 128));
4286 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4287
4288 CheckedDeleteKey();
4289
4290 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4291 .Authorization(TAG_NO_AUTH_REQUIRED)
4292 .AesKey(128)
4293 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4294 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4295 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4296 .Padding(PaddingMode::NONE)));
4297
4298 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4299 .BlockMode(BlockMode::GCM)
4300 .Padding(PaddingMode::NONE)
4301 .Authorization(TAG_MAC_LENGTH, 128));
4302 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4303}
4304
4305/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004306 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004307 *
4308 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4309 * multiple of the block size and no padding is specified.
4310 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004311TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4312 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4313 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4314 .Authorization(TAG_NO_AUTH_REQUIRED)
4315 .AesEncryptionKey(128)
4316 .Authorization(TAG_BLOCK_MODE, blockMode)
4317 .Padding(PaddingMode::NONE)));
4318 // Message is slightly shorter than two blocks.
4319 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004320
David Drysdaled2cc8c22021-04-15 13:29:45 +01004321 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4322 AuthorizationSet out_params;
4323 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4324 string ciphertext;
4325 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4326 EXPECT_EQ(0U, ciphertext.size());
4327
4328 CheckedDeleteKey();
4329 }
Selene Huang31ab4042020-04-29 04:22:39 -07004330}
4331
4332/*
4333 * EncryptionOperationsTest.AesEcbPkcs7Padding
4334 *
4335 * Verifies that AES PKCS7 padding works for any message length.
4336 */
4337TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4338 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4339 .Authorization(TAG_NO_AUTH_REQUIRED)
4340 .AesEncryptionKey(128)
4341 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4342 .Padding(PaddingMode::PKCS7)));
4343
4344 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4345
4346 // Try various message lengths; all should work.
4347 for (size_t i = 0; i < 32; ++i) {
4348 string message(i, 'a');
4349 string ciphertext = EncryptMessage(message, params);
4350 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4351 string plaintext = DecryptMessage(ciphertext, params);
4352 EXPECT_EQ(message, plaintext);
4353 }
4354}
4355
4356/*
4357 * EncryptionOperationsTest.AesEcbWrongPadding
4358 *
4359 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4360 * specified.
4361 */
4362TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4363 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4364 .Authorization(TAG_NO_AUTH_REQUIRED)
4365 .AesEncryptionKey(128)
4366 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4367 .Padding(PaddingMode::NONE)));
4368
4369 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4370
4371 // Try various message lengths; all should fail
4372 for (size_t i = 0; i < 32; ++i) {
4373 string message(i, 'a');
4374 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4375 }
4376}
4377
4378/*
4379 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4380 *
4381 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4382 */
4383TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4384 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4385 .Authorization(TAG_NO_AUTH_REQUIRED)
4386 .AesEncryptionKey(128)
4387 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4388 .Padding(PaddingMode::PKCS7)));
4389
4390 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4391
4392 string message = "a";
4393 string ciphertext = EncryptMessage(message, params);
4394 EXPECT_EQ(16U, ciphertext.size());
4395 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07004396
Seth Moore7a55ae32021-06-23 14:28:11 -07004397 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
4398 ++ciphertext[ciphertext.size() / 2];
4399
4400 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4401 string plaintext;
4402 ErrorCode error = Finish(message, &plaintext);
4403 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
4404 // This is the expected error, we can exit the test now.
4405 return;
4406 } else {
4407 // Very small chance we got valid decryption, so try again.
4408 ASSERT_EQ(error, ErrorCode::OK);
4409 }
4410 }
4411 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07004412}
4413
4414vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4415 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004416 EXPECT_TRUE(iv);
4417 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004418}
4419
4420/*
4421 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4422 *
4423 * Verifies that AES CTR mode works.
4424 */
4425TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4426 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4427 .Authorization(TAG_NO_AUTH_REQUIRED)
4428 .AesEncryptionKey(128)
4429 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4430 .Padding(PaddingMode::NONE)));
4431
4432 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4433
4434 string message = "123";
4435 AuthorizationSet out_params;
4436 string ciphertext1 = EncryptMessage(message, params, &out_params);
4437 vector<uint8_t> iv1 = CopyIv(out_params);
4438 EXPECT_EQ(16U, iv1.size());
4439
4440 EXPECT_EQ(message.size(), ciphertext1.size());
4441
4442 out_params.Clear();
4443 string ciphertext2 = EncryptMessage(message, params, &out_params);
4444 vector<uint8_t> iv2 = CopyIv(out_params);
4445 EXPECT_EQ(16U, iv2.size());
4446
4447 // IVs should be random, so ciphertexts should differ.
4448 EXPECT_NE(ciphertext1, ciphertext2);
4449
4450 auto params_iv1 =
4451 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4452 auto params_iv2 =
4453 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4454
4455 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4456 EXPECT_EQ(message, plaintext);
4457 plaintext = DecryptMessage(ciphertext2, params_iv2);
4458 EXPECT_EQ(message, plaintext);
4459
4460 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4461 plaintext = DecryptMessage(ciphertext1, params_iv2);
4462 EXPECT_NE(message, plaintext);
4463 plaintext = DecryptMessage(ciphertext2, params_iv1);
4464 EXPECT_NE(message, plaintext);
4465}
4466
4467/*
4468 * EncryptionOperationsTest.AesIncremental
4469 *
4470 * Verifies that AES works, all modes, when provided data in various size increments.
4471 */
4472TEST_P(EncryptionOperationsTest, AesIncremental) {
4473 auto block_modes = {
4474 BlockMode::ECB,
4475 BlockMode::CBC,
4476 BlockMode::CTR,
4477 BlockMode::GCM,
4478 };
4479
4480 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4481 .Authorization(TAG_NO_AUTH_REQUIRED)
4482 .AesEncryptionKey(128)
4483 .BlockMode(block_modes)
4484 .Padding(PaddingMode::NONE)
4485 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4486
4487 for (int increment = 1; increment <= 240; ++increment) {
4488 for (auto block_mode : block_modes) {
4489 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004490 auto params =
4491 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4492 if (block_mode == BlockMode::GCM) {
4493 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4494 }
Selene Huang31ab4042020-04-29 04:22:39 -07004495
4496 AuthorizationSet output_params;
4497 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4498
4499 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004500 string to_send;
4501 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004502 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004503 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004504 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4505 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004506
4507 switch (block_mode) {
4508 case BlockMode::GCM:
4509 EXPECT_EQ(message.size() + 16, ciphertext.size());
4510 break;
4511 case BlockMode::CTR:
4512 EXPECT_EQ(message.size(), ciphertext.size());
4513 break;
4514 case BlockMode::CBC:
4515 case BlockMode::ECB:
4516 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4517 break;
4518 }
4519
4520 auto iv = output_params.GetTagValue(TAG_NONCE);
4521 switch (block_mode) {
4522 case BlockMode::CBC:
4523 case BlockMode::GCM:
4524 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004525 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4526 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4527 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004528 break;
4529
4530 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004531 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004532 break;
4533 }
4534
4535 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4536 << "Decrypt begin() failed for block mode " << block_mode;
4537
4538 string plaintext;
4539 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004540 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004541 }
4542 ErrorCode error = Finish(to_send, &plaintext);
4543 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4544 << " and increment " << increment;
4545 if (error == ErrorCode::OK) {
4546 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4547 << block_mode << " and increment " << increment;
4548 }
4549 }
4550 }
4551}
4552
4553struct AesCtrSp80038aTestVector {
4554 const char* key;
4555 const char* nonce;
4556 const char* plaintext;
4557 const char* ciphertext;
4558};
4559
4560// These test vectors are taken from
4561// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4562static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4563 // AES-128
4564 {
4565 "2b7e151628aed2a6abf7158809cf4f3c",
4566 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4567 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4568 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4569 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4570 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4571 },
4572 // AES-192
4573 {
4574 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4575 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4576 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4577 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4578 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4579 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4580 },
4581 // AES-256
4582 {
4583 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4584 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4585 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4586 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4587 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4588 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4589 },
4590};
4591
4592/*
4593 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4594 *
4595 * Verifies AES CTR implementation against SP800-38A test vectors.
4596 */
4597TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4598 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4599 for (size_t i = 0; i < 3; i++) {
4600 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4601 const string key = hex2str(test.key);
4602 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4603 InvalidSizes.end())
4604 continue;
4605 const string nonce = hex2str(test.nonce);
4606 const string plaintext = hex2str(test.plaintext);
4607 const string ciphertext = hex2str(test.ciphertext);
4608 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4609 }
4610}
4611
4612/*
4613 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4614 *
4615 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4616 */
4617TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4618 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4619 .Authorization(TAG_NO_AUTH_REQUIRED)
4620 .AesEncryptionKey(128)
4621 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4622 .Padding(PaddingMode::PKCS7)));
4623 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4624 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4625}
4626
4627/*
4628 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4629 *
4630 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4631 */
4632TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4633 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4634 .Authorization(TAG_NO_AUTH_REQUIRED)
4635 .AesEncryptionKey(128)
4636 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4637 .Authorization(TAG_CALLER_NONCE)
4638 .Padding(PaddingMode::NONE)));
4639
4640 auto params = AuthorizationSetBuilder()
4641 .BlockMode(BlockMode::CTR)
4642 .Padding(PaddingMode::NONE)
4643 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4644 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4645
4646 params = AuthorizationSetBuilder()
4647 .BlockMode(BlockMode::CTR)
4648 .Padding(PaddingMode::NONE)
4649 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4650 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4651
4652 params = AuthorizationSetBuilder()
4653 .BlockMode(BlockMode::CTR)
4654 .Padding(PaddingMode::NONE)
4655 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4656 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4657}
4658
4659/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004660 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004661 *
4662 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4663 */
4664TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4665 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4666 .Authorization(TAG_NO_AUTH_REQUIRED)
4667 .AesEncryptionKey(128)
4668 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4669 .Padding(PaddingMode::NONE)));
4670 // Two-block message.
4671 string message = "12345678901234567890123456789012";
4672 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4673 AuthorizationSet out_params;
4674 string ciphertext1 = EncryptMessage(message, params, &out_params);
4675 vector<uint8_t> iv1 = CopyIv(out_params);
4676 EXPECT_EQ(message.size(), ciphertext1.size());
4677
4678 out_params.Clear();
4679
4680 string ciphertext2 = EncryptMessage(message, params, &out_params);
4681 vector<uint8_t> iv2 = CopyIv(out_params);
4682 EXPECT_EQ(message.size(), ciphertext2.size());
4683
4684 // IVs should be random, so ciphertexts should differ.
4685 EXPECT_NE(ciphertext1, ciphertext2);
4686
4687 params.push_back(TAG_NONCE, iv1);
4688 string plaintext = DecryptMessage(ciphertext1, params);
4689 EXPECT_EQ(message, plaintext);
4690}
4691
4692/*
4693 * EncryptionOperationsTest.AesCallerNonce
4694 *
4695 * Verifies that AES caller-provided nonces work correctly.
4696 */
4697TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4698 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4699 .Authorization(TAG_NO_AUTH_REQUIRED)
4700 .AesEncryptionKey(128)
4701 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4702 .Authorization(TAG_CALLER_NONCE)
4703 .Padding(PaddingMode::NONE)));
4704
4705 string message = "12345678901234567890123456789012";
4706
4707 // Don't specify nonce, should get a random one.
4708 AuthorizationSetBuilder params =
4709 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4710 AuthorizationSet out_params;
4711 string ciphertext = EncryptMessage(message, params, &out_params);
4712 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004713 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004714
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004715 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004716 string plaintext = DecryptMessage(ciphertext, params);
4717 EXPECT_EQ(message, plaintext);
4718
4719 // Now specify a nonce, should also work.
4720 params = AuthorizationSetBuilder()
4721 .BlockMode(BlockMode::CBC)
4722 .Padding(PaddingMode::NONE)
4723 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4724 out_params.Clear();
4725 ciphertext = EncryptMessage(message, params, &out_params);
4726
4727 // Decrypt with correct nonce.
4728 plaintext = DecryptMessage(ciphertext, params);
4729 EXPECT_EQ(message, plaintext);
4730
4731 // Try with wrong nonce.
4732 params = AuthorizationSetBuilder()
4733 .BlockMode(BlockMode::CBC)
4734 .Padding(PaddingMode::NONE)
4735 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4736 plaintext = DecryptMessage(ciphertext, params);
4737 EXPECT_NE(message, plaintext);
4738}
4739
4740/*
4741 * EncryptionOperationsTest.AesCallerNonceProhibited
4742 *
4743 * Verifies that caller-provided nonces are not permitted when not specified in the key
4744 * authorizations.
4745 */
4746TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4747 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4748 .Authorization(TAG_NO_AUTH_REQUIRED)
4749 .AesEncryptionKey(128)
4750 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4751 .Padding(PaddingMode::NONE)));
4752
4753 string message = "12345678901234567890123456789012";
4754
4755 // Don't specify nonce, should get a random one.
4756 AuthorizationSetBuilder params =
4757 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4758 AuthorizationSet out_params;
4759 string ciphertext = EncryptMessage(message, params, &out_params);
4760 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004761 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004762
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004763 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004764 string plaintext = DecryptMessage(ciphertext, params);
4765 EXPECT_EQ(message, plaintext);
4766
4767 // Now specify a nonce, should fail
4768 params = AuthorizationSetBuilder()
4769 .BlockMode(BlockMode::CBC)
4770 .Padding(PaddingMode::NONE)
4771 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4772 out_params.Clear();
4773 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4774}
4775
4776/*
4777 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4778 *
4779 * Verifies that AES GCM mode works.
4780 */
4781TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4782 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4783 .Authorization(TAG_NO_AUTH_REQUIRED)
4784 .AesEncryptionKey(128)
4785 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4786 .Padding(PaddingMode::NONE)
4787 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4788
4789 string aad = "foobar";
4790 string message = "123456789012345678901234567890123456";
4791
4792 auto begin_params = AuthorizationSetBuilder()
4793 .BlockMode(BlockMode::GCM)
4794 .Padding(PaddingMode::NONE)
4795 .Authorization(TAG_MAC_LENGTH, 128);
4796
Selene Huang31ab4042020-04-29 04:22:39 -07004797 // Encrypt
4798 AuthorizationSet begin_out_params;
4799 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4800 << "Begin encrypt";
4801 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004802 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4803 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004804 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4805
4806 // Grab nonce
4807 begin_params.push_back(begin_out_params);
4808
4809 // Decrypt.
4810 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004811 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004812 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004813 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004814 EXPECT_EQ(message.length(), plaintext.length());
4815 EXPECT_EQ(message, plaintext);
4816}
4817
4818/*
4819 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4820 *
4821 * Verifies that AES GCM mode works, even when there's a long delay
4822 * between operations.
4823 */
4824TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4825 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4826 .Authorization(TAG_NO_AUTH_REQUIRED)
4827 .AesEncryptionKey(128)
4828 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4829 .Padding(PaddingMode::NONE)
4830 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4831
4832 string aad = "foobar";
4833 string message = "123456789012345678901234567890123456";
4834
4835 auto begin_params = AuthorizationSetBuilder()
4836 .BlockMode(BlockMode::GCM)
4837 .Padding(PaddingMode::NONE)
4838 .Authorization(TAG_MAC_LENGTH, 128);
4839
Selene Huang31ab4042020-04-29 04:22:39 -07004840 // Encrypt
4841 AuthorizationSet begin_out_params;
4842 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4843 << "Begin encrypt";
4844 string ciphertext;
4845 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004846 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004847 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004848 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004849
4850 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4851
4852 // Grab nonce
4853 begin_params.push_back(begin_out_params);
4854
4855 // Decrypt.
4856 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4857 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004858 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004859 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004860 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004861 sleep(5);
4862 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4863 EXPECT_EQ(message.length(), plaintext.length());
4864 EXPECT_EQ(message, plaintext);
4865}
4866
4867/*
4868 * EncryptionOperationsTest.AesGcmDifferentNonces
4869 *
4870 * Verifies that encrypting the same data with different nonces produces different outputs.
4871 */
4872TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4873 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4874 .Authorization(TAG_NO_AUTH_REQUIRED)
4875 .AesEncryptionKey(128)
4876 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4877 .Padding(PaddingMode::NONE)
4878 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4879 .Authorization(TAG_CALLER_NONCE)));
4880
4881 string aad = "foobar";
4882 string message = "123456789012345678901234567890123456";
4883 string nonce1 = "000000000000";
4884 string nonce2 = "111111111111";
4885 string nonce3 = "222222222222";
4886
4887 string ciphertext1 =
4888 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4889 string ciphertext2 =
4890 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4891 string ciphertext3 =
4892 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4893
4894 ASSERT_NE(ciphertext1, ciphertext2);
4895 ASSERT_NE(ciphertext1, ciphertext3);
4896 ASSERT_NE(ciphertext2, ciphertext3);
4897}
4898
4899/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004900 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4901 *
4902 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4903 */
4904TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4905 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4906 .Authorization(TAG_NO_AUTH_REQUIRED)
4907 .AesEncryptionKey(128)
4908 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4909 .Padding(PaddingMode::NONE)
4910 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4911
4912 string aad = "foobar";
4913 string message = "123456789012345678901234567890123456";
4914
4915 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4916 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4917 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4918
4919 ASSERT_NE(ciphertext1, ciphertext2);
4920 ASSERT_NE(ciphertext1, ciphertext3);
4921 ASSERT_NE(ciphertext2, ciphertext3);
4922}
4923
4924/*
Selene Huang31ab4042020-04-29 04:22:39 -07004925 * EncryptionOperationsTest.AesGcmTooShortTag
4926 *
4927 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4928 */
4929TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4930 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4931 .Authorization(TAG_NO_AUTH_REQUIRED)
4932 .AesEncryptionKey(128)
4933 .BlockMode(BlockMode::GCM)
4934 .Padding(PaddingMode::NONE)
4935 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4936 string message = "123456789012345678901234567890123456";
4937 auto params = AuthorizationSetBuilder()
4938 .BlockMode(BlockMode::GCM)
4939 .Padding(PaddingMode::NONE)
4940 .Authorization(TAG_MAC_LENGTH, 96);
4941
4942 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4943}
4944
4945/*
4946 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4947 *
4948 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4949 */
4950TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4951 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4952 .Authorization(TAG_NO_AUTH_REQUIRED)
4953 .AesEncryptionKey(128)
4954 .BlockMode(BlockMode::GCM)
4955 .Padding(PaddingMode::NONE)
4956 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4957 string aad = "foobar";
4958 string message = "123456789012345678901234567890123456";
4959 auto params = AuthorizationSetBuilder()
4960 .BlockMode(BlockMode::GCM)
4961 .Padding(PaddingMode::NONE)
4962 .Authorization(TAG_MAC_LENGTH, 128);
4963
Selene Huang31ab4042020-04-29 04:22:39 -07004964 // Encrypt
4965 AuthorizationSet begin_out_params;
4966 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4967 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004968 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004969
4970 AuthorizationSet finish_out_params;
4971 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004972 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4973 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004974
4975 params = AuthorizationSetBuilder()
4976 .Authorizations(begin_out_params)
4977 .BlockMode(BlockMode::GCM)
4978 .Padding(PaddingMode::NONE)
4979 .Authorization(TAG_MAC_LENGTH, 96);
4980
4981 // Decrypt.
4982 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4983}
4984
4985/*
4986 * EncryptionOperationsTest.AesGcmCorruptKey
4987 *
4988 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4989 */
4990TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4991 const uint8_t nonce_bytes[] = {
4992 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4993 };
4994 string nonce = make_string(nonce_bytes);
4995 const uint8_t ciphertext_bytes[] = {
4996 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4997 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4998 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4999 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5000 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5001 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5002 };
5003 string ciphertext = make_string(ciphertext_bytes);
5004
5005 auto params = AuthorizationSetBuilder()
5006 .BlockMode(BlockMode::GCM)
5007 .Padding(PaddingMode::NONE)
5008 .Authorization(TAG_MAC_LENGTH, 128)
5009 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5010
5011 auto import_params = AuthorizationSetBuilder()
5012 .Authorization(TAG_NO_AUTH_REQUIRED)
5013 .AesEncryptionKey(128)
5014 .BlockMode(BlockMode::GCM)
5015 .Padding(PaddingMode::NONE)
5016 .Authorization(TAG_CALLER_NONCE)
5017 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5018
5019 // Import correct key and decrypt
5020 const uint8_t key_bytes[] = {
5021 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5022 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5023 };
5024 string key = make_string(key_bytes);
5025 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5026 string plaintext = DecryptMessage(ciphertext, params);
5027 CheckedDeleteKey();
5028
5029 // Corrupt key and attempt to decrypt
5030 key[0] = 0;
5031 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5032 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5033 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5034 CheckedDeleteKey();
5035}
5036
5037/*
5038 * EncryptionOperationsTest.AesGcmAadNoData
5039 *
5040 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5041 * encrypt.
5042 */
5043TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5044 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5045 .Authorization(TAG_NO_AUTH_REQUIRED)
5046 .AesEncryptionKey(128)
5047 .BlockMode(BlockMode::GCM)
5048 .Padding(PaddingMode::NONE)
5049 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5050
5051 string aad = "1234567890123456";
5052 auto params = AuthorizationSetBuilder()
5053 .BlockMode(BlockMode::GCM)
5054 .Padding(PaddingMode::NONE)
5055 .Authorization(TAG_MAC_LENGTH, 128);
5056
Selene Huang31ab4042020-04-29 04:22:39 -07005057 // Encrypt
5058 AuthorizationSet begin_out_params;
5059 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5060 string ciphertext;
5061 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005062 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5063 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005064 EXPECT_TRUE(finish_out_params.empty());
5065
5066 // Grab nonce
5067 params.push_back(begin_out_params);
5068
5069 // Decrypt.
5070 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005071 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005072 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005073 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005074
5075 EXPECT_TRUE(finish_out_params.empty());
5076
5077 EXPECT_EQ("", plaintext);
5078}
5079
5080/*
5081 * EncryptionOperationsTest.AesGcmMultiPartAad
5082 *
5083 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5084 * chunks.
5085 */
5086TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5087 const size_t tag_bits = 128;
5088 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5089 .Authorization(TAG_NO_AUTH_REQUIRED)
5090 .AesEncryptionKey(128)
5091 .BlockMode(BlockMode::GCM)
5092 .Padding(PaddingMode::NONE)
5093 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5094
5095 string message = "123456789012345678901234567890123456";
5096 auto begin_params = AuthorizationSetBuilder()
5097 .BlockMode(BlockMode::GCM)
5098 .Padding(PaddingMode::NONE)
5099 .Authorization(TAG_MAC_LENGTH, tag_bits);
5100 AuthorizationSet begin_out_params;
5101
Selene Huang31ab4042020-04-29 04:22:39 -07005102 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5103
5104 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005105 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5106 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005107 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005108 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5109 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005110
Selene Huang31ab4042020-04-29 04:22:39 -07005111 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005112 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005113
5114 // Grab nonce.
5115 begin_params.push_back(begin_out_params);
5116
5117 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005118 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005119 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005120 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005121 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005122 EXPECT_EQ(message, plaintext);
5123}
5124
5125/*
5126 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5127 *
5128 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5129 */
5130TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5131 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5132 .Authorization(TAG_NO_AUTH_REQUIRED)
5133 .AesEncryptionKey(128)
5134 .BlockMode(BlockMode::GCM)
5135 .Padding(PaddingMode::NONE)
5136 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5137
5138 string message = "123456789012345678901234567890123456";
5139 auto begin_params = AuthorizationSetBuilder()
5140 .BlockMode(BlockMode::GCM)
5141 .Padding(PaddingMode::NONE)
5142 .Authorization(TAG_MAC_LENGTH, 128);
5143 AuthorizationSet begin_out_params;
5144
Selene Huang31ab4042020-04-29 04:22:39 -07005145 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5146
Shawn Willden92d79c02021-02-19 07:31:55 -07005147 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005148 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005149 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5150 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005151
David Drysdaled2cc8c22021-04-15 13:29:45 +01005152 // The failure should have already cancelled the operation.
5153 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5154
Shawn Willden92d79c02021-02-19 07:31:55 -07005155 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005156}
5157
5158/*
5159 * EncryptionOperationsTest.AesGcmBadAad
5160 *
5161 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5162 */
5163TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5164 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5165 .Authorization(TAG_NO_AUTH_REQUIRED)
5166 .AesEncryptionKey(128)
5167 .BlockMode(BlockMode::GCM)
5168 .Padding(PaddingMode::NONE)
5169 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5170
5171 string message = "12345678901234567890123456789012";
5172 auto begin_params = AuthorizationSetBuilder()
5173 .BlockMode(BlockMode::GCM)
5174 .Padding(PaddingMode::NONE)
5175 .Authorization(TAG_MAC_LENGTH, 128);
5176
Selene Huang31ab4042020-04-29 04:22:39 -07005177 // Encrypt
5178 AuthorizationSet begin_out_params;
5179 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005180 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005181 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005182 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005183
5184 // Grab nonce
5185 begin_params.push_back(begin_out_params);
5186
Selene Huang31ab4042020-04-29 04:22:39 -07005187 // Decrypt.
5188 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005189 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005190 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005191 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005192}
5193
5194/*
5195 * EncryptionOperationsTest.AesGcmWrongNonce
5196 *
5197 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5198 */
5199TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5200 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5201 .Authorization(TAG_NO_AUTH_REQUIRED)
5202 .AesEncryptionKey(128)
5203 .BlockMode(BlockMode::GCM)
5204 .Padding(PaddingMode::NONE)
5205 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5206
5207 string message = "12345678901234567890123456789012";
5208 auto begin_params = AuthorizationSetBuilder()
5209 .BlockMode(BlockMode::GCM)
5210 .Padding(PaddingMode::NONE)
5211 .Authorization(TAG_MAC_LENGTH, 128);
5212
Selene Huang31ab4042020-04-29 04:22:39 -07005213 // Encrypt
5214 AuthorizationSet begin_out_params;
5215 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005216 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005217 string ciphertext;
5218 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005219 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005220
5221 // Wrong nonce
5222 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5223
5224 // Decrypt.
5225 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005226 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005227 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005228 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005229
5230 // With wrong nonce, should have gotten garbage plaintext (or none).
5231 EXPECT_NE(message, plaintext);
5232}
5233
5234/*
5235 * EncryptionOperationsTest.AesGcmCorruptTag
5236 *
5237 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5238 */
5239TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5240 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5241 .Authorization(TAG_NO_AUTH_REQUIRED)
5242 .AesEncryptionKey(128)
5243 .BlockMode(BlockMode::GCM)
5244 .Padding(PaddingMode::NONE)
5245 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5246
5247 string aad = "1234567890123456";
5248 string message = "123456789012345678901234567890123456";
5249
5250 auto params = AuthorizationSetBuilder()
5251 .BlockMode(BlockMode::GCM)
5252 .Padding(PaddingMode::NONE)
5253 .Authorization(TAG_MAC_LENGTH, 128);
5254
Selene Huang31ab4042020-04-29 04:22:39 -07005255 // Encrypt
5256 AuthorizationSet begin_out_params;
5257 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005258 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005259 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005260 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005261
5262 // Corrupt tag
5263 ++(*ciphertext.rbegin());
5264
5265 // Grab nonce
5266 params.push_back(begin_out_params);
5267
5268 // Decrypt.
5269 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005270 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005271 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005272 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005273}
5274
5275/*
5276 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5277 *
5278 * Verifies that 3DES is basically functional.
5279 */
5280TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5281 auto auths = AuthorizationSetBuilder()
5282 .TripleDesEncryptionKey(168)
5283 .BlockMode(BlockMode::ECB)
5284 .Authorization(TAG_NO_AUTH_REQUIRED)
5285 .Padding(PaddingMode::NONE);
5286
5287 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5288 // Two-block message.
5289 string message = "1234567890123456";
5290 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5291 string ciphertext1 = EncryptMessage(message, inParams);
5292 EXPECT_EQ(message.size(), ciphertext1.size());
5293
5294 string ciphertext2 = EncryptMessage(string(message), inParams);
5295 EXPECT_EQ(message.size(), ciphertext2.size());
5296
5297 // ECB is deterministic.
5298 EXPECT_EQ(ciphertext1, ciphertext2);
5299
5300 string plaintext = DecryptMessage(ciphertext1, inParams);
5301 EXPECT_EQ(message, plaintext);
5302}
5303
5304/*
5305 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5306 *
5307 * Verifies that CBC keys reject ECB usage.
5308 */
5309TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5310 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5311 .TripleDesEncryptionKey(168)
5312 .BlockMode(BlockMode::CBC)
5313 .Authorization(TAG_NO_AUTH_REQUIRED)
5314 .Padding(PaddingMode::NONE)));
5315
5316 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5317 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5318}
5319
5320/*
5321 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5322 *
5323 * Tests ECB mode with PKCS#7 padding, various message sizes.
5324 */
5325TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5326 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5327 .TripleDesEncryptionKey(168)
5328 .BlockMode(BlockMode::ECB)
5329 .Authorization(TAG_NO_AUTH_REQUIRED)
5330 .Padding(PaddingMode::PKCS7)));
5331
5332 for (size_t i = 0; i < 32; ++i) {
5333 string message(i, 'a');
5334 auto inParams =
5335 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5336 string ciphertext = EncryptMessage(message, inParams);
5337 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5338 string plaintext = DecryptMessage(ciphertext, inParams);
5339 EXPECT_EQ(message, plaintext);
5340 }
5341}
5342
5343/*
5344 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5345 *
5346 * Verifies that keys configured for no padding reject PKCS7 padding
5347 */
5348TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5349 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5350 .TripleDesEncryptionKey(168)
5351 .BlockMode(BlockMode::ECB)
5352 .Authorization(TAG_NO_AUTH_REQUIRED)
5353 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005354 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5355 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005356}
5357
5358/*
5359 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5360 *
5361 * Verifies that corrupted padding is detected.
5362 */
5363TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5364 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5365 .TripleDesEncryptionKey(168)
5366 .BlockMode(BlockMode::ECB)
5367 .Authorization(TAG_NO_AUTH_REQUIRED)
5368 .Padding(PaddingMode::PKCS7)));
5369
5370 string message = "a";
5371 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5372 EXPECT_EQ(8U, ciphertext.size());
5373 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005374
5375 AuthorizationSetBuilder begin_params;
5376 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5377 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07005378
5379 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5380 ++ciphertext[ciphertext.size() / 2];
5381
5382 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5383 string plaintext;
5384 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5385 ErrorCode error = Finish(&plaintext);
5386 if (error == ErrorCode::INVALID_ARGUMENT) {
5387 // This is the expected error, we can exit the test now.
5388 return;
5389 } else {
5390 // Very small chance we got valid decryption, so try again.
5391 ASSERT_EQ(error, ErrorCode::OK);
5392 }
5393 }
5394 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005395}
5396
5397struct TripleDesTestVector {
5398 const char* name;
5399 const KeyPurpose purpose;
5400 const BlockMode block_mode;
5401 const PaddingMode padding_mode;
5402 const char* key;
5403 const char* iv;
5404 const char* input;
5405 const char* output;
5406};
5407
5408// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5409// of the NIST vectors are multiples of the block size.
5410static const TripleDesTestVector kTripleDesTestVectors[] = {
5411 {
5412 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5413 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5414 "", // IV
5415 "329d86bdf1bc5af4", // input
5416 "d946c2756d78633f", // output
5417 },
5418 {
5419 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5420 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5421 "", // IV
5422 "6b1540781b01ce1997adae102dbf3c5b", // input
5423 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5424 },
5425 {
5426 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5427 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5428 "", // IV
5429 "6daad94ce08acfe7", // input
5430 "660e7d32dcc90e79", // output
5431 },
5432 {
5433 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5434 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5435 "", // IV
5436 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5437 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5438 },
5439 {
5440 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5441 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5442 "43f791134c5647ba", // IV
5443 "dcc153cef81d6f24", // input
5444 "92538bd8af18d3ba", // output
5445 },
5446 {
5447 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5448 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5449 "c2e999cb6249023c", // IV
5450 "c689aee38a301bb316da75db36f110b5", // input
5451 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5452 },
5453 {
5454 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5455 PaddingMode::PKCS7,
5456 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5457 "c2e999cb6249023c", // IV
5458 "c689aee38a301bb316da75db36f110b500", // input
5459 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5460 },
5461 {
5462 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5463 PaddingMode::PKCS7,
5464 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5465 "c2e999cb6249023c", // IV
5466 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5467 "c689aee38a301bb316da75db36f110b500", // output
5468 },
5469 {
5470 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5471 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5472 "41746c7e442d3681", // IV
5473 "c53a7b0ec40600fe", // input
5474 "d4f00eb455de1034", // output
5475 },
5476 {
5477 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5478 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5479 "3982bc02c3727d45", // IV
5480 "6006f10adef52991fcc777a1238bbb65", // input
5481 "edae09288e9e3bc05746d872b48e3b29", // output
5482 },
5483};
5484
5485/*
5486 * EncryptionOperationsTest.TripleDesTestVector
5487 *
5488 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5489 */
5490TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5491 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5492 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5493 SCOPED_TRACE(test->name);
5494 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5495 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5496 hex2str(test->output));
5497 }
5498}
5499
5500/*
5501 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5502 *
5503 * Validates CBC mode functionality.
5504 */
5505TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5506 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5507 .TripleDesEncryptionKey(168)
5508 .BlockMode(BlockMode::CBC)
5509 .Authorization(TAG_NO_AUTH_REQUIRED)
5510 .Padding(PaddingMode::NONE)));
5511
5512 ASSERT_GT(key_blob_.size(), 0U);
5513
5514 // Two-block message.
5515 string message = "1234567890123456";
5516 vector<uint8_t> iv1;
5517 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5518 EXPECT_EQ(message.size(), ciphertext1.size());
5519
5520 vector<uint8_t> iv2;
5521 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5522 EXPECT_EQ(message.size(), ciphertext2.size());
5523
5524 // IVs should be random, so ciphertexts should differ.
5525 EXPECT_NE(iv1, iv2);
5526 EXPECT_NE(ciphertext1, ciphertext2);
5527
5528 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5529 EXPECT_EQ(message, plaintext);
5530}
5531
5532/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005533 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5534 *
5535 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5536 */
5537TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5538 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5539 .TripleDesEncryptionKey(168)
5540 .BlockMode(BlockMode::CBC)
5541 .Authorization(TAG_NO_AUTH_REQUIRED)
5542 .Authorization(TAG_CALLER_NONCE)
5543 .Padding(PaddingMode::NONE)));
5544 auto params = AuthorizationSetBuilder()
5545 .BlockMode(BlockMode::CBC)
5546 .Padding(PaddingMode::NONE)
5547 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5548 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5549}
5550
5551/*
Selene Huang31ab4042020-04-29 04:22:39 -07005552 * EncryptionOperationsTest.TripleDesCallerIv
5553 *
5554 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5555 */
5556TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5557 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5558 .TripleDesEncryptionKey(168)
5559 .BlockMode(BlockMode::CBC)
5560 .Authorization(TAG_NO_AUTH_REQUIRED)
5561 .Authorization(TAG_CALLER_NONCE)
5562 .Padding(PaddingMode::NONE)));
5563 string message = "1234567890123456";
5564 vector<uint8_t> iv;
5565 // Don't specify IV, should get a random one.
5566 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5567 EXPECT_EQ(message.size(), ciphertext1.size());
5568 EXPECT_EQ(8U, iv.size());
5569
5570 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5571 EXPECT_EQ(message, plaintext);
5572
5573 // Now specify an IV, should also work.
5574 iv = AidlBuf("abcdefgh");
5575 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5576
5577 // Decrypt with correct IV.
5578 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5579 EXPECT_EQ(message, plaintext);
5580
5581 // Now try with wrong IV.
5582 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5583 EXPECT_NE(message, plaintext);
5584}
5585
5586/*
5587 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5588 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005589 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005590 */
5591TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5592 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5593 .TripleDesEncryptionKey(168)
5594 .BlockMode(BlockMode::CBC)
5595 .Authorization(TAG_NO_AUTH_REQUIRED)
5596 .Padding(PaddingMode::NONE)));
5597
5598 string message = "12345678901234567890123456789012";
5599 vector<uint8_t> iv;
5600 // Don't specify nonce, should get a random one.
5601 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5602 EXPECT_EQ(message.size(), ciphertext1.size());
5603 EXPECT_EQ(8U, iv.size());
5604
5605 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5606 EXPECT_EQ(message, plaintext);
5607
5608 // Now specify a nonce, should fail.
5609 auto input_params = AuthorizationSetBuilder()
5610 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5611 .BlockMode(BlockMode::CBC)
5612 .Padding(PaddingMode::NONE);
5613 AuthorizationSet output_params;
5614 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5615 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5616}
5617
5618/*
5619 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5620 *
5621 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5622 */
5623TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5624 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5625 .TripleDesEncryptionKey(168)
5626 .BlockMode(BlockMode::ECB)
5627 .Authorization(TAG_NO_AUTH_REQUIRED)
5628 .Padding(PaddingMode::NONE)));
5629 // Two-block message.
5630 string message = "1234567890123456";
5631 auto begin_params =
5632 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5633 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5634}
5635
5636/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005637 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005638 *
5639 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5640 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005641TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5642 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5643 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5644 .TripleDesEncryptionKey(168)
5645 .BlockMode(blockMode)
5646 .Authorization(TAG_NO_AUTH_REQUIRED)
5647 .Padding(PaddingMode::NONE)));
5648 // Message is slightly shorter than two blocks.
5649 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005650
David Drysdaled2cc8c22021-04-15 13:29:45 +01005651 auto begin_params =
5652 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5653 AuthorizationSet output_params;
5654 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5655 string ciphertext;
5656 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5657
5658 CheckedDeleteKey();
5659 }
Selene Huang31ab4042020-04-29 04:22:39 -07005660}
5661
5662/*
5663 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5664 *
5665 * Verifies that PKCS7 padding works correctly in CBC mode.
5666 */
5667TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5668 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5669 .TripleDesEncryptionKey(168)
5670 .BlockMode(BlockMode::CBC)
5671 .Authorization(TAG_NO_AUTH_REQUIRED)
5672 .Padding(PaddingMode::PKCS7)));
5673
5674 // Try various message lengths; all should work.
5675 for (size_t i = 0; i < 32; ++i) {
5676 string message(i, 'a');
5677 vector<uint8_t> iv;
5678 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5679 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5680 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5681 EXPECT_EQ(message, plaintext);
5682 }
5683}
5684
5685/*
5686 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5687 *
5688 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5689 */
5690TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5691 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5692 .TripleDesEncryptionKey(168)
5693 .BlockMode(BlockMode::CBC)
5694 .Authorization(TAG_NO_AUTH_REQUIRED)
5695 .Padding(PaddingMode::NONE)));
5696
5697 // Try various message lengths; all should fail.
5698 for (size_t i = 0; i < 32; ++i) {
5699 auto begin_params =
5700 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5701 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5702 }
5703}
5704
5705/*
5706 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5707 *
5708 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5709 */
5710TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5711 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5712 .TripleDesEncryptionKey(168)
5713 .BlockMode(BlockMode::CBC)
5714 .Authorization(TAG_NO_AUTH_REQUIRED)
5715 .Padding(PaddingMode::PKCS7)));
5716
5717 string message = "a";
5718 vector<uint8_t> iv;
5719 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5720 EXPECT_EQ(8U, ciphertext.size());
5721 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005722
5723 auto begin_params = AuthorizationSetBuilder()
5724 .BlockMode(BlockMode::CBC)
5725 .Padding(PaddingMode::PKCS7)
5726 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07005727
5728 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5729 ++ciphertext[ciphertext.size() / 2];
5730 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5731 string plaintext;
5732 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5733 ErrorCode error = Finish(&plaintext);
5734 if (error == ErrorCode::INVALID_ARGUMENT) {
5735 // This is the expected error, we can exit the test now.
5736 return;
5737 } else {
5738 // Very small chance we got valid decryption, so try again.
5739 ASSERT_EQ(error, ErrorCode::OK);
5740 }
5741 }
5742 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005743}
5744
5745/*
5746 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5747 *
5748 * Verifies that 3DES CBC works with many different input sizes.
5749 */
5750TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5751 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5752 .TripleDesEncryptionKey(168)
5753 .BlockMode(BlockMode::CBC)
5754 .Authorization(TAG_NO_AUTH_REQUIRED)
5755 .Padding(PaddingMode::NONE)));
5756
5757 int increment = 7;
5758 string message(240, 'a');
5759 AuthorizationSet input_params =
5760 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5761 AuthorizationSet output_params;
5762 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5763
5764 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005765 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005766 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005767 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5768 EXPECT_EQ(message.size(), ciphertext.size());
5769
5770 // Move TAG_NONCE into input_params
5771 input_params = output_params;
5772 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5773 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5774 output_params.Clear();
5775
5776 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5777 string plaintext;
5778 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005779 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005780 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5781 EXPECT_EQ(ciphertext.size(), plaintext.size());
5782 EXPECT_EQ(message, plaintext);
5783}
5784
5785INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5786
5787typedef KeyMintAidlTestBase MaxOperationsTest;
5788
5789/*
5790 * MaxOperationsTest.TestLimitAes
5791 *
5792 * Verifies that the max uses per boot tag works correctly with AES keys.
5793 */
5794TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01005795 if (SecLevel() == SecurityLevel::STRONGBOX) {
5796 GTEST_SKIP() << "Test not applicable to StrongBox device";
5797 }
Selene Huang31ab4042020-04-29 04:22:39 -07005798
5799 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5800 .Authorization(TAG_NO_AUTH_REQUIRED)
5801 .AesEncryptionKey(128)
5802 .EcbMode()
5803 .Padding(PaddingMode::NONE)
5804 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5805
5806 string message = "1234567890123456";
5807
5808 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5809
5810 EncryptMessage(message, params);
5811 EncryptMessage(message, params);
5812 EncryptMessage(message, params);
5813
5814 // Fourth time should fail.
5815 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5816}
5817
5818/*
Qi Wud22ec842020-11-26 13:27:53 +08005819 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005820 *
5821 * Verifies that the max uses per boot tag works correctly with RSA keys.
5822 */
5823TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01005824 if (SecLevel() == SecurityLevel::STRONGBOX) {
5825 GTEST_SKIP() << "Test not applicable to StrongBox device";
5826 }
Selene Huang31ab4042020-04-29 04:22:39 -07005827
5828 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5829 .Authorization(TAG_NO_AUTH_REQUIRED)
5830 .RsaSigningKey(1024, 65537)
5831 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005832 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5833 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005834
5835 string message = "1234567890123456";
5836
5837 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5838
5839 SignMessage(message, params);
5840 SignMessage(message, params);
5841 SignMessage(message, params);
5842
5843 // Fourth time should fail.
5844 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5845}
5846
5847INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5848
Qi Wud22ec842020-11-26 13:27:53 +08005849typedef KeyMintAidlTestBase UsageCountLimitTest;
5850
5851/*
Qi Wubeefae42021-01-28 23:16:37 +08005852 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005853 *
Qi Wubeefae42021-01-28 23:16:37 +08005854 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005855 */
Qi Wubeefae42021-01-28 23:16:37 +08005856TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01005857 if (SecLevel() == SecurityLevel::STRONGBOX) {
5858 GTEST_SKIP() << "Test not applicable to StrongBox device";
5859 }
Qi Wud22ec842020-11-26 13:27:53 +08005860
5861 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5862 .Authorization(TAG_NO_AUTH_REQUIRED)
5863 .AesEncryptionKey(128)
5864 .EcbMode()
5865 .Padding(PaddingMode::NONE)
5866 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5867
5868 // Check the usage count limit tag appears in the authorizations.
5869 AuthorizationSet auths;
5870 for (auto& entry : key_characteristics_) {
5871 auths.push_back(AuthorizationSet(entry.authorizations));
5872 }
5873 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5874 << "key usage count limit " << 1U << " missing";
5875
5876 string message = "1234567890123456";
5877 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5878
Qi Wubeefae42021-01-28 23:16:37 +08005879 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5880 AuthorizationSet keystore_auths =
5881 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5882
Qi Wud22ec842020-11-26 13:27:53 +08005883 // First usage of AES key should work.
5884 EncryptMessage(message, params);
5885
Qi Wud22ec842020-11-26 13:27:53 +08005886 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5887 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5888 // must be invalidated from secure storage (such as RPMB partition).
5889 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5890 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005891 // Usage count limit tag is enforced by keystore, keymint does nothing.
5892 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005893 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5894 }
5895}
5896
5897/*
Qi Wubeefae42021-01-28 23:16:37 +08005898 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005899 *
Qi Wubeefae42021-01-28 23:16:37 +08005900 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005901 */
Qi Wubeefae42021-01-28 23:16:37 +08005902TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01005903 if (SecLevel() == SecurityLevel::STRONGBOX) {
5904 GTEST_SKIP() << "Test not applicable to StrongBox device";
5905 }
Qi Wubeefae42021-01-28 23:16:37 +08005906
5907 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5908 .Authorization(TAG_NO_AUTH_REQUIRED)
5909 .AesEncryptionKey(128)
5910 .EcbMode()
5911 .Padding(PaddingMode::NONE)
5912 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5913
5914 // Check the usage count limit tag appears in the authorizations.
5915 AuthorizationSet auths;
5916 for (auto& entry : key_characteristics_) {
5917 auths.push_back(AuthorizationSet(entry.authorizations));
5918 }
5919 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5920 << "key usage count limit " << 3U << " missing";
5921
5922 string message = "1234567890123456";
5923 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5924
5925 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5926 AuthorizationSet keystore_auths =
5927 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5928
5929 EncryptMessage(message, params);
5930 EncryptMessage(message, params);
5931 EncryptMessage(message, params);
5932
5933 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5934 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5935 // must be invalidated from secure storage (such as RPMB partition).
5936 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5937 } else {
5938 // Usage count limit tag is enforced by keystore, keymint does nothing.
5939 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5940 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5941 }
5942}
5943
5944/*
5945 * UsageCountLimitTest.TestSingleUseRsa
5946 *
5947 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5948 */
5949TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01005950 if (SecLevel() == SecurityLevel::STRONGBOX) {
5951 GTEST_SKIP() << "Test not applicable to StrongBox device";
5952 }
Qi Wud22ec842020-11-26 13:27:53 +08005953
5954 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5955 .Authorization(TAG_NO_AUTH_REQUIRED)
5956 .RsaSigningKey(1024, 65537)
5957 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005958 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5959 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005960
5961 // Check the usage count limit tag appears in the authorizations.
5962 AuthorizationSet auths;
5963 for (auto& entry : key_characteristics_) {
5964 auths.push_back(AuthorizationSet(entry.authorizations));
5965 }
5966 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5967 << "key usage count limit " << 1U << " missing";
5968
5969 string message = "1234567890123456";
5970 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5971
Qi Wubeefae42021-01-28 23:16:37 +08005972 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5973 AuthorizationSet keystore_auths =
5974 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5975
Qi Wud22ec842020-11-26 13:27:53 +08005976 // First usage of RSA key should work.
5977 SignMessage(message, params);
5978
Qi Wud22ec842020-11-26 13:27:53 +08005979 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5980 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5981 // must be invalidated from secure storage (such as RPMB partition).
5982 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5983 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005984 // Usage count limit tag is enforced by keystore, keymint does nothing.
5985 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5986 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5987 }
5988}
5989
5990/*
5991 * UsageCountLimitTest.TestLimitUseRsa
5992 *
5993 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5994 */
5995TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01005996 if (SecLevel() == SecurityLevel::STRONGBOX) {
5997 GTEST_SKIP() << "Test not applicable to StrongBox device";
5998 }
Qi Wubeefae42021-01-28 23:16:37 +08005999
6000 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6001 .Authorization(TAG_NO_AUTH_REQUIRED)
6002 .RsaSigningKey(1024, 65537)
6003 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006004 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6005 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006006
6007 // Check the usage count limit tag appears in the authorizations.
6008 AuthorizationSet auths;
6009 for (auto& entry : key_characteristics_) {
6010 auths.push_back(AuthorizationSet(entry.authorizations));
6011 }
6012 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6013 << "key usage count limit " << 3U << " missing";
6014
6015 string message = "1234567890123456";
6016 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6017
6018 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6019 AuthorizationSet keystore_auths =
6020 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6021
6022 SignMessage(message, params);
6023 SignMessage(message, params);
6024 SignMessage(message, params);
6025
6026 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6027 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6028 // must be invalidated from secure storage (such as RPMB partition).
6029 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6030 } else {
6031 // Usage count limit tag is enforced by keystore, keymint does nothing.
6032 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006033 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6034 }
6035}
6036
Qi Wu8e727f72021-02-11 02:49:33 +08006037/*
6038 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6039 *
6040 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6041 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6042 * in hardware.
6043 */
6044TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01006045 if (SecLevel() == SecurityLevel::STRONGBOX) {
6046 GTEST_SKIP() << "Test not applicable to StrongBox device";
6047 }
Qi Wu8e727f72021-02-11 02:49:33 +08006048
6049 auto error = GenerateKey(AuthorizationSetBuilder()
6050 .RsaSigningKey(2048, 65537)
6051 .Digest(Digest::NONE)
6052 .Padding(PaddingMode::NONE)
6053 .Authorization(TAG_NO_AUTH_REQUIRED)
6054 .Authorization(TAG_ROLLBACK_RESISTANCE)
6055 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006056 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6057 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08006058 }
David Drysdale513bf122021-10-06 11:53:13 +01006059
6060 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6061 ASSERT_EQ(ErrorCode::OK, error);
6062 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6063 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6064 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6065
6066 // The KeyMint should also enforce single use key in hardware when it supports rollback
6067 // resistance.
6068 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6069 .Authorization(TAG_NO_AUTH_REQUIRED)
6070 .RsaSigningKey(1024, 65537)
6071 .NoDigestOrPadding()
6072 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6073 .SetDefaultValidity()));
6074
6075 // Check the usage count limit tag appears in the hardware authorizations.
6076 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6077 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6078 << "key usage count limit " << 1U << " missing";
6079
6080 string message = "1234567890123456";
6081 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6082
6083 // First usage of RSA key should work.
6084 SignMessage(message, params);
6085
6086 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6087 // must be invalidated from secure storage (such as RPMB partition).
6088 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08006089}
6090
Qi Wud22ec842020-11-26 13:27:53 +08006091INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6092
David Drysdale7de9feb2021-03-05 14:56:19 +00006093typedef KeyMintAidlTestBase GetHardwareInfoTest;
6094
6095TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6096 // Retrieving hardware info should give the same result each time.
6097 KeyMintHardwareInfo info;
6098 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6099 KeyMintHardwareInfo info2;
6100 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6101 EXPECT_EQ(info, info2);
6102}
6103
6104INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6105
Selene Huang31ab4042020-04-29 04:22:39 -07006106typedef KeyMintAidlTestBase AddEntropyTest;
6107
6108/*
6109 * AddEntropyTest.AddEntropy
6110 *
6111 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6112 * is actually added.
6113 */
6114TEST_P(AddEntropyTest, AddEntropy) {
6115 string data = "foo";
6116 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6117}
6118
6119/*
6120 * AddEntropyTest.AddEmptyEntropy
6121 *
6122 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6123 */
6124TEST_P(AddEntropyTest, AddEmptyEntropy) {
6125 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6126}
6127
6128/*
6129 * AddEntropyTest.AddLargeEntropy
6130 *
6131 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6132 */
6133TEST_P(AddEntropyTest, AddLargeEntropy) {
6134 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6135}
6136
David Drysdalebb3d85e2021-04-13 11:15:51 +01006137/*
6138 * AddEntropyTest.AddTooLargeEntropy
6139 *
6140 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6141 */
6142TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6143 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6144 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6145}
6146
Selene Huang31ab4042020-04-29 04:22:39 -07006147INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6148
Selene Huang31ab4042020-04-29 04:22:39 -07006149typedef KeyMintAidlTestBase KeyDeletionTest;
6150
6151/**
6152 * KeyDeletionTest.DeleteKey
6153 *
6154 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6155 * valid key blob.
6156 */
6157TEST_P(KeyDeletionTest, DeleteKey) {
6158 auto error = GenerateKey(AuthorizationSetBuilder()
6159 .RsaSigningKey(2048, 65537)
6160 .Digest(Digest::NONE)
6161 .Padding(PaddingMode::NONE)
6162 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006163 .Authorization(TAG_ROLLBACK_RESISTANCE)
6164 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006165 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6166 GTEST_SKIP() << "Rollback resistance not supported";
6167 }
Selene Huang31ab4042020-04-29 04:22:39 -07006168
6169 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006170 ASSERT_EQ(ErrorCode::OK, error);
6171 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6172 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006173
David Drysdale513bf122021-10-06 11:53:13 +01006174 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07006175
David Drysdale513bf122021-10-06 11:53:13 +01006176 string message = "12345678901234567890123456789012";
6177 AuthorizationSet begin_out_params;
6178 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6179 Begin(KeyPurpose::SIGN, key_blob_,
6180 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6181 &begin_out_params));
6182 AbortIfNeeded();
6183 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006184}
6185
6186/**
6187 * KeyDeletionTest.DeleteInvalidKey
6188 *
6189 * This test checks that the HAL excepts invalid key blobs..
6190 */
6191TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6192 // Generate key just to check if rollback protection is implemented
6193 auto error = GenerateKey(AuthorizationSetBuilder()
6194 .RsaSigningKey(2048, 65537)
6195 .Digest(Digest::NONE)
6196 .Padding(PaddingMode::NONE)
6197 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006198 .Authorization(TAG_ROLLBACK_RESISTANCE)
6199 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006200 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6201 GTEST_SKIP() << "Rollback resistance not supported";
6202 }
Selene Huang31ab4042020-04-29 04:22:39 -07006203
6204 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006205 ASSERT_EQ(ErrorCode::OK, error);
6206 AuthorizationSet enforced(SecLevelAuthorizations());
6207 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006208
David Drysdale513bf122021-10-06 11:53:13 +01006209 // Delete the key we don't care about the result at this point.
6210 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07006211
David Drysdale513bf122021-10-06 11:53:13 +01006212 // Now create an invalid key blob and delete it.
6213 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07006214
David Drysdale513bf122021-10-06 11:53:13 +01006215 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07006216}
6217
6218/**
6219 * KeyDeletionTest.DeleteAllKeys
6220 *
6221 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6222 *
6223 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6224 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6225 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6226 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6227 * credentials stored in Keystore/Keymint.
6228 */
6229TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01006230 if (!arm_deleteAllKeys) {
6231 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
6232 return;
6233 }
Selene Huang31ab4042020-04-29 04:22:39 -07006234 auto error = GenerateKey(AuthorizationSetBuilder()
6235 .RsaSigningKey(2048, 65537)
6236 .Digest(Digest::NONE)
6237 .Padding(PaddingMode::NONE)
6238 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06006239 .Authorization(TAG_ROLLBACK_RESISTANCE)
6240 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006241 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6242 GTEST_SKIP() << "Rollback resistance not supported";
6243 }
Selene Huang31ab4042020-04-29 04:22:39 -07006244
6245 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006246 ASSERT_EQ(ErrorCode::OK, error);
6247 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6248 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006249
David Drysdale513bf122021-10-06 11:53:13 +01006250 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07006251
David Drysdale513bf122021-10-06 11:53:13 +01006252 string message = "12345678901234567890123456789012";
6253 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07006254
David Drysdale513bf122021-10-06 11:53:13 +01006255 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6256 Begin(KeyPurpose::SIGN, key_blob_,
6257 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6258 &begin_out_params));
6259 AbortIfNeeded();
6260 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006261}
6262
6263INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6264
David Drysdaled2cc8c22021-04-15 13:29:45 +01006265typedef KeyMintAidlTestBase KeyUpgradeTest;
6266
6267/**
6268 * KeyUpgradeTest.UpgradeInvalidKey
6269 *
6270 * This test checks that the HAL excepts invalid key blobs..
6271 */
6272TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6273 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6274
6275 std::vector<uint8_t> new_blob;
6276 Status result = keymint_->upgradeKey(key_blob,
6277 AuthorizationSetBuilder()
6278 .Authorization(TAG_APPLICATION_ID, "clientid")
6279 .Authorization(TAG_APPLICATION_DATA, "appdata")
6280 .vector_data(),
6281 &new_blob);
6282 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6283}
6284
6285INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6286
Selene Huang31ab4042020-04-29 04:22:39 -07006287using UpgradeKeyTest = KeyMintAidlTestBase;
6288
6289/*
6290 * UpgradeKeyTest.UpgradeKey
6291 *
6292 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6293 */
6294TEST_P(UpgradeKeyTest, UpgradeKey) {
6295 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6296 .AesEncryptionKey(128)
6297 .Padding(PaddingMode::NONE)
6298 .Authorization(TAG_NO_AUTH_REQUIRED)));
6299
6300 auto result = UpgradeKey(key_blob_);
6301
6302 // Key doesn't need upgrading. Should get okay, but no new key blob.
6303 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6304}
6305
6306INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6307
6308using ClearOperationsTest = KeyMintAidlTestBase;
6309
6310/*
6311 * ClearSlotsTest.TooManyOperations
6312 *
6313 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6314 * operations are started without being finished or aborted. Also verifies
6315 * that aborting the operations clears the operations.
6316 *
6317 */
6318TEST_P(ClearOperationsTest, TooManyOperations) {
6319 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6320 .Authorization(TAG_NO_AUTH_REQUIRED)
6321 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006322 .Padding(PaddingMode::NONE)
6323 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006324
6325 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6326 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006327 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006328 AuthorizationSet out_params;
6329 ErrorCode result;
6330 size_t i;
6331
6332 for (i = 0; i < max_operations; i++) {
6333 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6334 if (ErrorCode::OK != result) {
6335 break;
6336 }
6337 }
6338 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6339 // Try again just in case there's a weird overflow bug
6340 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6341 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6342 for (size_t j = 0; j < i; j++) {
6343 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6344 << "Aboort failed for i = " << j << std::endl;
6345 }
6346 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6347 AbortIfNeeded();
6348}
6349
6350INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6351
6352typedef KeyMintAidlTestBase TransportLimitTest;
6353
6354/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006355 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006356 *
6357 * Verifies that passing input data to finish succeeds as expected.
6358 */
6359TEST_P(TransportLimitTest, LargeFinishInput) {
6360 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6361 .Authorization(TAG_NO_AUTH_REQUIRED)
6362 .AesEncryptionKey(128)
6363 .BlockMode(BlockMode::ECB)
6364 .Padding(PaddingMode::NONE)));
6365
6366 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6367 auto cipher_params =
6368 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6369
6370 AuthorizationSet out_params;
6371 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6372
6373 string plain_message = std::string(1 << msg_size, 'x');
6374 string encrypted_message;
6375 auto rc = Finish(plain_message, &encrypted_message);
6376
6377 EXPECT_EQ(ErrorCode::OK, rc);
6378 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6379 << "Encrypt finish returned OK, but did not consume all of the given input";
6380 cipher_params.push_back(out_params);
6381
6382 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6383
6384 string decrypted_message;
6385 rc = Finish(encrypted_message, &decrypted_message);
6386 EXPECT_EQ(ErrorCode::OK, rc);
6387 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6388 << "Decrypt finish returned OK, did not consume all of the given input";
6389 }
6390}
6391
6392INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6393
David Zeuthene0c40892021-01-08 12:54:11 -05006394typedef KeyMintAidlTestBase KeyAgreementTest;
6395
6396int CurveToOpenSslCurveName(EcCurve curve) {
6397 switch (curve) {
6398 case EcCurve::P_224:
6399 return NID_secp224r1;
6400 case EcCurve::P_256:
6401 return NID_X9_62_prime256v1;
6402 case EcCurve::P_384:
6403 return NID_secp384r1;
6404 case EcCurve::P_521:
6405 return NID_secp521r1;
6406 }
6407}
6408
6409/*
6410 * KeyAgreementTest.Ecdh
6411 *
6412 * Verifies that ECDH works for all curves
6413 */
6414TEST_P(KeyAgreementTest, Ecdh) {
6415 // Because it's possible to use this API with keys on different curves, we
6416 // check all N^2 combinations where N is the number of supported
6417 // curves.
6418 //
6419 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6420 // lot more curves we can be smart about things and just pick |otherCurve| so
6421 // it's not |curve| and that way we end up with only 2*N runs
6422 //
6423 for (auto curve : ValidCurves()) {
6424 for (auto localCurve : ValidCurves()) {
6425 // Generate EC key locally (with access to private key material)
6426 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6427 int curveName = CurveToOpenSslCurveName(localCurve);
6428 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6429 ASSERT_NE(group, nullptr);
6430 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6431 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6432 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6433 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6434
6435 // Get encoded form of the public part of the locally generated key...
6436 unsigned char* p = nullptr;
6437 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6438 ASSERT_GT(encodedPublicKeySize, 0);
6439 vector<uint8_t> encodedPublicKey(
6440 reinterpret_cast<const uint8_t*>(p),
6441 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6442 OPENSSL_free(p);
6443
6444 // Generate EC key in KeyMint (only access to public key material)
6445 vector<uint8_t> challenge = {0x41, 0x42};
6446 EXPECT_EQ(
6447 ErrorCode::OK,
6448 GenerateKey(AuthorizationSetBuilder()
6449 .Authorization(TAG_NO_AUTH_REQUIRED)
6450 .Authorization(TAG_EC_CURVE, curve)
6451 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6452 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6453 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006454 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6455 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006456 << "Failed to generate key";
6457 ASSERT_GT(cert_chain_.size(), 0);
6458 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6459 ASSERT_NE(kmKeyCert, nullptr);
6460 // Check that keyAgreement (bit 4) is set in KeyUsage
6461 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6462 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6463 ASSERT_NE(kmPkey, nullptr);
6464 if (dump_Attestations) {
6465 for (size_t n = 0; n < cert_chain_.size(); n++) {
6466 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6467 }
6468 }
6469
6470 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6471 if (curve != localCurve) {
6472 // If the keys are using different curves KeyMint should fail with
6473 // ErrorCode:INVALID_ARGUMENT. Check that.
6474 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6475 string ZabFromKeyMintStr;
6476 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6477 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6478 &ZabFromKeyMintStr));
6479
6480 } else {
6481 // Otherwise if the keys are using the same curve, it should work.
6482 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6483 string ZabFromKeyMintStr;
6484 EXPECT_EQ(ErrorCode::OK,
6485 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6486 &ZabFromKeyMintStr));
6487 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6488
6489 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6490 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6491 ASSERT_NE(ctx, nullptr);
6492 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6493 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6494 size_t ZabFromTestLen = 0;
6495 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6496 vector<uint8_t> ZabFromTest;
6497 ZabFromTest.resize(ZabFromTestLen);
6498 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6499
6500 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6501 }
6502
6503 CheckedDeleteKey();
6504 }
6505 }
6506}
6507
6508INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6509
David Drysdaled2cc8c22021-04-15 13:29:45 +01006510using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6511
6512// This is a problematic test, as it can render the device under test permanently unusable.
6513// Re-enable and run at your own risk.
6514TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6515 auto result = DestroyAttestationIds();
6516 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6517}
6518
6519INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6520
Shawn Willdend659c7c2021-02-19 14:51:51 -07006521using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006522
David Drysdaledb0dcf52021-05-18 11:43:31 +01006523/*
6524 * EarlyBootKeyTest.CreateEarlyBootKeys
6525 *
6526 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6527 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006528TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01006529 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006530 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6531 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6532
David Drysdaleadfe6112021-05-27 12:00:53 +01006533 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6534 ASSERT_GT(keyData.blob.size(), 0U);
6535 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6536 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6537 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006538 CheckedDeleteKey(&aesKeyData.blob);
6539 CheckedDeleteKey(&hmacKeyData.blob);
6540 CheckedDeleteKey(&rsaKeyData.blob);
6541 CheckedDeleteKey(&ecdsaKeyData.blob);
6542}
6543
David Drysdaledb0dcf52021-05-18 11:43:31 +01006544/*
David Drysdaleadfe6112021-05-27 12:00:53 +01006545 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6546 *
6547 * Verifies that creating an early boot key with attestation succeeds.
6548 */
6549TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6550 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6551 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6552 builder->AttestationChallenge("challenge");
6553 builder->AttestationApplicationId("app_id");
6554 });
6555
6556 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6557 ASSERT_GT(keyData.blob.size(), 0U);
6558 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6559 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6560 }
6561 CheckedDeleteKey(&aesKeyData.blob);
6562 CheckedDeleteKey(&hmacKeyData.blob);
6563 CheckedDeleteKey(&rsaKeyData.blob);
6564 CheckedDeleteKey(&ecdsaKeyData.blob);
6565}
6566
6567/*
6568 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01006569 *
6570 * Verifies that using early boot keys at a later stage fails.
6571 */
6572TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6573 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6574 .Authorization(TAG_NO_AUTH_REQUIRED)
6575 .Authorization(TAG_EARLY_BOOT_ONLY)
6576 .HmacKey(128)
6577 .Digest(Digest::SHA_2_256)
6578 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6579 AuthorizationSet output_params;
6580 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6581 AuthorizationSetBuilder()
6582 .Digest(Digest::SHA_2_256)
6583 .Authorization(TAG_MAC_LENGTH, 256),
6584 &output_params));
6585}
6586
6587/*
6588 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6589 *
6590 * Verifies that importing early boot keys fails.
6591 */
6592TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6593 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6594 .Authorization(TAG_NO_AUTH_REQUIRED)
6595 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01006596 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01006597 .Digest(Digest::SHA_2_256)
6598 .SetDefaultValidity(),
6599 KeyFormat::PKCS8, ec_256_key));
6600}
6601
David Drysdaled2cc8c22021-04-15 13:29:45 +01006602// 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 +00006603// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6604// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6605// early boot, so you'll have to reboot between runs.
6606TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6607 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6608 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6609 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6610 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6611 EXPECT_TRUE(
6612 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6613 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6614 EXPECT_TRUE(
6615 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6616
6617 // Should be able to use keys, since early boot has not ended
6618 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6619 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6620 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6621 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6622
6623 // End early boot
6624 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6625 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6626
6627 // Should not be able to use already-created keys.
6628 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6629 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6630 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6631 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6632
6633 CheckedDeleteKey(&aesKeyData.blob);
6634 CheckedDeleteKey(&hmacKeyData.blob);
6635 CheckedDeleteKey(&rsaKeyData.blob);
6636 CheckedDeleteKey(&ecdsaKeyData.blob);
6637
6638 // Should not be able to create new keys
6639 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6640 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6641
6642 CheckedDeleteKey(&aesKeyData.blob);
6643 CheckedDeleteKey(&hmacKeyData.blob);
6644 CheckedDeleteKey(&rsaKeyData.blob);
6645 CheckedDeleteKey(&ecdsaKeyData.blob);
6646}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006647
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006648INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6649
Shawn Willdend659c7c2021-02-19 14:51:51 -07006650using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006651
6652// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6653// between runs... and on most test devices there are no enrolled credentials so it can't be
6654// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6655// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6656// a manual test process, which includes unlocking between runs, which is why it's included here.
6657// Well, that and the fact that it's the only test we can do without also making calls into the
6658// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6659// implications might be, so that may or may not be a solution.
6660TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6661 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6662 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6663
6664 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6665 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6666 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6667 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6668
6669 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006670 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006671 ASSERT_EQ(ErrorCode::OK, rc);
6672 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6673 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6674 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6675 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6676
6677 CheckedDeleteKey(&aesKeyData.blob);
6678 CheckedDeleteKey(&hmacKeyData.blob);
6679 CheckedDeleteKey(&rsaKeyData.blob);
6680 CheckedDeleteKey(&ecdsaKeyData.blob);
6681}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006682
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006683INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6684
Janis Danisevskis24c04702020-12-16 18:28:39 -08006685} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006686
6687int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006688 std::cout << "Testing ";
6689 auto halInstances =
6690 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6691 std::cout << "HAL instances:\n";
6692 for (auto& entry : halInstances) {
6693 std::cout << " " << entry << '\n';
6694 }
6695
Selene Huang31ab4042020-04-29 04:22:39 -07006696 ::testing::InitGoogleTest(&argc, argv);
6697 for (int i = 1; i < argc; ++i) {
6698 if (argv[i][0] == '-') {
6699 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006700 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6701 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006702 }
6703 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006704 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6705 dump_Attestations = true;
6706 } else {
6707 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006708 }
6709 }
6710 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006711 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006712}