1 /*
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
17 #define LOG_TAG "keymint_1_test"
18 #include <cutils/log.h>
19
20 #include <signal.h>
21
22 #include <algorithm>
23 #include <iostream>
24
25 #include <openssl/curve25519.h>
26 #include <openssl/ec.h>
27 #include <openssl/evp.h>
28 #include <openssl/mem.h>
29 #include <openssl/x509.h>
30 #include <openssl/x509v3.h>
31
32 #include <cutils/properties.h>
33
34 #include <android/binder_manager.h>
35
36 #include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
37 #include <aidl/android/hardware/security/keymint/KeyFormat.h>
38
39 #include <keymint_support/key_param_output.h>
40 #include <keymint_support/openssl_utils.h>
41
42 #include "KeyMintAidlTestBase.h"
43
44 using aidl::android::hardware::security::keymint::AuthorizationSet;
45 using aidl::android::hardware::security::keymint::KeyCharacteristics;
46 using aidl::android::hardware::security::keymint::KeyFormat;
47
48 namespace std {
49
50 using namespace aidl::android::hardware::security::keymint;
51
52 template <>
53 struct std::equal_to<KeyCharacteristics> {
operator ()std::std::equal_to54 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
55 if (a.securityLevel != b.securityLevel) return false;
56
57 // this isn't very efficient. Oh, well.
58 AuthorizationSet a_auths(a.authorizations);
59 AuthorizationSet b_auths(b.authorizations);
60
61 a_auths.Sort();
62 b_auths.Sort();
63
64 return a_auths == b_auths;
65 }
66 };
67
68 } // namespace std
69
70 namespace aidl::android::hardware::security::keymint::test {
71
72 namespace {
73
74 // Maximum supported Ed25519 message size.
75 const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
76
77 // Whether to check that BOOT_PATCHLEVEL is populated.
78 bool check_boot_pl = true;
79
80 // The maximum number of times we'll attempt to verify that corruption
81 // of an encrypted blob results in an error. Retries are necessary as there
82 // is a small (roughly 1/256) chance that corrupting ciphertext still results
83 // in valid PKCS7 padding.
84 constexpr size_t kMaxPaddingCorruptionRetries = 8;
85
86 template <TagType tag_type, Tag tag, typename ValueT>
contains(const vector<KeyParameter> & set,TypedTag<tag_type,tag> ttag,ValueT expected_value)87 bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
88 ValueT expected_value) {
89 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
90 if (auto p = authorizationValue(ttag, param)) {
91 return *p == expected_value;
92 }
93 return false;
94 });
95 return (it != set.end());
96 }
97
98 template <TagType tag_type, Tag tag>
contains(const vector<KeyParameter> & set,TypedTag<tag_type,tag>)99 bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
100 auto it = std::find_if(set.begin(), set.end(),
101 [&](const KeyParameter& param) { return param.tag == tag; });
102 return (it != set.end());
103 }
104
105 constexpr char hex_value[256] = {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, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
109 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
110 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
111 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
115 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
120 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
121
hex2str(string a)122 string hex2str(string a) {
123 string b;
124 size_t num = a.size() / 2;
125 b.resize(num);
126 for (size_t i = 0; i < num; i++) {
127 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
128 }
129 return b;
130 }
131
132 string rsa_key = hex2str(
133 // RFC 5208 s5
134 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
135 "020100" // INTEGER length 1 value 0x00 (version)
136 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
137 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
138 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
139 "0500" // NULL (parameters)
140 // } end SEQUENCE (AlgorithmIdentifier)
141 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
142 // RFC 8017 A.1.2
143 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
144 "020100" // INTEGER length 1 value 0x00 (version)
145 "028181" // INTEGER length 0x81 value (modulus) ...
146 "00c6095409047d8634812d5a218176e4"
147 "5c41d60a75b13901f234226cffe77652"
148 "1c5a77b9e389417b71c0b6a44d13afe4"
149 "e4a2805d46c9da2935adb1ff0c1f24ea"
150 "06e62b20d776430a4d435157233c6f91"
151 "6783c30e310fcbd89b85c2d567711697"
152 "85ac12bca244abda72bfb19fc44d27c8"
153 "1e1d92de284f4061edfd99280745ea6d"
154 "25"
155 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
156 "028180" // INTEGER length 0x80 (privateExponent) value...
157 "1be0f04d9cae3718691f035338308e91"
158 "564b55899ffb5084d2460e6630257e05"
159 "b3ceab02972dfabcd6ce5f6ee2589eb6"
160 "7911ed0fac16e43a444b8c861e544a05"
161 "93365772f8baf6b22fc9e3c5f1024b06"
162 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
163 "ace7240290bef16c0b3f7f3cdd64ce3a"
164 "b5912cf6e32f39ab188358afcccd8081"
165 "0241" // INTEGER length 0x41 (prime1)
166 "00e4b49ef50f765d3b24dde01aceaaf1"
167 "30f2c76670a91a61ae08af497b4a82be"
168 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
169 "8c92bfab137fba2285227b83c342ff7c"
170 "55"
171 "0241" // INTEGER length 0x41 (prime2)
172 "00ddabb5839c4c7f6bf3d4183231f005"
173 "b31aa58affdda5c79e4cce217f6bc930"
174 "dbe563d480706c24e9ebfcab28a6cdef"
175 "d324b77e1bf7251b709092c24ff501fd"
176 "91"
177 "0240" // INTEGER length 0x40 (exponent1)
178 "23d4340eda3445d8cd26c14411da6fdc"
179 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
180 "842c1d280405bc2f6c1bea214a1d742a"
181 "b996b35b63a82a5e470fa88dbf823cdd"
182 "0240" // INTEGER length 0x40 (exponent2)
183 "1b7b57449ad30d1518249a5f56bb9829"
184 "4d4b6ac12ffc86940497a5a5837a6cf9"
185 "46262b494526d328c11e1126380fde04"
186 "c24f916dec250892db09a6d77cdba351"
187 "0240" // INTEGER length 0x40 (coefficient)
188 "7762cd8f4d050da56bd591adb515d24d"
189 "7ccd32cca0d05f866d583514bd7324d5"
190 "f33645e8ed8b4a1cb3cc4a1d67987399"
191 "f2a09f5b3fb68c88d5e5d90ac33492d6"
192 // } end SEQUENCE (PrivateKey)
193 // } end SEQUENCE (PrivateKeyInfo)
194 );
195
196 /*
197 * DER-encoded PKCS#8 format RSA key. Generated using:
198 *
199 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
200 */
201 string rsa_2048_key = hex2str(
202 // RFC 5208 s5
203 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
204 "020100" // INTEGER length 1 value 0x00 (version)
205 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
206 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
207 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
208 "0500" // NULL (parameters)
209 // } end SEQUENCE (AlgorithmIdentifier)
210 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
211 // RFC 8017 A.1.2
212 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
213 "020100" // INTEGER length 1 value 0x00 (version)
214 "02820101" // INTEGER length 0x101 value (modulus) ...
215 "00BEBC342B56D443B1299F9A6A7056E8"
216 "0A897E318476A5A18029E63B2ED739A6"
217 "1791D339F58DC763D9D14911F2EDEC38"
218 "3DEE11F6319B44510E7A3ECD9B79B973"
219 "82E49500ACF8117DC89CAF0E621F7775"
220 "6554A2FD4664BFE7AB8B59AB48340DBF"
221 "A27B93B5A81F6ECDEB02D0759307128D"
222 "F3E3BAD4055C8B840216DFAA5700670E"
223 "6C5126F0962FCB70FF308F25049164CC"
224 "F76CC2DA66A7DD9A81A714C2809D6918"
225 "6133D29D84568E892B6FFBF3199BDB14"
226 "383EE224407F190358F111A949552ABA"
227 "6714227D1BD7F6B20DD0CB88F9467B71"
228 "9339F33BFF35B3870B3F62204E4286B0"
229 "948EA348B524544B5F9838F29EE643B0"
230 "79EEF8A713B220D7806924CDF7295070"
231 "C5"
232 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
233 "02820100" // INTEGER length 0x100 (privateExponent) value...
234 "69F377F35F2F584EF075353CCD1CA997"
235 "38DB3DBC7C7FF35F9366CE176DFD1B13"
236 "5AB10030344ABF5FBECF1D4659FDEF1C"
237 "0FC430834BE1BE3911951377BB3D563A"
238 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
239 "2686C7B4B3C09A7B8354133E6F93F790"
240 "D59EAEB92E84C9A4339302CCE28FDF04"
241 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
242 "6AB706645BF074A4E4090D06FB163124"
243 "365FD5EE7A20D350E9958CC30D91326E"
244 "1B292E9EF5DB408EC42DAF737D201497"
245 "04D0A678A0FB5B5446863B099228A352"
246 "D604BA8091A164D01D5AB05397C71EAD"
247 "20BE2A08FC528FE442817809C787FEE4"
248 "AB97F97B9130D022153EDC6EB6CBE7B0"
249 "F8E3473F2E901209B5DB10F93604DB01"
250 "028181" // INTEGER length 0x81 (prime1)
251 "00E83C0998214941EA4F9293F1B77E2E"
252 "99E6CF305FAF358238E126124FEAF2EB"
253 "9724B2EA7B78E6032343821A80E55D1D"
254 "88FB12D220C3F41A56142FEC85796D19"
255 "17F1E8C774F142B67D3D6E7B7E6B4383"
256 "E94DB5929089DBB346D5BDAB40CC2D96"
257 "EE0409475E175C63BF78CFD744136740"
258 "838127EA723FF3FE7FA368C1311B4A4E"
259 "05"
260 "028181" // INTEGER length 0x81 (prime2)
261 "00D240FCC0F5D7715CDE21CB2DC86EA1"
262 "46132EA3B06F61FF2AF54BF38473F59D"
263 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
264 "B1B58C39F95E4798CCBB43E83D0119AC"
265 "F532F359CA743C85199F0286610E2009"
266 "97D7312917179AC9B67558773212EC96"
267 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
268 "94D94E066A0900B7B70E82A44FB30053"
269 "C1"
270 "028181" // INTEGER length 0x81 (exponent1)
271 "00AD15DA1CBD6A492B66851BA8C316D3"
272 "8AB700E2CFDDD926A658003513C54BAA"
273 "152B30021D667D20078F500F8AD3E7F3"
274 "945D74A891ED1A28EAD0FEEAEC8C14A8"
275 "E834CF46A13D1378C99D18940823CFDD"
276 "27EC5810D59339E0C34198AC638E09C8"
277 "7CBB1B634A9864AE9F4D5EB2D53514F6"
278 "7B4CAEC048C8AB849A02E397618F3271"
279 "35"
280 "028180" // INTEGER length 0x80 (exponent2)
281 "1FA2C1A5331880A92D8F3E281C617108"
282 "BF38244F16E352E69ED417C7153F9EC3"
283 "18F211839C643DCF8B4DD67CE2AC312E"
284 "95178D5D952F06B1BF779F4916924B70"
285 "F582A23F11304E02A5E7565AE22A35E7"
286 "4FECC8B6FDC93F92A1A37703E4CF0E63"
287 "783BD02EB716A7ECBBFA606B10B74D01"
288 "579522E7EF84D91FC522292108D902C1"
289 "028180" // INTEGER length 0x80 (coefficient)
290 "796FE3825F9DCC85DF22D58690065D93"
291 "898ACD65C087BEA8DA3A63BF4549B795"
292 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
293 "0D74F40DED8E1102C52152A31B6165F8"
294 "3A6722AECFCC35A493D7634664B888A0"
295 "8D3EB034F12EA28BFEE346E205D33482"
296 "7F778B16ED40872BD29FCB36536B6E93"
297 "FFB06778696B4A9D81BB0A9423E63DE5"
298 // } end SEQUENCE (PrivateKey)
299 // } end SEQUENCE (PrivateKeyInfo)
300 );
301
302 string ec_256_key = hex2str(
303 // RFC 5208 s5
304 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
305 "020100" // INTEGER length 1 value 0 (version)
306 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
307 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
308 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
309 "0608" // OBJECT IDENTIFIER length 8 (param)
310 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
311 // } end SEQUENCE (AlgorithmIdentifier)
312 "046d" // OCTET STRING length 0x6d (privateKey) holding...
313 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
314 "020101" // INTEGER length 1 value 1 (version)
315 "0420" // OCTET STRING length 0x20 (privateKey)
316 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
317 "941eed09366bc03299986481f3a4d859"
318 "a144" // TAG [1] len 0x44 (publicKey) {
319 "03420004bf85d7720d07c25461683bc6"
320 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
321 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
322 "bcc41c6eb00083cf3376d11fd44949e0"
323 "b2183bfe"
324 // } end SEQUENCE (ECPrivateKey)
325 // } end SEQUENCE (PrivateKeyInfo)
326 );
327
328 string ec_521_key = hex2str(
329 // RFC 5208 s5
330 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
331 "020100" // INTEGER length 1 value 0 (version)
332 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
333 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
334 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
335 "0605" // OBJECT IDENTIFIER length 5 (param)
336 "2B81040023" // 1.3.132.0.35 (secp521r1)
337 // } end SEQUENCE (AlgorithmIdentifier)
338 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
339 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
340 "020101" // INTEGER length 1 value 1 (version)
341 "0442" // OCTET STRING length 0x42 (privateKey)
342 "0011458C586DB5DAA92AFAB03F4FE46A"
343 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
344 "9D18D7D08B5BCFA0E53C75B064AD51C4"
345 "49BAE0258D54B94B1E885DED08ED4FB2"
346 "5CE9"
347 "A18189" // TAG [1] len 0x89 (publicKey) {
348 "03818600040149EC11C6DF0FA122C6A9"
349 "AFD9754A4FA9513A627CA329E349535A"
350 "5629875A8ADFBE27DCB932C051986377"
351 "108D054C28C6F39B6F2C9AF81802F9F3"
352 "26B842FF2E5F3C00AB7635CFB36157FC"
353 "0882D574A10D839C1A0C049DC5E0D775"
354 "E2EE50671A208431BB45E78E70BEFE93"
355 "0DB34818EE4D5C26259F5C6B8E28A652"
356 "950F9F88D7B4B2C9D9"
357 // } end SEQUENCE (ECPrivateKey)
358 // } end SEQUENCE (PrivateKeyInfo)
359 );
360
361 string ec_256_key_rfc5915 = hex2str(
362 // RFC 5208 s5
363 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
364 "020100" // INTEGER length 1 value 0 (version)
365 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
366 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
367 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
368 "0608" // OBJECT IDENTIFIER length 8 (param)
369 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
370 // } end SEQUENCE (AlgorithmIdentifier)
371 "0479" // OCTET STRING length 0x79 (privateKey) holding...
372 // RFC 5915 s3
373 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
374 "020101" // INTEGER length 1 value 1 (version)
375 "0420" // OCTET STRING length 0x42 (privateKey)
376 "782370a8c8ce5537baadd04dcff079c8"
377 "158cfa9c67b818b38e8d21c9fa750c1d"
378 "a00a" // TAG [0] length 0xa (parameters)
379 "0608" // OBJECT IDENTIFIER length 8
380 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
381 // } end TAG [0]
382 "a144" // TAG [1] length 0x44 (publicKey) {
383 "0342" // BIT STRING length 0x42
384 "00" // no pad bits
385 "04e2cc561ee701da0ad0ef0d176bb0c9"
386 "19d42e79c393fdc1bd6c4010d85cf2cf"
387 "8e68c905464666f98dad4f01573ba810"
388 "78b3428570a439ba3229fbc026c55068"
389 "2f"
390 // } end SEQUENCE (ECPrivateKey)
391 // } end SEQUENCE (PrivateKeyInfo)
392 );
393
394 string ec_256_key_sec1 = hex2str(
395 // RFC 5208 s5
396 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
397 "020100" // INTEGER length 1 value 0 (version)
398 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
399 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
400 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
401 "0608" // OBJECT IDENTIFIER length 8 (param)
402 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
403 // } end SEQUENCE (AlgorithmIdentifier)
404 "046d" // OCTET STRING length 0x6d (privateKey) holding...
405 // SEC1-v2 C.4
406 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
407 "020101" // INTEGER length 1 value 0x01 (version)
408 "0420" // OCTET STRING length 0x20 (privateKey)
409 "782370a8c8ce5537baadd04dcff079c8"
410 "158cfa9c67b818b38e8d21c9fa750c1d"
411 "a144" // TAG [1] length 0x44 (publicKey) {
412 "0342" // BIT STRING length 0x42
413 "00" // no pad bits
414 "04e2cc561ee701da0ad0ef0d176bb0c9"
415 "19d42e79c393fdc1bd6c4010d85cf2cf"
416 "8e68c905464666f98dad4f01573ba810"
417 "78b3428570a439ba3229fbc026c55068"
418 "2f"
419 // } end TAG [1] (publicKey)
420 // } end SEQUENCE (PrivateKeyInfo)
421 );
422
423 /**
424 * Ed25519 key pair generated as follows:
425 * ```
426 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
427 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
428 * Generating a ED25519 private key writing new private key to
429 * 'ed25519_priv.key'
430 * -----
431 * % cat ed25519_priv.key
432 * -----BEGIN PRIVATE KEY-----
433 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
434 * -----END PRIVATE KEY-----
435 * % der2ascii -pem -i ed25519_priv.key
436 * SEQUENCE {
437 * INTEGER { 0 }
438 * SEQUENCE {
439 * # ed25519
440 * OBJECT_IDENTIFIER { 1.3.101.112 }
441 * }
442 * OCTET_STRING {
443 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
444 * }
445 * }
446 * % cat ed25519.pem
447 * -----BEGIN CERTIFICATE-----
448 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
449 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
450 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
451 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
452 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
453 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
454 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
455 * -----END CERTIFICATE-----
456 * % openssl x509 -in ed25519.pem -text -noout
457 * Certificate:
458 * Data:
459 * Version: 3 (0x2)
460 * Serial Number:
461 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
462 * Signature Algorithm: ED25519
463 * Issuer: CN = fake.ed25519.com
464 * Validity
465 * Not Before: Oct 20 08:27:42 2021 GMT
466 * Not After : Sep 20 08:27:42 2023 GMT
467 * Subject: CN = fake.ed25519.com
468 * Subject Public Key Info:
469 * Public Key Algorithm: ED25519
470 * ED25519 Public-Key:
471 * pub:
472 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
473 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
474 * 56:91
475 * X509v3 extensions:
476 * X509v3 Subject Key Identifier:
477 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
478 * X509v3 Authority Key Identifier:
479 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
480 *
481 * X509v3 Basic Constraints: critical
482 * CA:TRUE
483 * Signature Algorithm: ED25519
484 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
485 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
486 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
487 * e7:07:32:60:32:8d:bb:eb:f6:0f
488 * ```
489 */
490 string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
491 string ed25519_pkcs8_key = hex2str(
492 // RFC 5208 s5
493 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
494 "0201" // INTEGER length 1 (Version)
495 "00" // version 0
496 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
497 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
498 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
499 // } end SEQUENCE (AlgorithmIdentifier)
500 "0422" // OCTET STRING length 0x22 (PrivateKey)
501 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
502 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
503 // } end SEQUENCE (PrivateKeyInfo)
504 );
505 string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
506
507 /**
508 * X25519 key pair generated as follows:
509 * ```
510 * % openssl genpkey -algorithm X25519 > x25519_priv.key
511 * % cat x25519_priv.key
512 * -----BEGIN PRIVATE KEY-----
513 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
514 * -----END PRIVATE KEY-----
515 * % der2ascii -pem -i x25519_priv.key
516 * SEQUENCE {
517 * INTEGER { 0 }
518 * SEQUENCE {
519 * # x25519
520 * OBJECT_IDENTIFIER { 1.3.101.110 }
521 * }
522 * OCTET_STRING {
523 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
524 * }
525 * }
526 * ```
527 */
528
529 string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
530 string x25519_pkcs8_key = hex2str(
531 // RFC 5208 s5
532 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
533 "0201" // INTEGER length 1 (Version)
534 "00" // version 0
535 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
536 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
537 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
538 "0422" // OCTET STRING length 0x22 (PrivateKey)
539 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
540 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
541 string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
542
543 struct RSA_Delete {
operator ()aidl::android::hardware::security::keymint::test::__anon4332ae940111::RSA_Delete544 void operator()(RSA* p) { RSA_free(p); }
545 };
546
make_string(const uint8_t * data,size_t length)547 std::string make_string(const uint8_t* data, size_t length) {
548 return std::string(reinterpret_cast<const char*>(data), length);
549 }
550
551 template <size_t N>
make_string(const uint8_t (& a)[N])552 std::string make_string(const uint8_t (&a)[N]) {
553 return make_string(a, N);
554 }
555
556 class AidlBuf : public vector<uint8_t> {
557 typedef vector<uint8_t> super;
558
559 public:
AidlBuf()560 AidlBuf() {}
AidlBuf(const super & other)561 AidlBuf(const super& other) : super(other) {}
AidlBuf(super && other)562 AidlBuf(super&& other) : super(std::move(other)) {}
AidlBuf(const std::string & other)563 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
564
operator =(const super & other)565 AidlBuf& operator=(const super& other) {
566 super::operator=(other);
567 return *this;
568 }
569
operator =(super && other)570 AidlBuf& operator=(super&& other) {
571 super::operator=(std::move(other));
572 return *this;
573 }
574
operator =(const string & other)575 AidlBuf& operator=(const string& other) {
576 resize(other.size());
577 for (size_t i = 0; i < other.size(); ++i) {
578 (*this)[i] = static_cast<uint8_t>(other[i]);
579 }
580 return *this;
581 }
582
to_string() const583 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
584 };
585
device_suffix(const string & name)586 string device_suffix(const string& name) {
587 size_t pos = name.find('/');
588 if (pos == string::npos) {
589 return name;
590 }
591 return name.substr(pos + 1);
592 }
593
matching_rp_instance(const std::string & km_name)594 std::shared_ptr<IRemotelyProvisionedComponent> matching_rp_instance(const std::string& km_name) {
595 string km_suffix = device_suffix(km_name);
596
597 vector<string> rp_names =
598 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
599 for (const string& rp_name : rp_names) {
600 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
601 // KeyMint instance, assume they match.
602 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
603 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
604 return IRemotelyProvisionedComponent::fromBinder(binder);
605 }
606 }
607 return nullptr;
608 }
609
610 } // namespace
611
612 class NewKeyGenerationTest : public KeyMintAidlTestBase {
613 protected:
CheckBaseParams(const vector<KeyCharacteristics> & keyCharacteristics)614 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
615 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
616 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
617
618 // Check that some unexpected tags/values are NOT present.
619 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
620 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
621 }
622
CheckSymmetricParams(const vector<KeyCharacteristics> & keyCharacteristics)623 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
624 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
625 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
626 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
627
628 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
629 }
630
CheckCommonParams(const vector<KeyCharacteristics> & keyCharacteristics,const KeyOrigin expectedKeyOrigin)631 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics,
632 const KeyOrigin expectedKeyOrigin) {
633 // TODO(swillden): Distinguish which params should be in which auth list.
634 AuthorizationSet auths;
635 for (auto& entry : keyCharacteristics) {
636 auths.push_back(AuthorizationSet(entry.authorizations));
637 }
638 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, expectedKeyOrigin));
639
640 // Verify that App data, ROT and auth timeout are NOT included.
641 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
642 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
643 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
644
645 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
646 // never adds it.
647 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
648
649 // Check OS details match the original hardware info.
650 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
651 EXPECT_TRUE(os_ver);
652 EXPECT_EQ(*os_ver, os_version());
653 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
654 EXPECT_TRUE(os_pl);
655 EXPECT_EQ(*os_pl, os_patch_level());
656
657 // Should include vendor patchlevel.
658 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
659 EXPECT_TRUE(vendor_pl);
660 EXPECT_EQ(*vendor_pl, vendor_patch_level());
661
662 // Should include boot patchlevel (but there are some test scenarios where this is not
663 // possible).
664 if (check_boot_pl) {
665 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
666 EXPECT_TRUE(boot_pl);
667 }
668
669 return auths;
670 }
671 };
672
673 /*
674 * NewKeyGenerationTest.Aes
675 *
676 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
677 * have correct characteristics.
678 */
TEST_P(NewKeyGenerationTest,Aes)679 TEST_P(NewKeyGenerationTest, Aes) {
680 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
681 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
682 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
683 SCOPED_TRACE(testing::Message()
684 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
685 vector<uint8_t> key_blob;
686 vector<KeyCharacteristics> key_characteristics;
687 auto builder = AuthorizationSetBuilder()
688 .AesEncryptionKey(key_size)
689 .BlockMode(block_mode)
690 .Padding(padding_mode)
691 .SetDefaultValidity();
692 if (block_mode == BlockMode::GCM) {
693 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
694 }
695 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
696
697 EXPECT_GT(key_blob.size(), 0U);
698 CheckSymmetricParams(key_characteristics);
699 CheckCharacteristics(key_blob, key_characteristics);
700
701 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
702
703 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
704 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
705 << "Key size " << key_size << "missing";
706
707 CheckedDeleteKey(&key_blob);
708 }
709 }
710 }
711 }
712
713 /*
714 * NewKeyGenerationTest.AesInvalidSize
715 *
716 * Verifies that specifying an invalid key size for AES key generation returns
717 * UNSUPPORTED_KEY_SIZE.
718 */
TEST_P(NewKeyGenerationTest,AesInvalidSize)719 TEST_P(NewKeyGenerationTest, AesInvalidSize) {
720 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
721 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
722 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
723 SCOPED_TRACE(testing::Message()
724 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
725 vector<uint8_t> key_blob;
726 vector<KeyCharacteristics> key_characteristics;
727 auto builder = AuthorizationSetBuilder()
728 .AesEncryptionKey(key_size)
729 .BlockMode(block_mode)
730 .Padding(padding_mode)
731 .SetDefaultValidity();
732 if (block_mode == BlockMode::GCM) {
733 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
734 }
735 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
736 GenerateKey(builder, &key_blob, &key_characteristics));
737 }
738 }
739 }
740
741 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
742 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
743 SCOPED_TRACE(testing::Message() << "AES-unknown-" << block_mode << "-" << padding_mode);
744 vector<uint8_t> key_blob;
745 vector<KeyCharacteristics> key_characteristics;
746 // No key size specified
747 auto builder = AuthorizationSetBuilder()
748 .Authorization(TAG_ALGORITHM, Algorithm::AES)
749 .BlockMode(block_mode)
750 .Padding(padding_mode)
751 .SetDefaultValidity();
752 if (block_mode == BlockMode::GCM) {
753 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
754 }
755 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
756 GenerateKey(builder, &key_blob, &key_characteristics));
757 }
758 }
759 }
760
761 /*
762 * NewKeyGenerationTest.AesInvalidPadding
763 *
764 * Verifies that specifying an invalid padding on AES keys gives a failure
765 * somewhere along the way.
766 */
TEST_P(NewKeyGenerationTest,AesInvalidPadding)767 TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
768 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
769 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
770 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
771 SCOPED_TRACE(testing::Message()
772 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
773 auto builder = AuthorizationSetBuilder()
774 .Authorization(TAG_NO_AUTH_REQUIRED)
775 .AesEncryptionKey(key_size)
776 .BlockMode(block_mode)
777 .Padding(padding_mode)
778 .SetDefaultValidity();
779 if (block_mode == BlockMode::GCM) {
780 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
781 }
782
783 auto result = GenerateKey(builder);
784 if (result == ErrorCode::OK) {
785 // Key creation was OK but has generated a key that cannot be used.
786 auto params =
787 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
788 if (block_mode == BlockMode::GCM) {
789 params.Authorization(TAG_MAC_LENGTH, 128);
790 }
791 auto result = Begin(KeyPurpose::ENCRYPT, params);
792 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
793 result == ErrorCode::INVALID_KEY_BLOB)
794 << "unexpected result: " << result;
795 } else {
796 // The KeyMint implementation detected that the generated key
797 // is unusable.
798 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
799 }
800 }
801 }
802 }
803 }
804
805 /*
806 * NewKeyGenerationTest.AesGcmMissingMinMac
807 *
808 * Verifies that specifying an invalid key size for AES key generation returns
809 * UNSUPPORTED_KEY_SIZE.
810 */
TEST_P(NewKeyGenerationTest,AesGcmMissingMinMac)811 TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
812 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
813 BlockMode block_mode = BlockMode::GCM;
814 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
815 SCOPED_TRACE(testing::Message()
816 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
817 vector<uint8_t> key_blob;
818 vector<KeyCharacteristics> key_characteristics;
819 // No MIN_MAC_LENGTH provided.
820 auto builder = AuthorizationSetBuilder()
821 .AesEncryptionKey(key_size)
822 .BlockMode(block_mode)
823 .Padding(padding_mode)
824 .SetDefaultValidity();
825 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
826 GenerateKey(builder, &key_blob, &key_characteristics));
827 }
828 }
829 }
830
831 /*
832 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
833 *
834 * Verifies that specifying an invalid min MAC size for AES key generation returns
835 * UNSUPPORTED_MIN_MAC_LENGTH.
836 */
TEST_P(NewKeyGenerationTest,AesGcmMinMacOutOfRange)837 TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
838 for (size_t min_mac_len : {88, 136}) {
839 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
840 BlockMode block_mode = BlockMode::GCM;
841 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
842 SCOPED_TRACE(testing::Message()
843 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
844 vector<uint8_t> key_blob;
845 vector<KeyCharacteristics> key_characteristics;
846 auto builder = AuthorizationSetBuilder()
847 .AesEncryptionKey(key_size)
848 .BlockMode(block_mode)
849 .Padding(padding_mode)
850 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
851 .SetDefaultValidity();
852 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
853 GenerateKey(builder, &key_blob, &key_characteristics));
854 }
855 }
856 }
857 }
858
859 /*
860 * NewKeyGenerationTest.TripleDes
861 *
862 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
863 * have correct characteristics.
864 */
TEST_P(NewKeyGenerationTest,TripleDes)865 TEST_P(NewKeyGenerationTest, TripleDes) {
866 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
867 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
868 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
869 SCOPED_TRACE(testing::Message()
870 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
871 vector<uint8_t> key_blob;
872 vector<KeyCharacteristics> key_characteristics;
873 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
874 .TripleDesEncryptionKey(key_size)
875 .BlockMode(block_mode)
876 .Padding(padding_mode)
877 .Authorization(TAG_NO_AUTH_REQUIRED)
878 .SetDefaultValidity(),
879 &key_blob, &key_characteristics));
880
881 EXPECT_GT(key_blob.size(), 0U);
882 CheckSymmetricParams(key_characteristics);
883 CheckCharacteristics(key_blob, key_characteristics);
884
885 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
886
887 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
888 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
889 << "Key size " << key_size << "missing";
890
891 CheckedDeleteKey(&key_blob);
892 }
893 }
894 }
895 }
896
897 /*
898 * NewKeyGenerationTest.TripleDesWithAttestation
899 *
900 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
901 * have correct characteristics.
902 *
903 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
904 * put in a certificate) but which isn't an error.
905 */
TEST_P(NewKeyGenerationTest,TripleDesWithAttestation)906 TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
907 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
908 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
909 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
910 SCOPED_TRACE(testing::Message()
911 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
912
913 auto challenge = "hello";
914 auto app_id = "foo";
915
916 vector<uint8_t> key_blob;
917 vector<KeyCharacteristics> key_characteristics;
918 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
919 .TripleDesEncryptionKey(key_size)
920 .BlockMode(block_mode)
921 .Padding(padding_mode)
922 .Authorization(TAG_NO_AUTH_REQUIRED)
923 .AttestationChallenge(challenge)
924 .AttestationApplicationId(app_id)
925 .SetDefaultValidity(),
926 &key_blob, &key_characteristics));
927
928 EXPECT_GT(key_blob.size(), 0U);
929 CheckSymmetricParams(key_characteristics);
930 CheckCharacteristics(key_blob, key_characteristics);
931
932 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
933
934 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
935 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
936 << "Key size " << key_size << "missing";
937
938 CheckedDeleteKey(&key_blob);
939 }
940 }
941 }
942 }
943
944 /*
945 * NewKeyGenerationTest.TripleDesInvalidSize
946 *
947 * Verifies that specifying an invalid key size for 3-DES key generation returns
948 * UNSUPPORTED_KEY_SIZE.
949 */
TEST_P(NewKeyGenerationTest,TripleDesInvalidSize)950 TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
951 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
952 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
953 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
954 SCOPED_TRACE(testing::Message()
955 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
956 vector<uint8_t> key_blob;
957 vector<KeyCharacteristics> key_characteristics;
958 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
959 GenerateKey(AuthorizationSetBuilder()
960 .TripleDesEncryptionKey(key_size)
961 .BlockMode(block_mode)
962 .Padding(padding_mode)
963 .Authorization(TAG_NO_AUTH_REQUIRED)
964 .SetDefaultValidity(),
965 &key_blob, &key_characteristics));
966 }
967 }
968 }
969
970 // Omitting the key size fails.
971 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
972 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
973 SCOPED_TRACE(testing::Message()
974 << "3DES-default-" << block_mode << "-" << padding_mode);
975 vector<uint8_t> key_blob;
976 vector<KeyCharacteristics> key_characteristics;
977 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
978 GenerateKey(AuthorizationSetBuilder()
979 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
980 .BlockMode(block_mode)
981 .Padding(padding_mode)
982 .Authorization(TAG_NO_AUTH_REQUIRED)
983 .SetDefaultValidity(),
984 &key_blob, &key_characteristics));
985 }
986 }
987 }
988
989 /*
990 * NewKeyGenerationTest.Rsa
991 *
992 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
993 * have correct characteristics.
994 */
TEST_P(NewKeyGenerationTest,Rsa)995 TEST_P(NewKeyGenerationTest, Rsa) {
996 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
997 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
998 vector<uint8_t> key_blob;
999 vector<KeyCharacteristics> key_characteristics;
1000 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1001 .RsaSigningKey(key_size, 65537)
1002 .Digest(Digest::NONE)
1003 .Padding(PaddingMode::NONE)
1004 .SetDefaultValidity(),
1005 &key_blob, &key_characteristics));
1006
1007 ASSERT_GT(key_blob.size(), 0U);
1008 CheckBaseParams(key_characteristics);
1009 CheckCharacteristics(key_blob, key_characteristics);
1010
1011 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1012
1013 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1014 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1015 << "Key size " << key_size << "missing";
1016 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1017
1018 CheckedDeleteKey(&key_blob);
1019 }
1020 }
1021
1022 /*
1023 * NewKeyGenerationTest.RsaWithMissingValidity
1024 *
1025 * Verifies that keymint returns an error while generating asymmetric key
1026 * without providing NOT_BEFORE and NOT_AFTER parameters.
1027 */
TEST_P(NewKeyGenerationTest,RsaWithMissingValidity)1028 TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
1029 if (AidlVersion() < 3) {
1030 /*
1031 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1032 * specified for asymmetric key generation. However, this was not
1033 * checked at the time so we can only be strict about checking this for
1034 * implementations of KeyMint version 2 and above.
1035 */
1036 GTEST_SKIP() << "Validity strict since KeyMint v2";
1037 }
1038 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1039 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1040 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1041
1042 vector<uint8_t> key_blob;
1043 vector<KeyCharacteristics> key_characteristics;
1044 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1045 GenerateKey(AuthorizationSetBuilder()
1046 .RsaSigningKey(2048, 65537)
1047 .Digest(Digest::NONE)
1048 .Padding(PaddingMode::NONE)
1049 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1050 kUndefinedExpirationDateTime),
1051 &key_blob, &key_characteristics));
1052
1053 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1054 GenerateKey(AuthorizationSetBuilder()
1055 .RsaSigningKey(2048, 65537)
1056 .Digest(Digest::NONE)
1057 .Padding(PaddingMode::NONE)
1058 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1059 &key_blob, &key_characteristics));
1060 }
1061
1062 /*
1063 * NewKeyGenerationTest.RsaWithSpecifiedValidity
1064 *
1065 * Verifies that KeyMint respects specified NOT_BEFORE and NOT_AFTER certificate dates.
1066 */
TEST_P(NewKeyGenerationTest,RsaWithSpecifiedValidity)1067 TEST_P(NewKeyGenerationTest, RsaWithSpecifiedValidity) {
1068 vector<uint8_t> key_blob;
1069 vector<KeyCharacteristics> key_characteristics;
1070 ASSERT_EQ(ErrorCode::OK,
1071 GenerateKey(AuthorizationSetBuilder()
1072 .RsaSigningKey(2048, 65537)
1073 .Digest(Digest::NONE)
1074 .Padding(PaddingMode::NONE)
1075 .Authorization(TAG_CERTIFICATE_NOT_BEFORE,
1076 1183806000000 /* 2007-07-07T11:00:00Z */)
1077 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1078 1916049600000 /* 2030-09-19T12:00:00Z */),
1079 &key_blob, &key_characteristics));
1080 ASSERT_GT(cert_chain_.size(), 0);
1081
1082 X509_Ptr cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1083 ASSERT_TRUE(!!cert.get());
1084
1085 const ASN1_TIME* not_before = X509_get0_notBefore(cert.get());
1086 ASSERT_NE(not_before, nullptr);
1087 time_t not_before_time;
1088 ASSERT_EQ(ASN1_TIME_to_time_t(not_before, ¬_before_time), 1);
1089 EXPECT_EQ(not_before_time, 1183806000);
1090
1091 const ASN1_TIME* not_after = X509_get0_notAfter(cert.get());
1092 ASSERT_NE(not_after, nullptr);
1093 time_t not_after_time;
1094 ASSERT_EQ(ASN1_TIME_to_time_t(not_after, ¬_after_time), 1);
1095 EXPECT_EQ(not_after_time, 1916049600);
1096 }
1097
1098 /*
1099 * NewKeyGenerationTest.RsaWithAttestation
1100 *
1101 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1102 * resulting keys have correct characteristics.
1103 */
TEST_P(NewKeyGenerationTest,RsaWithAttestation)1104 TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
1105 auto challenge = "hello";
1106 auto app_id = "foo";
1107
1108 auto subject = "cert subj 2";
1109 vector<uint8_t> subject_der(make_name_from_str(subject));
1110
1111 uint64_t serial_int = 66;
1112 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1113
1114 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1115 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
1116 vector<uint8_t> key_blob;
1117 vector<KeyCharacteristics> key_characteristics;
1118 auto builder = AuthorizationSetBuilder()
1119 .RsaSigningKey(key_size, 65537)
1120 .Digest(Digest::NONE)
1121 .Padding(PaddingMode::NONE)
1122 .AttestationChallenge(challenge)
1123 .AttestationApplicationId(app_id)
1124 .Authorization(TAG_NO_AUTH_REQUIRED)
1125 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1126 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1127 .SetDefaultValidity();
1128
1129 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1130 // Strongbox may not support factory provisioned attestation key.
1131 if (SecLevel() == SecurityLevel::STRONGBOX) {
1132 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1133 result = GenerateKeyWithSelfSignedAttestKey(
1134 AuthorizationSetBuilder()
1135 .RsaKey(key_size, 65537)
1136 .AttestKey()
1137 .SetDefaultValidity(), /* attest key params */
1138 builder, &key_blob, &key_characteristics);
1139 }
1140 }
1141 ASSERT_EQ(ErrorCode::OK, result);
1142 ASSERT_GT(key_blob.size(), 0U);
1143 CheckBaseParams(key_characteristics);
1144 CheckCharacteristics(key_blob, key_characteristics);
1145
1146 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1147
1148 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1149 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1150 << "Key size " << key_size << "missing";
1151 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1152
1153 ASSERT_GT(cert_chain_.size(), 0);
1154 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1155 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1156
1157 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1158 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1159 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1160 sw_enforced, hw_enforced, SecLevel(),
1161 cert_chain_[0].encodedCertificate));
1162
1163 CheckedDeleteKey(&key_blob);
1164 }
1165 }
1166
1167 /*
1168 * NewKeyGenerationTest.RsaWithRkpAttestation
1169 *
1170 * Verifies that keymint can generate all required RSA key sizes using an attestation key
1171 * that has been generated using an associate IRemotelyProvisionedComponent.
1172 */
TEST_P(NewKeyGenerationTest,RsaWithRkpAttestation)1173 TEST_P(NewKeyGenerationTest, RsaWithRkpAttestation) {
1174 if (!IsRkpSupportRequired()) {
1175 GTEST_SKIP() << "RKP support is not required on this platform";
1176 }
1177
1178 // Check for an IRemotelyProvisionedComponent instance associated with the
1179 // KeyMint instance.
1180 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1181 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1182 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1183 }
1184 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1185 << GetParam();
1186
1187 // Generate a P-256 keypair to use as an attestation key.
1188 MacedPublicKey macedPubKey;
1189 std::vector<uint8_t> privateKeyBlob;
1190 auto status =
1191 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1192 ASSERT_TRUE(status.isOk());
1193 vector<uint8_t> coseKeyData;
1194 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1195
1196 AttestationKey attestation_key;
1197 attestation_key.keyBlob = std::move(privateKeyBlob);
1198 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1199
1200 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1201 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
1202 auto challenge = "hello";
1203 auto app_id = "foo";
1204
1205 vector<uint8_t> key_blob;
1206 vector<KeyCharacteristics> key_characteristics;
1207 ASSERT_EQ(ErrorCode::OK,
1208 GenerateKey(AuthorizationSetBuilder()
1209 .RsaSigningKey(key_size, 65537)
1210 .Digest(Digest::NONE)
1211 .Padding(PaddingMode::NONE)
1212 .AttestationChallenge(challenge)
1213 .AttestationApplicationId(app_id)
1214 .Authorization(TAG_NO_AUTH_REQUIRED)
1215 .SetDefaultValidity(),
1216 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1217
1218 ASSERT_GT(key_blob.size(), 0U);
1219 CheckBaseParams(key_characteristics);
1220 CheckCharacteristics(key_blob, key_characteristics);
1221
1222 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1223
1224 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1225 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1226 << "Key size " << key_size << "missing";
1227 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1228
1229 // Attestation by itself is not valid (last entry is not self-signed).
1230 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1231
1232 // The signature over the attested key should correspond to the P256 public key.
1233 ASSERT_GT(cert_chain_.size(), 0);
1234 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1235 ASSERT_TRUE(key_cert.get());
1236 EVP_PKEY_Ptr signing_pubkey;
1237 p256_pub_key(coseKeyData, &signing_pubkey);
1238 ASSERT_TRUE(signing_pubkey.get());
1239
1240 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1241 << "Verification of attested certificate failed "
1242 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1243
1244 CheckedDeleteKey(&key_blob);
1245 }
1246 }
1247
1248 /*
1249 * NewKeyGenerationTest.EcdsaWithRkpAttestation
1250 *
1251 * Verifies that keymint can generate all required ECDSA key sizes using an attestation key
1252 * that has been generated using an associate IRemotelyProvisionedComponent.
1253 */
TEST_P(NewKeyGenerationTest,EcdsaWithRkpAttestation)1254 TEST_P(NewKeyGenerationTest, EcdsaWithRkpAttestation) {
1255 if (!IsRkpSupportRequired()) {
1256 GTEST_SKIP() << "RKP support is not required on this platform";
1257 }
1258
1259 // Check for an IRemotelyProvisionedComponent instance associated with the
1260 // KeyMint instance.
1261 std::shared_ptr<IRemotelyProvisionedComponent> rp = matching_rp_instance(GetParam());
1262 if (rp == nullptr && SecLevel() == SecurityLevel::STRONGBOX) {
1263 GTEST_SKIP() << "Encountered StrongBox implementation that does not support RKP";
1264 }
1265 ASSERT_NE(rp, nullptr) << "No IRemotelyProvisionedComponent found that matches KeyMint device "
1266 << GetParam();
1267
1268 // Generate a P-256 keypair to use as an attestation key.
1269 MacedPublicKey macedPubKey;
1270 std::vector<uint8_t> privateKeyBlob;
1271 auto status =
1272 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1273 ASSERT_TRUE(status.isOk());
1274 vector<uint8_t> coseKeyData;
1275 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1276
1277 AttestationKey attestation_key;
1278 attestation_key.keyBlob = std::move(privateKeyBlob);
1279 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1280
1281 for (auto curve : ValidCurves()) {
1282 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
1283 auto challenge = "hello";
1284 auto app_id = "foo";
1285
1286 vector<uint8_t> key_blob;
1287 vector<KeyCharacteristics> key_characteristics;
1288 ASSERT_EQ(ErrorCode::OK,
1289 GenerateKey(AuthorizationSetBuilder()
1290 .EcdsaSigningKey(curve)
1291 .Digest(Digest::NONE)
1292 .AttestationChallenge(challenge)
1293 .AttestationApplicationId(app_id)
1294 .Authorization(TAG_NO_AUTH_REQUIRED)
1295 .SetDefaultValidity(),
1296 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1297
1298 ASSERT_GT(key_blob.size(), 0U);
1299 CheckBaseParams(key_characteristics);
1300 CheckCharacteristics(key_blob, key_characteristics);
1301
1302 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1303
1304 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1305 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1306
1307 // Attestation by itself is not valid (last entry is not self-signed).
1308 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1309
1310 // The signature over the attested key should correspond to the P256 public key.
1311 ASSERT_GT(cert_chain_.size(), 0);
1312 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1313 ASSERT_TRUE(key_cert.get());
1314 EVP_PKEY_Ptr signing_pubkey;
1315 p256_pub_key(coseKeyData, &signing_pubkey);
1316 ASSERT_TRUE(signing_pubkey.get());
1317
1318 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1319 << "Verification of attested certificate failed "
1320 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1321
1322 CheckedDeleteKey(&key_blob);
1323 }
1324 }
1325
1326 /*
1327 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1328 *
1329 * Verifies that keymint attestation for RSA encryption keys with challenge and
1330 * app id is also successful.
1331 */
TEST_P(NewKeyGenerationTest,RsaEncryptionWithAttestation)1332 TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1333 auto key_size = 2048;
1334 auto challenge = "hello";
1335 auto app_id = "foo";
1336
1337 auto subject = "subj 2";
1338 vector<uint8_t> subject_der(make_name_from_str(subject));
1339
1340 uint64_t serial_int = 111166;
1341 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1342
1343 vector<uint8_t> key_blob;
1344 vector<KeyCharacteristics> key_characteristics;
1345 auto builder = AuthorizationSetBuilder()
1346 .RsaEncryptionKey(key_size, 65537)
1347 .Padding(PaddingMode::NONE)
1348 .AttestationChallenge(challenge)
1349 .AttestationApplicationId(app_id)
1350 .Authorization(TAG_NO_AUTH_REQUIRED)
1351 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1352 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1353 .SetDefaultValidity();
1354
1355 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1356 // Strongbox may not support factory provisioned attestation key.
1357 if (SecLevel() == SecurityLevel::STRONGBOX) {
1358 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1359 result = GenerateKeyWithSelfSignedAttestKey(
1360 AuthorizationSetBuilder()
1361 .RsaKey(key_size, 65537)
1362 .AttestKey()
1363 .SetDefaultValidity(), /* attest key params */
1364 builder, &key_blob, &key_characteristics);
1365 }
1366 }
1367 ASSERT_EQ(ErrorCode::OK, result);
1368
1369 ASSERT_GT(key_blob.size(), 0U);
1370 AuthorizationSet auths;
1371 for (auto& entry : key_characteristics) {
1372 auths.push_back(AuthorizationSet(entry.authorizations));
1373 }
1374
1375 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1376 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1377
1378 // Verify that App data and ROT are NOT included.
1379 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1380 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1381
1382 // Check that some unexpected tags/values are NOT present.
1383 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1384 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1385
1386 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1387
1388 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1389 ASSERT_TRUE(os_ver);
1390 EXPECT_EQ(*os_ver, os_version());
1391
1392 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1393
1394 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1395 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1396 << "Key size " << key_size << "missing";
1397 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1398
1399 ASSERT_GT(cert_chain_.size(), 0);
1400 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1401 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1402
1403 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1404 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1405 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1406 sw_enforced, hw_enforced, SecLevel(),
1407 cert_chain_[0].encodedCertificate));
1408
1409 CheckedDeleteKey(&key_blob);
1410 }
1411
1412 /*
1413 * NewKeyGenerationTest.RsaWithSelfSign
1414 *
1415 * Verifies that attesting to RSA key generation is successful, and returns
1416 * self signed certificate if no challenge is provided. And signing etc
1417 * works as expected.
1418 */
TEST_P(NewKeyGenerationTest,RsaWithSelfSign)1419 TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
1420 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1421 vector<uint8_t> subject_der(make_name_from_str(subject));
1422
1423 uint64_t serial_int = 0;
1424 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1425
1426 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1427 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
1428 vector<uint8_t> key_blob;
1429 vector<KeyCharacteristics> key_characteristics;
1430 ASSERT_EQ(ErrorCode::OK,
1431 GenerateKey(AuthorizationSetBuilder()
1432 .RsaSigningKey(key_size, 65537)
1433 .Digest(Digest::NONE)
1434 .Padding(PaddingMode::NONE)
1435 .Authorization(TAG_NO_AUTH_REQUIRED)
1436 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1437 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1438 .SetDefaultValidity(),
1439 &key_blob, &key_characteristics));
1440
1441 ASSERT_GT(key_blob.size(), 0U);
1442 CheckBaseParams(key_characteristics);
1443 CheckCharacteristics(key_blob, key_characteristics);
1444
1445 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1446
1447 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1448 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1449 << "Key size " << key_size << "missing";
1450 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1451
1452 ASSERT_EQ(cert_chain_.size(), 1);
1453 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1454 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1455
1456 CheckedDeleteKey(&key_blob);
1457 }
1458 }
1459
1460 /*
1461 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1462 *
1463 * Verifies that attesting to RSA checks for missing app ID.
1464 */
TEST_P(NewKeyGenerationTest,RsaWithAttestationMissAppId)1465 TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1466 auto challenge = "hello";
1467 vector<uint8_t> key_blob;
1468 vector<KeyCharacteristics> key_characteristics;
1469
1470 auto builder = AuthorizationSetBuilder()
1471 .RsaSigningKey(2048, 65537)
1472 .Digest(Digest::NONE)
1473 .Padding(PaddingMode::NONE)
1474 .AttestationChallenge(challenge)
1475 .Authorization(TAG_NO_AUTH_REQUIRED)
1476 .SetDefaultValidity();
1477
1478 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1479 // Strongbox may not support factory provisioned attestation key.
1480 if (SecLevel() == SecurityLevel::STRONGBOX) {
1481 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1482 result = GenerateKeyWithSelfSignedAttestKey(
1483 AuthorizationSetBuilder()
1484 .RsaKey(2048, 65537)
1485 .AttestKey()
1486 .SetDefaultValidity(), /* attest key params */
1487 builder, &key_blob, &key_characteristics);
1488 }
1489 }
1490 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
1491 }
1492
1493 /*
1494 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1495 *
1496 * Verifies that attesting to RSA ignores app id if challenge is missing.
1497 */
TEST_P(NewKeyGenerationTest,RsaWithAttestationAppIdIgnored)1498 TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1499 auto key_size = 2048;
1500 auto app_id = "foo";
1501
1502 auto subject = "cert subj 2";
1503 vector<uint8_t> subject_der(make_name_from_str(subject));
1504
1505 uint64_t serial_int = 1;
1506 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1507
1508 vector<uint8_t> key_blob;
1509 vector<KeyCharacteristics> key_characteristics;
1510 ASSERT_EQ(ErrorCode::OK,
1511 GenerateKey(AuthorizationSetBuilder()
1512 .RsaSigningKey(key_size, 65537)
1513 .Digest(Digest::NONE)
1514 .Padding(PaddingMode::NONE)
1515 .AttestationApplicationId(app_id)
1516 .Authorization(TAG_NO_AUTH_REQUIRED)
1517 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1518 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1519 .SetDefaultValidity(),
1520 &key_blob, &key_characteristics));
1521
1522 ASSERT_GT(key_blob.size(), 0U);
1523 CheckBaseParams(key_characteristics);
1524 CheckCharacteristics(key_blob, key_characteristics);
1525
1526 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1527
1528 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1529 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1530 << "Key size " << key_size << "missing";
1531 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1532
1533 ASSERT_GT(cert_chain_.size(), 0);
1534 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1535 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1536 ASSERT_EQ(cert_chain_.size(), 1);
1537
1538 CheckedDeleteKey(&key_blob);
1539 }
1540
1541 /*
1542 * NewKeyGenerationTest.LimitedUsageRsa
1543 *
1544 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1545 * resulting keys have correct characteristics.
1546 */
TEST_P(NewKeyGenerationTest,LimitedUsageRsa)1547 TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1548 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1549 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
1550 vector<uint8_t> key_blob;
1551 vector<KeyCharacteristics> key_characteristics;
1552 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1553 .RsaSigningKey(key_size, 65537)
1554 .Digest(Digest::NONE)
1555 .Padding(PaddingMode::NONE)
1556 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1557 .SetDefaultValidity(),
1558 &key_blob, &key_characteristics));
1559
1560 ASSERT_GT(key_blob.size(), 0U);
1561 CheckBaseParams(key_characteristics);
1562 CheckCharacteristics(key_blob, key_characteristics);
1563
1564 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1565
1566 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1567 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1568 << "Key size " << key_size << "missing";
1569 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1570
1571 // Check the usage count limit tag appears in the authorizations.
1572 AuthorizationSet auths;
1573 for (auto& entry : key_characteristics) {
1574 auths.push_back(AuthorizationSet(entry.authorizations));
1575 }
1576 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1577 << "key usage count limit " << 1U << " missing";
1578
1579 CheckedDeleteKey(&key_blob);
1580 }
1581 }
1582
1583 /*
1584 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1585 *
1586 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1587 * resulting keys have correct characteristics and attestation.
1588 */
TEST_P(NewKeyGenerationTest,LimitedUsageRsaWithAttestation)1589 TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
1590 auto challenge = "hello";
1591 auto app_id = "foo";
1592
1593 auto subject = "cert subj 2";
1594 vector<uint8_t> subject_der(make_name_from_str(subject));
1595
1596 uint64_t serial_int = 66;
1597 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1598
1599 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1600 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
1601 vector<uint8_t> key_blob;
1602 vector<KeyCharacteristics> key_characteristics;
1603 auto builder = AuthorizationSetBuilder()
1604 .RsaSigningKey(key_size, 65537)
1605 .Digest(Digest::NONE)
1606 .Padding(PaddingMode::NONE)
1607 .AttestationChallenge(challenge)
1608 .AttestationApplicationId(app_id)
1609 .Authorization(TAG_NO_AUTH_REQUIRED)
1610 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1611 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1612 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1613 .SetDefaultValidity();
1614
1615 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1616 // Strongbox may not support factory provisioned attestation key.
1617 if (SecLevel() == SecurityLevel::STRONGBOX) {
1618 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1619 result = GenerateKeyWithSelfSignedAttestKey(
1620 AuthorizationSetBuilder()
1621 .RsaKey(key_size, 65537)
1622 .AttestKey()
1623 .SetDefaultValidity(), /* attest key params */
1624 builder, &key_blob, &key_characteristics);
1625 }
1626 }
1627 ASSERT_EQ(ErrorCode::OK, result);
1628
1629 ASSERT_GT(key_blob.size(), 0U);
1630 CheckBaseParams(key_characteristics);
1631 CheckCharacteristics(key_blob, key_characteristics);
1632
1633 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1634
1635 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1636 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1637 << "Key size " << key_size << "missing";
1638 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1639
1640 // Check the usage count limit tag appears in the authorizations.
1641 AuthorizationSet auths;
1642 for (auto& entry : key_characteristics) {
1643 auths.push_back(AuthorizationSet(entry.authorizations));
1644 }
1645 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1646 << "key usage count limit " << 1U << " missing";
1647
1648 // Check the usage count limit tag also appears in the attestation.
1649 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1650 ASSERT_GT(cert_chain_.size(), 0);
1651 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1652
1653 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1654 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1655 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1656 sw_enforced, hw_enforced, SecLevel(),
1657 cert_chain_[0].encodedCertificate));
1658
1659 CheckedDeleteKey(&key_blob);
1660 }
1661 }
1662
1663 /*
1664 * NewKeyGenerationTest.NoInvalidRsaSizes
1665 *
1666 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1667 */
TEST_P(NewKeyGenerationTest,NoInvalidRsaSizes)1668 TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1669 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1670 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
1671 vector<uint8_t> key_blob;
1672 vector<KeyCharacteristics> key_characteristics;
1673 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1674 GenerateKey(AuthorizationSetBuilder()
1675 .RsaSigningKey(key_size, 65537)
1676 .Digest(Digest::NONE)
1677 .Padding(PaddingMode::NONE)
1678 .SetDefaultValidity(),
1679 &key_blob, &key_characteristics));
1680 }
1681 }
1682
1683 /*
1684 * NewKeyGenerationTest.RsaNoDefaultSize
1685 *
1686 * Verifies that failing to specify a key size for RSA key generation returns
1687 * UNSUPPORTED_KEY_SIZE.
1688 */
TEST_P(NewKeyGenerationTest,RsaNoDefaultSize)1689 TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1690 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1691 GenerateKey(AuthorizationSetBuilder()
1692 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1693 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
1694 .SigningKey()
1695 .SetDefaultValidity()));
1696 }
1697
1698 /*
1699 * NewKeyGenerationTest.RsaMissingParams
1700 *
1701 * Verifies that omitting optional tags works.
1702 */
TEST_P(NewKeyGenerationTest,RsaMissingParams)1703 TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1704 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1705 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
1706 ASSERT_EQ(ErrorCode::OK,
1707 GenerateKey(
1708 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1709 CheckedDeleteKey();
1710 }
1711 }
1712
1713 /*
1714 * NewKeyGenerationTest.Ecdsa
1715 *
1716 * Verifies that keymint can generate all required EC curves, and that the resulting keys
1717 * have correct characteristics.
1718 */
TEST_P(NewKeyGenerationTest,Ecdsa)1719 TEST_P(NewKeyGenerationTest, Ecdsa) {
1720 for (auto curve : ValidCurves()) {
1721 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
1722 vector<uint8_t> key_blob;
1723 vector<KeyCharacteristics> key_characteristics;
1724 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1725 .EcdsaSigningKey(curve)
1726 .Digest(Digest::NONE)
1727 .SetDefaultValidity(),
1728 &key_blob, &key_characteristics));
1729 ASSERT_GT(key_blob.size(), 0U);
1730 CheckBaseParams(key_characteristics);
1731 CheckCharacteristics(key_blob, key_characteristics);
1732
1733 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1734
1735 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1736 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1737
1738 CheckedDeleteKey(&key_blob);
1739 }
1740 }
1741
1742 /*
1743 * NewKeyGenerationTest.EcdsaCurve25519
1744 *
1745 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1746 * has correct characteristics.
1747 */
TEST_P(NewKeyGenerationTest,EcdsaCurve25519)1748 TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1749 if (!Curve25519Supported()) {
1750 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1751 }
1752
1753 EcCurve curve = EcCurve::CURVE_25519;
1754 vector<uint8_t> key_blob;
1755 vector<KeyCharacteristics> key_characteristics;
1756 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1757 .EcdsaSigningKey(curve)
1758 .Digest(Digest::NONE)
1759 .SetDefaultValidity(),
1760 &key_blob, &key_characteristics);
1761 ASSERT_EQ(result, ErrorCode::OK);
1762 ASSERT_GT(key_blob.size(), 0U);
1763
1764 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1765 ASSERT_GT(cert_chain_.size(), 0);
1766
1767 CheckBaseParams(key_characteristics);
1768 CheckCharacteristics(key_blob, key_characteristics);
1769
1770 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1771
1772 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1773 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1774
1775 CheckedDeleteKey(&key_blob);
1776 }
1777
1778 /*
1779 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1780 *
1781 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1782 * SIGN and AGREE_KEY.
1783 */
TEST_P(NewKeyGenerationTest,EcdsaCurve25519MultiPurposeFail)1784 TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1785 if (!Curve25519Supported()) {
1786 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1787 }
1788
1789 EcCurve curve = EcCurve::CURVE_25519;
1790 vector<uint8_t> key_blob;
1791 vector<KeyCharacteristics> key_characteristics;
1792 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1793 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1794 .EcdsaSigningKey(curve)
1795 .Digest(Digest::NONE)
1796 .SetDefaultValidity(),
1797 &key_blob, &key_characteristics);
1798 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1799 }
1800
1801 /*
1802 * NewKeyGenerationTest.EcdsaWithMissingValidity
1803 *
1804 * Verifies that keymint returns an error while generating asymmetric key
1805 * without providing NOT_BEFORE and NOT_AFTER parameters.
1806 */
TEST_P(NewKeyGenerationTest,EcdsaWithMissingValidity)1807 TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
1808 if (AidlVersion() < 2) {
1809 /*
1810 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1811 * specified for asymmetric key generation. However, this was not
1812 * checked at the time so we can only be strict about checking this for
1813 * implementations of KeyMint version 2 and above.
1814 */
1815 GTEST_SKIP() << "Validity strict since KeyMint v2";
1816 }
1817 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1818 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1819 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1820
1821 vector<uint8_t> key_blob;
1822 vector<KeyCharacteristics> key_characteristics;
1823 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1824 GenerateKey(AuthorizationSetBuilder()
1825 .EcdsaSigningKey(EcCurve::P_256)
1826 .Digest(Digest::NONE)
1827 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1828 kUndefinedExpirationDateTime),
1829 &key_blob, &key_characteristics));
1830
1831 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1832 GenerateKey(AuthorizationSetBuilder()
1833 .EcdsaSigningKey(EcCurve::P_256)
1834 .Digest(Digest::NONE)
1835 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1836 &key_blob, &key_characteristics));
1837 }
1838
1839 /*
1840 * NewKeyGenerationTest.EcdsaAttestation
1841 *
1842 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1843 * an attestation will be generated.
1844 */
TEST_P(NewKeyGenerationTest,EcdsaAttestation)1845 TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1846 auto challenge = "hello";
1847 auto app_id = "foo";
1848
1849 auto subject = "cert subj 2";
1850 vector<uint8_t> subject_der(make_name_from_str(subject));
1851
1852 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1853 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1854
1855 for (auto curve : ValidCurves()) {
1856 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
1857 vector<uint8_t> key_blob;
1858 vector<KeyCharacteristics> key_characteristics;
1859 auto builder = AuthorizationSetBuilder()
1860 .Authorization(TAG_NO_AUTH_REQUIRED)
1861 .EcdsaSigningKey(curve)
1862 .Digest(Digest::NONE)
1863 .AttestationChallenge(challenge)
1864 .AttestationApplicationId(app_id)
1865 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1866 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1867 .SetDefaultValidity();
1868
1869 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1870 // Strongbox may not support factory provisioned attestation key.
1871 if (SecLevel() == SecurityLevel::STRONGBOX) {
1872 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1873 result = GenerateKeyWithSelfSignedAttestKey(
1874 AuthorizationSetBuilder()
1875 .EcdsaKey(curve)
1876 .AttestKey()
1877 .SetDefaultValidity(), /* attest key params */
1878 builder, &key_blob, &key_characteristics);
1879 }
1880 }
1881 ASSERT_EQ(ErrorCode::OK, result);
1882 ASSERT_GT(key_blob.size(), 0U);
1883 CheckBaseParams(key_characteristics);
1884 CheckCharacteristics(key_blob, key_characteristics);
1885
1886 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1887
1888 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1889 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1890
1891 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1892 ASSERT_GT(cert_chain_.size(), 0);
1893 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1894
1895 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1896 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1897 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1898 sw_enforced, hw_enforced, SecLevel(),
1899 cert_chain_[0].encodedCertificate));
1900
1901 CheckedDeleteKey(&key_blob);
1902 }
1903 }
1904
1905 /*
1906 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1907 *
1908 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1909 * an attestation will be generated.
1910 */
TEST_P(NewKeyGenerationTest,EcdsaAttestationCurve25519)1911 TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1912 if (!Curve25519Supported()) {
1913 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1914 }
1915
1916 EcCurve curve = EcCurve::CURVE_25519;
1917 auto challenge = "hello";
1918 auto app_id = "foo";
1919
1920 auto subject = "cert subj 2";
1921 vector<uint8_t> subject_der(make_name_from_str(subject));
1922
1923 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1924 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1925
1926 vector<uint8_t> key_blob;
1927 vector<KeyCharacteristics> key_characteristics;
1928 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1929 .Authorization(TAG_NO_AUTH_REQUIRED)
1930 .EcdsaSigningKey(curve)
1931 .Digest(Digest::NONE)
1932 .AttestationChallenge(challenge)
1933 .AttestationApplicationId(app_id)
1934 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1935 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1936 .SetDefaultValidity(),
1937 &key_blob, &key_characteristics);
1938 ASSERT_EQ(ErrorCode::OK, result);
1939 ASSERT_GT(key_blob.size(), 0U);
1940 CheckBaseParams(key_characteristics);
1941 CheckCharacteristics(key_blob, key_characteristics);
1942
1943 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1944
1945 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1946 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1947
1948 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1949 ASSERT_GT(cert_chain_.size(), 0);
1950 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1951
1952 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1953 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1954 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1955 sw_enforced, hw_enforced, SecLevel(),
1956 cert_chain_[0].encodedCertificate));
1957
1958 CheckedDeleteKey(&key_blob);
1959 }
1960
1961 /*
1962 * NewKeyGenerationTest.EcdsaAttestationTags
1963 *
1964 * Verifies that creation of an attested ECDSA key includes various tags in the
1965 * attestation extension.
1966 */
TEST_P(NewKeyGenerationTest,EcdsaAttestationTags)1967 TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1968 auto challenge = "hello";
1969 auto app_id = "foo";
1970 auto subject = "cert subj 2";
1971 vector<uint8_t> subject_der(make_name_from_str(subject));
1972 uint64_t serial_int = 0x1010;
1973 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1974 const AuthorizationSetBuilder base_builder =
1975 AuthorizationSetBuilder()
1976 .Authorization(TAG_NO_AUTH_REQUIRED)
1977 .EcdsaSigningKey(EcCurve::P_256)
1978 .Digest(Digest::NONE)
1979 .AttestationChallenge(challenge)
1980 .AttestationApplicationId(app_id)
1981 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1982 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1983 .SetDefaultValidity();
1984
1985 // Various tags that map to fields in the attestation extension ASN.1 schema.
1986 auto extra_tags = AuthorizationSetBuilder()
1987 .Authorization(TAG_ROLLBACK_RESISTANCE)
1988 .Authorization(TAG_EARLY_BOOT_ONLY)
1989 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1990 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1991 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1992 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1993 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1994 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1995 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1996 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1997 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1998 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
1999
2000 for (const KeyParameter& tag : extra_tags) {
2001 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2002 vector<uint8_t> key_blob;
2003 vector<KeyCharacteristics> key_characteristics;
2004 AuthorizationSetBuilder builder = base_builder;
2005 builder.push_back(tag);
2006 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
2007 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
2008 tag.tag == TAG_ROLLBACK_RESISTANCE) {
2009 continue;
2010 }
2011 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
2012 // Tag not required to be supported by all KeyMint implementations.
2013 continue;
2014 }
2015 // Strongbox may not support factory provisioned attestation key.
2016 if (SecLevel() == SecurityLevel::STRONGBOX) {
2017 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2018 result = GenerateKeyWithSelfSignedAttestKey(
2019 AuthorizationSetBuilder()
2020 .EcdsaKey(EcCurve::P_256)
2021 .AttestKey()
2022 .SetDefaultValidity(), /* attest key params */
2023 builder, &key_blob, &key_characteristics);
2024 }
2025 }
2026 ASSERT_EQ(result, ErrorCode::OK);
2027 ASSERT_GT(key_blob.size(), 0U);
2028
2029 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2030 ASSERT_GT(cert_chain_.size(), 0);
2031 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2032
2033 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2034 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2035 // Some tags are optional, so don't require them to be in the enforcements.
2036 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
2037 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
2038 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
2039 }
2040
2041 // Verifying the attestation record will check for the specific tag because
2042 // it's included in the authorizations.
2043 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2044 hw_enforced, SecLevel(),
2045 cert_chain_[0].encodedCertificate));
2046
2047 CheckedDeleteKey(&key_blob);
2048 }
2049
2050 // Collection of invalid attestation ID tags.
2051 auto invalid_tags =
2052 AuthorizationSetBuilder()
2053 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
2054 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
2055 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
2056 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
2057 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
2058 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
2059 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
2060 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
2061 for (const KeyParameter& tag : invalid_tags) {
2062 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
2063 vector<uint8_t> key_blob;
2064 vector<KeyCharacteristics> key_characteristics;
2065 AuthorizationSetBuilder builder =
2066 AuthorizationSetBuilder()
2067 .Authorization(TAG_NO_AUTH_REQUIRED)
2068 .EcdsaSigningKey(EcCurve::P_256)
2069 .Digest(Digest::NONE)
2070 .AttestationChallenge(challenge)
2071 .AttestationApplicationId(app_id)
2072 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2073 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2074 .SetDefaultValidity();
2075 builder.push_back(tag);
2076
2077 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
2078 // Strongbox may not support factory provisioned attestation key.
2079 if (SecLevel() == SecurityLevel::STRONGBOX) {
2080 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2081 error = GenerateKeyWithSelfSignedAttestKey(
2082 AuthorizationSetBuilder()
2083 .EcdsaKey(EcCurve::P_256)
2084 .AttestKey()
2085 .SetDefaultValidity(), /* attest key params */
2086 builder, &key_blob, &key_characteristics);
2087 }
2088 }
2089
2090 device_id_attestation_check_acceptable_error(tag.tag, error);
2091 }
2092 }
2093
2094 /*
2095 * NewKeyGenerationTest.EcdsaAttestationIdTags
2096 *
2097 * Verifies that creation of an attested ECDSA key includes various ID tags in the
2098 * attestation extension.
2099 */
TEST_P(NewKeyGenerationTest,EcdsaAttestationIdTags)2100 TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
2101 if (is_gsi_image()) {
2102 // GSI sets up a standard set of device identifiers that may not match
2103 // the device identifiers held by the device.
2104 GTEST_SKIP() << "Test not applicable under GSI";
2105 }
2106 auto challenge = "hello";
2107 auto app_id = "foo";
2108 auto subject = "cert subj 2";
2109 vector<uint8_t> subject_der(make_name_from_str(subject));
2110 uint64_t serial_int = 0x1010;
2111 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2112 const AuthorizationSetBuilder base_builder =
2113 AuthorizationSetBuilder()
2114 .Authorization(TAG_NO_AUTH_REQUIRED)
2115 .EcdsaSigningKey(EcCurve::P_256)
2116 .Digest(Digest::NONE)
2117 .AttestationChallenge(challenge)
2118 .AttestationApplicationId(app_id)
2119 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2120 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2121 .SetDefaultValidity();
2122
2123 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2124 auto extra_tags = AuthorizationSetBuilder();
2125 // Use ro.product.brand_for_attestation property for attestation if it is present else fallback
2126 // to ro.product.brand
2127 std::string prop_value =
2128 ::android::base::GetProperty("ro.product.brand_for_attestation", /* default= */ "");
2129 if (!prop_value.empty()) {
2130 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND,
2131 "ro.product.brand_for_attestation");
2132 } else {
2133 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
2134 }
2135 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
2136 // Use ro.product.name_for_attestation property for attestation if it is present else fallback
2137 // to ro.product.name
2138 prop_value = ::android::base::GetProperty("ro.product.name_for_attestation", /* default= */ "");
2139 if (!prop_value.empty()) {
2140 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT,
2141 "ro.product.name_for_attestation");
2142 } else {
2143 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
2144 }
2145 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
2146 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
2147 // Use ro.product.model_for_attestation property for attestation if it is present else fallback
2148 // to ro.product.model
2149 prop_value =
2150 ::android::base::GetProperty("ro.product.model_for_attestation", /* default= */ "");
2151 if (!prop_value.empty()) {
2152 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL,
2153 "ro.product.model_for_attestation");
2154 } else {
2155 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
2156 }
2157
2158 for (const KeyParameter& tag : extra_tags) {
2159 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2160 vector<uint8_t> key_blob;
2161 vector<KeyCharacteristics> key_characteristics;
2162 AuthorizationSetBuilder builder = base_builder;
2163 builder.push_back(tag);
2164 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
2165 // Strongbox may not support factory provisioned attestation key.
2166 if (SecLevel() == SecurityLevel::STRONGBOX) {
2167 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2168 }
2169 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2170 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
2171 continue;
2172 }
2173 ASSERT_EQ(result, ErrorCode::OK);
2174 ASSERT_GT(key_blob.size(), 0U);
2175
2176 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2177 ASSERT_GT(cert_chain_.size(), 0);
2178 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2179
2180 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2181 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2182
2183 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2184 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2185 // attestation extension should contain them, so make sure the extra tag is added.
2186 hw_enforced.push_back(tag);
2187
2188 // Verifying the attestation record will check for the specific tag because
2189 // it's included in the authorizations.
2190 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2191 hw_enforced, SecLevel(),
2192 cert_chain_[0].encodedCertificate));
2193
2194 CheckedDeleteKey(&key_blob);
2195 }
2196 }
2197
2198 /*
2199 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2200 *
2201 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2202 */
TEST_P(NewKeyGenerationTest,EcdsaAttestationUniqueId)2203 TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2204 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
2205 vector<uint8_t>* unique_id, bool reset = false) {
2206 auto challenge = "hello";
2207 auto subject = "cert subj 2";
2208 vector<uint8_t> subject_der(make_name_from_str(subject));
2209 uint64_t serial_int = 0x1010;
2210 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2211 AuthorizationSetBuilder builder =
2212 AuthorizationSetBuilder()
2213 .Authorization(TAG_NO_AUTH_REQUIRED)
2214 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2215 .EcdsaSigningKey(EcCurve::P_256)
2216 .Digest(Digest::NONE)
2217 .AttestationChallenge(challenge)
2218 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2219 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2220 .AttestationApplicationId(app_id)
2221 .Authorization(TAG_CREATION_DATETIME, datetime)
2222 .SetDefaultValidity();
2223 if (reset) {
2224 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2225 }
2226 auto result = GenerateKey(builder);
2227 if (SecLevel() == SecurityLevel::STRONGBOX) {
2228 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2229 result = GenerateKeyWithSelfSignedAttestKey(
2230 AuthorizationSetBuilder()
2231 .EcdsaKey(EcCurve::P_256)
2232 .AttestKey()
2233 .SetDefaultValidity(), /* attest key params */
2234 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2235 }
2236 }
2237 ASSERT_EQ(ErrorCode::OK, result);
2238 ASSERT_GT(key_blob_.size(), 0U);
2239
2240 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2241 ASSERT_GT(cert_chain_.size(), 0);
2242 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2243
2244 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2245 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2246
2247 // Check that the unique ID field in the extension is non-empty.
2248 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2249 hw_enforced, SecLevel(),
2250 cert_chain_[0].encodedCertificate, unique_id));
2251 EXPECT_GT(unique_id->size(), 0);
2252 CheckedDeleteKey();
2253 };
2254
2255 // Generate unique ID
2256 auto app_id = "foo";
2257 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2258 vector<uint8_t> unique_id;
2259 get_unique_id(app_id, cert_date, &unique_id);
2260
2261 // Generating a new key with the same parameters should give the same unique ID.
2262 vector<uint8_t> unique_id2;
2263 get_unique_id(app_id, cert_date, &unique_id2);
2264 EXPECT_EQ(unique_id, unique_id2);
2265
2266 // Generating a new key with a slightly different date should give the same unique ID.
2267 uint64_t rounded_date = cert_date / 2592000000LLU;
2268 uint64_t min_date = rounded_date * 2592000000LLU;
2269 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2270
2271 vector<uint8_t> unique_id3;
2272 get_unique_id(app_id, min_date, &unique_id3);
2273 EXPECT_EQ(unique_id, unique_id3);
2274
2275 vector<uint8_t> unique_id4;
2276 get_unique_id(app_id, max_date, &unique_id4);
2277 EXPECT_EQ(unique_id, unique_id4);
2278
2279 // A different attestation application ID should yield a different unique ID.
2280 auto app_id2 = "different_foo";
2281 vector<uint8_t> unique_id5;
2282 get_unique_id(app_id2, cert_date, &unique_id5);
2283 EXPECT_NE(unique_id, unique_id5);
2284
2285 // A radically different date should yield a different unique ID.
2286 vector<uint8_t> unique_id6;
2287 get_unique_id(app_id, 1611621648000, &unique_id6);
2288 EXPECT_NE(unique_id, unique_id6);
2289
2290 vector<uint8_t> unique_id7;
2291 get_unique_id(app_id, max_date + 1, &unique_id7);
2292 EXPECT_NE(unique_id, unique_id7);
2293
2294 vector<uint8_t> unique_id8;
2295 get_unique_id(app_id, min_date - 1, &unique_id8);
2296 EXPECT_NE(unique_id, unique_id8);
2297
2298 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2299 vector<uint8_t> unique_id9;
2300 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2301 EXPECT_NE(unique_id, unique_id9);
2302 }
2303
2304 /*
2305 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2306 *
2307 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2308 */
TEST_P(NewKeyGenerationTest,EcdsaAttestationTagNoApplicationId)2309 TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2310 auto challenge = "hello";
2311 auto attest_app_id = "foo";
2312 auto subject = "cert subj 2";
2313 vector<uint8_t> subject_der(make_name_from_str(subject));
2314 uint64_t serial_int = 0x1010;
2315 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2316
2317 // Earlier versions of the attestation extension schema included a slot:
2318 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2319 // This should never have been included, and should never be filled in.
2320 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2321 // to confirm that this field never makes it into the attestation extension.
2322 vector<uint8_t> key_blob;
2323 vector<KeyCharacteristics> key_characteristics;
2324 auto builder = AuthorizationSetBuilder()
2325 .Authorization(TAG_NO_AUTH_REQUIRED)
2326 .EcdsaSigningKey(EcCurve::P_256)
2327 .Digest(Digest::NONE)
2328 .AttestationChallenge(challenge)
2329 .AttestationApplicationId(attest_app_id)
2330 .Authorization(TAG_APPLICATION_ID, "client_id")
2331 .Authorization(TAG_APPLICATION_DATA, "appdata")
2332 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2333 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2334 .SetDefaultValidity();
2335
2336 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
2337 // Strongbox may not support factory provisioned attestation key.
2338 if (SecLevel() == SecurityLevel::STRONGBOX) {
2339 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2340 result = GenerateKeyWithSelfSignedAttestKey(
2341 AuthorizationSetBuilder()
2342 .EcdsaKey(EcCurve::P_256)
2343 .AttestKey()
2344 .SetDefaultValidity(), /* attest key params */
2345 builder, &key_blob, &key_characteristics);
2346 }
2347 }
2348 ASSERT_EQ(result, ErrorCode::OK);
2349 ASSERT_GT(key_blob.size(), 0U);
2350
2351 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2352 ASSERT_GT(cert_chain_.size(), 0);
2353 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2354
2355 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2356 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2357 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2358 hw_enforced, SecLevel(),
2359 cert_chain_[0].encodedCertificate));
2360
2361 // Check that the app id is not in the cert.
2362 string app_id = "clientid";
2363 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2364 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2365 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2366 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2367 cert_chain_[0].encodedCertificate.end());
2368
2369 CheckedDeleteKey(&key_blob);
2370 }
2371
2372 /*
2373 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2374 *
2375 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2376 * the key will generate a self signed attestation.
2377 */
TEST_P(NewKeyGenerationTest,EcdsaSelfSignAttestation)2378 TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
2379 auto subject = "cert subj 2";
2380 vector<uint8_t> subject_der(make_name_from_str(subject));
2381
2382 uint64_t serial_int = 0x123456FFF1234;
2383 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2384
2385 for (auto curve : ValidCurves()) {
2386 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2387 vector<uint8_t> key_blob;
2388 vector<KeyCharacteristics> key_characteristics;
2389 ASSERT_EQ(ErrorCode::OK,
2390 GenerateKey(AuthorizationSetBuilder()
2391 .EcdsaSigningKey(curve)
2392 .Digest(Digest::NONE)
2393 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2394 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2395 .SetDefaultValidity(),
2396 &key_blob, &key_characteristics));
2397 ASSERT_GT(key_blob.size(), 0U);
2398 CheckBaseParams(key_characteristics);
2399 CheckCharacteristics(key_blob, key_characteristics);
2400
2401 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2402
2403 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
2404 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
2405
2406 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2407 ASSERT_EQ(cert_chain_.size(), 1);
2408 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
2409
2410 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2411 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2412
2413 CheckedDeleteKey(&key_blob);
2414 }
2415 }
2416
2417 /*
2418 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2419 *
2420 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2421 * app id must also be provided or else it will fail.
2422 */
TEST_P(NewKeyGenerationTest,EcdsaAttestationRequireAppId)2423 TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2424 auto challenge = "hello";
2425 vector<uint8_t> key_blob;
2426 vector<KeyCharacteristics> key_characteristics;
2427 auto builder = AuthorizationSetBuilder()
2428 .EcdsaSigningKey(EcCurve::P_256)
2429 .Digest(Digest::NONE)
2430 .AttestationChallenge(challenge)
2431 .SetDefaultValidity();
2432
2433 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
2434 // Strongbox may not support factory provisioned attestation key.
2435 if (SecLevel() == SecurityLevel::STRONGBOX) {
2436 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2437 result = GenerateKeyWithSelfSignedAttestKey(
2438 AuthorizationSetBuilder()
2439 .EcdsaKey(EcCurve::P_256)
2440 .AttestKey()
2441 .SetDefaultValidity(), /* attest key params */
2442 builder, &key_blob, &key_characteristics);
2443 }
2444 }
2445 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
2446 }
2447
2448 /*
2449 * NewKeyGenerationTest.EcdsaIgnoreAppId
2450 *
2451 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2452 * any appid will be ignored, and keymint will generate a self sign certificate.
2453 */
TEST_P(NewKeyGenerationTest,EcdsaIgnoreAppId)2454 TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2455 auto app_id = "foo";
2456
2457 for (auto curve : ValidCurves()) {
2458 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2459 vector<uint8_t> key_blob;
2460 vector<KeyCharacteristics> key_characteristics;
2461 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2462 .EcdsaSigningKey(curve)
2463 .Digest(Digest::NONE)
2464 .AttestationApplicationId(app_id)
2465 .SetDefaultValidity(),
2466 &key_blob, &key_characteristics));
2467
2468 ASSERT_GT(key_blob.size(), 0U);
2469 CheckBaseParams(key_characteristics);
2470 CheckCharacteristics(key_blob, key_characteristics);
2471
2472 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2473
2474 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
2475 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
2476
2477 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2478 ASSERT_EQ(cert_chain_.size(), 1);
2479
2480 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2481 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2482
2483 CheckedDeleteKey(&key_blob);
2484 }
2485 }
2486
2487 /*
2488 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2489 *
2490 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2491 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2492 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2493 * to specify how many following bytes will be used to encode the length.
2494 */
TEST_P(NewKeyGenerationTest,AttestationApplicationIDLengthProperlyEncoded)2495 TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2496 auto challenge = "hello";
2497 std::vector<uint32_t> app_id_lengths{143, 258};
2498
2499 for (uint32_t length : app_id_lengths) {
2500 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
2501 const string app_id(length, 'a');
2502 vector<uint8_t> key_blob;
2503 vector<KeyCharacteristics> key_characteristics;
2504 auto builder = AuthorizationSetBuilder()
2505 .Authorization(TAG_NO_AUTH_REQUIRED)
2506 .EcdsaSigningKey(EcCurve::P_256)
2507 .Digest(Digest::NONE)
2508 .AttestationChallenge(challenge)
2509 .AttestationApplicationId(app_id)
2510 .SetDefaultValidity();
2511
2512 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
2513 // Strongbox may not support factory provisioned attestation key.
2514 if (SecLevel() == SecurityLevel::STRONGBOX) {
2515 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2516 result = GenerateKeyWithSelfSignedAttestKey(
2517 AuthorizationSetBuilder()
2518 .EcdsaKey(EcCurve::P_256)
2519 .AttestKey()
2520 .SetDefaultValidity(), /* attest key params */
2521 builder, &key_blob, &key_characteristics);
2522 }
2523 }
2524 ASSERT_EQ(ErrorCode::OK, result);
2525 ASSERT_GT(key_blob.size(), 0U);
2526 CheckBaseParams(key_characteristics);
2527 CheckCharacteristics(key_blob, key_characteristics);
2528
2529 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2530
2531 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
2532 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
2533
2534 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2535 ASSERT_GT(cert_chain_.size(), 0);
2536
2537 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2538 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2539 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
2540 sw_enforced, hw_enforced, SecLevel(),
2541 cert_chain_[0].encodedCertificate));
2542
2543 CheckedDeleteKey(&key_blob);
2544 }
2545 }
2546
2547 /*
2548 * NewKeyGenerationTest.LimitedUsageEcdsa
2549 *
2550 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2551 * resulting keys have correct characteristics.
2552 */
TEST_P(NewKeyGenerationTest,LimitedUsageEcdsa)2553 TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
2554 for (auto curve : ValidCurves()) {
2555 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2556 vector<uint8_t> key_blob;
2557 vector<KeyCharacteristics> key_characteristics;
2558 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2559 .EcdsaSigningKey(curve)
2560 .Digest(Digest::NONE)
2561 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2562 .SetDefaultValidity(),
2563 &key_blob, &key_characteristics));
2564
2565 ASSERT_GT(key_blob.size(), 0U);
2566 CheckBaseParams(key_characteristics);
2567 CheckCharacteristics(key_blob, key_characteristics);
2568
2569 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2570
2571 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
2572 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
2573
2574 // Check the usage count limit tag appears in the authorizations.
2575 AuthorizationSet auths;
2576 for (auto& entry : key_characteristics) {
2577 auths.push_back(AuthorizationSet(entry.authorizations));
2578 }
2579 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2580 << "key usage count limit " << 1U << " missing";
2581
2582 CheckedDeleteKey(&key_blob);
2583 }
2584 }
2585
2586 /*
2587 * NewKeyGenerationTest.EcdsaDefaultSize
2588 *
2589 * Verifies that failing to specify a curve for EC key generation returns
2590 * UNSUPPORTED_KEY_SIZE.
2591 */
TEST_P(NewKeyGenerationTest,EcdsaDefaultSize)2592 TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2593 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2594 GenerateKey(AuthorizationSetBuilder()
2595 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2596 .SigningKey()
2597 .Digest(Digest::NONE)
2598 .SetDefaultValidity()));
2599 }
2600
2601 /*
2602 * NewKeyGenerationTest.EcdsaInvalidCurve
2603 *
2604 * Verifies that specifying an invalid curve for EC key generation returns
2605 * UNSUPPORTED_KEY_SIZE.
2606 */
TEST_P(NewKeyGenerationTest,EcdsaInvalidCurve)2607 TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
2608 for (auto curve : InvalidCurves()) {
2609 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2610 vector<uint8_t> key_blob;
2611 vector<KeyCharacteristics> key_characteristics;
2612 auto result = GenerateKey(AuthorizationSetBuilder()
2613 .EcdsaSigningKey(curve)
2614 .Digest(Digest::NONE)
2615 .SetDefaultValidity(),
2616 &key_blob, &key_characteristics);
2617 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2618 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2619 }
2620
2621 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2622 GenerateKey(AuthorizationSetBuilder()
2623 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2624 .Authorization(TAG_KEY_SIZE, 190)
2625 .SigningKey()
2626 .Digest(Digest::NONE)
2627 .SetDefaultValidity()));
2628 }
2629
2630 /*
2631 * NewKeyGenerationTest.EcdsaMissingCurve
2632 *
2633 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V3.
2634 */
TEST_P(NewKeyGenerationTest,EcdsaMissingCurve)2635 TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2636 if (AidlVersion() < 3) {
2637 /*
2638 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2639 * However, this was not checked at the time so we can only be strict about checking this
2640 * for implementations of KeyMint version 3 and above.
2641 */
2642 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v3";
2643 }
2644 /* If EC_CURVE not provided, generateKey
2645 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2646 */
2647 auto result = GenerateKey(
2648 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2649 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2650 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2651 }
2652
2653 /*
2654 * NewKeyGenerationTest.EcdsaMismatchKeySize
2655 *
2656 * Verifies that specifying mismatched key size and curve for EC key generation returns
2657 * INVALID_ARGUMENT.
2658 */
TEST_P(NewKeyGenerationTest,EcdsaMismatchKeySize)2659 TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
2660 if (SecLevel() == SecurityLevel::STRONGBOX) {
2661 GTEST_SKIP() << "Test not applicable to StrongBox device";
2662 }
2663
2664 auto result = GenerateKey(AuthorizationSetBuilder()
2665 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2666 .Authorization(TAG_KEY_SIZE, 224)
2667 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
2668 .SigningKey()
2669 .Digest(Digest::NONE)
2670 .SetDefaultValidity());
2671 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
2672 }
2673
2674 /*
2675 * NewKeyGenerationTest.EcdsaAllValidCurves
2676 *
2677 * Verifies that keymint does not support any curve designated as unsupported.
2678 */
TEST_P(NewKeyGenerationTest,EcdsaAllValidCurves)2679 TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2680 Digest digest;
2681 if (SecLevel() == SecurityLevel::STRONGBOX) {
2682 digest = Digest::SHA_2_256;
2683 } else {
2684 digest = Digest::SHA_2_512;
2685 }
2686 for (auto curve : ValidCurves()) {
2687 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2688 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2689 .EcdsaSigningKey(curve)
2690 .Digest(digest)
2691 .SetDefaultValidity()))
2692 << "Failed to generate key on curve: " << curve;
2693 CheckedDeleteKey();
2694 }
2695 }
2696
2697 /*
2698 * NewKeyGenerationTest.Hmac
2699 *
2700 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2701 * characteristics.
2702 */
TEST_P(NewKeyGenerationTest,Hmac)2703 TEST_P(NewKeyGenerationTest, Hmac) {
2704 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2705 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2706 vector<uint8_t> key_blob;
2707 vector<KeyCharacteristics> key_characteristics;
2708 constexpr size_t key_size = 128;
2709 ASSERT_EQ(ErrorCode::OK,
2710 GenerateKey(
2711 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2712 TAG_MIN_MAC_LENGTH, 128),
2713 &key_blob, &key_characteristics));
2714
2715 ASSERT_GT(key_blob.size(), 0U);
2716 CheckBaseParams(key_characteristics);
2717 CheckCharacteristics(key_blob, key_characteristics);
2718
2719 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2720 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2721 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2722 << "Key size " << key_size << "missing";
2723
2724 CheckedDeleteKey(&key_blob);
2725 }
2726 }
2727
2728 /*
2729 * NewKeyGenerationTest.HmacNoAttestation
2730 *
2731 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2732 * and app id are provided.
2733 */
TEST_P(NewKeyGenerationTest,HmacNoAttestation)2734 TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2735 auto challenge = "hello";
2736 auto app_id = "foo";
2737
2738 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2739 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2740 vector<uint8_t> key_blob;
2741 vector<KeyCharacteristics> key_characteristics;
2742 constexpr size_t key_size = 128;
2743 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2744 .HmacKey(key_size)
2745 .Digest(digest)
2746 .AttestationChallenge(challenge)
2747 .AttestationApplicationId(app_id)
2748 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2749 &key_blob, &key_characteristics));
2750
2751 ASSERT_GT(key_blob.size(), 0U);
2752 ASSERT_EQ(cert_chain_.size(), 0);
2753 CheckBaseParams(key_characteristics);
2754 CheckCharacteristics(key_blob, key_characteristics);
2755
2756 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2757 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2758 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2759 << "Key size " << key_size << "missing";
2760
2761 CheckedDeleteKey(&key_blob);
2762 }
2763 }
2764
2765 /*
2766 * NewKeyGenerationTest.LimitedUsageHmac
2767 *
2768 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2769 * resulting keys have correct characteristics.
2770 */
TEST_P(NewKeyGenerationTest,LimitedUsageHmac)2771 TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2772 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2773 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2774 vector<uint8_t> key_blob;
2775 vector<KeyCharacteristics> key_characteristics;
2776 constexpr size_t key_size = 128;
2777 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2778 .HmacKey(key_size)
2779 .Digest(digest)
2780 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2781 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2782 &key_blob, &key_characteristics));
2783
2784 ASSERT_GT(key_blob.size(), 0U);
2785 CheckBaseParams(key_characteristics);
2786 CheckCharacteristics(key_blob, key_characteristics);
2787
2788 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2789 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2790 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2791 << "Key size " << key_size << "missing";
2792
2793 // Check the usage count limit tag appears in the authorizations.
2794 AuthorizationSet auths;
2795 for (auto& entry : key_characteristics) {
2796 auths.push_back(AuthorizationSet(entry.authorizations));
2797 }
2798 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2799 << "key usage count limit " << 1U << " missing";
2800
2801 CheckedDeleteKey(&key_blob);
2802 }
2803 }
2804
2805 /*
2806 * NewKeyGenerationTest.HmacCheckKeySizes
2807 *
2808 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2809 */
TEST_P(NewKeyGenerationTest,HmacCheckKeySizes)2810 TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2811 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2812 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
2813 if (key_size < 64 || key_size % 8 != 0) {
2814 // To keep this test from being very slow, we only test a random fraction of
2815 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2816 // them, we expect to run ~40 of them in each run.
2817 if (key_size % 8 == 0 || random() % 10 == 0) {
2818 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2819 GenerateKey(AuthorizationSetBuilder()
2820 .HmacKey(key_size)
2821 .Digest(Digest::SHA_2_256)
2822 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2823 << "HMAC key size " << key_size << " invalid";
2824 }
2825 } else {
2826 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2827 .HmacKey(key_size)
2828 .Digest(Digest::SHA_2_256)
2829 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2830 << "Failed to generate HMAC key of size " << key_size;
2831 CheckedDeleteKey();
2832 }
2833 }
2834 if (SecLevel() == SecurityLevel::STRONGBOX) {
2835 // STRONGBOX devices must not support keys larger than 512 bits.
2836 size_t key_size = 520;
2837 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2838 GenerateKey(AuthorizationSetBuilder()
2839 .HmacKey(key_size)
2840 .Digest(Digest::SHA_2_256)
2841 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2842 << "HMAC key size " << key_size << " unexpectedly valid";
2843 }
2844 }
2845
2846 /*
2847 * NewKeyGenerationTest.HmacCheckMinMacLengths
2848 *
2849 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2850 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2851 * specific MAC length that failed, so reproducing a failed run will be easy.
2852 */
TEST_P(NewKeyGenerationTest,HmacCheckMinMacLengths)2853 TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2854 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2855 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
2856 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2857 // To keep this test from being very long, we only test a random fraction of
2858 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2859 // we expect to run ~17 of them in each run.
2860 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2861 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2862 GenerateKey(AuthorizationSetBuilder()
2863 .HmacKey(128)
2864 .Digest(Digest::SHA_2_256)
2865 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2866 << "HMAC min mac length " << min_mac_length << " invalid.";
2867 }
2868 } else {
2869 EXPECT_EQ(ErrorCode::OK,
2870 GenerateKey(AuthorizationSetBuilder()
2871 .HmacKey(128)
2872 .Digest(Digest::SHA_2_256)
2873 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2874 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2875 CheckedDeleteKey();
2876 }
2877 }
2878
2879 // Minimum MAC length must be no more than 512 bits.
2880 size_t min_mac_length = 520;
2881 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2882 GenerateKey(AuthorizationSetBuilder()
2883 .HmacKey(128)
2884 .Digest(Digest::SHA_2_256)
2885 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2886 << "HMAC min mac length " << min_mac_length << " invalid.";
2887 }
2888
2889 /*
2890 * NewKeyGenerationTest.HmacMultipleDigests
2891 *
2892 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2893 */
TEST_P(NewKeyGenerationTest,HmacMultipleDigests)2894 TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
2895 if (SecLevel() == SecurityLevel::STRONGBOX) {
2896 GTEST_SKIP() << "Test not applicable to StrongBox device";
2897 }
2898
2899 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2900 GenerateKey(AuthorizationSetBuilder()
2901 .HmacKey(128)
2902 .Digest(Digest::SHA1)
2903 .Digest(Digest::SHA_2_256)
2904 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2905 }
2906
2907 /*
2908 * NewKeyGenerationTest.HmacDigestNone
2909 *
2910 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2911 */
TEST_P(NewKeyGenerationTest,HmacDigestNone)2912 TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2913 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2914 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2915 128)));
2916
2917 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2918 GenerateKey(AuthorizationSetBuilder()
2919 .HmacKey(128)
2920 .Digest(Digest::NONE)
2921 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2922 }
2923
2924 /*
2925 * NewKeyGenerationTest.AesNoAttestation
2926 *
2927 * Verifies that attestation parameters to AES keys are ignored and generateKey
2928 * will succeed.
2929 */
TEST_P(NewKeyGenerationTest,AesNoAttestation)2930 TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2931 auto challenge = "hello";
2932 auto app_id = "foo";
2933
2934 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2935 .Authorization(TAG_NO_AUTH_REQUIRED)
2936 .AesEncryptionKey(128)
2937 .EcbMode()
2938 .Padding(PaddingMode::PKCS7)
2939 .AttestationChallenge(challenge)
2940 .AttestationApplicationId(app_id)));
2941
2942 ASSERT_EQ(cert_chain_.size(), 0);
2943 }
2944
2945 /*
2946 * NewKeyGenerationTest.TripleDesNoAttestation
2947 *
2948 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2949 * will be successful. No attestation should be generated.
2950 */
TEST_P(NewKeyGenerationTest,TripleDesNoAttestation)2951 TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2952 auto challenge = "hello";
2953 auto app_id = "foo";
2954
2955 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2956 .TripleDesEncryptionKey(168)
2957 .BlockMode(BlockMode::ECB)
2958 .Authorization(TAG_NO_AUTH_REQUIRED)
2959 .Padding(PaddingMode::NONE)
2960 .AttestationChallenge(challenge)
2961 .AttestationApplicationId(app_id)));
2962 ASSERT_EQ(cert_chain_.size(), 0);
2963 }
2964
2965 INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2966
2967 typedef KeyMintAidlTestBase SigningOperationsTest;
2968
2969 /*
2970 * SigningOperationsTest.RsaSuccess
2971 *
2972 * Verifies that raw RSA signature operations succeed.
2973 */
TEST_P(SigningOperationsTest,RsaSuccess)2974 TEST_P(SigningOperationsTest, RsaSuccess) {
2975 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2976 .RsaSigningKey(2048, 65537)
2977 .Digest(Digest::NONE)
2978 .Padding(PaddingMode::NONE)
2979 .Authorization(TAG_NO_AUTH_REQUIRED)
2980 .SetDefaultValidity()));
2981 string message = "12345678901234567890123456789012";
2982 string signature = SignMessage(
2983 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2984 LocalVerifyMessage(message, signature,
2985 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2986 }
2987
2988 /*
2989 * SigningOperationsTest.RsaAllPaddingsAndDigests
2990 *
2991 * Verifies RSA signature/verification for all padding modes and digests.
2992 */
TEST_P(SigningOperationsTest,RsaAllPaddingsAndDigests)2993 TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2994 auto authorizations = AuthorizationSetBuilder()
2995 .Authorization(TAG_NO_AUTH_REQUIRED)
2996 .RsaSigningKey(2048, 65537)
2997 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2998 .Padding(PaddingMode::NONE)
2999 .Padding(PaddingMode::RSA_PSS)
3000 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3001 .SetDefaultValidity();
3002
3003 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
3004
3005 string message(128, 'a');
3006 string corrupt_message(message);
3007 ++corrupt_message[corrupt_message.size() / 2];
3008
3009 for (auto padding :
3010 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
3011 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
3012 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
3013 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
3014 // Digesting only makes sense with padding.
3015 continue;
3016 }
3017
3018 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
3019 // PSS requires digesting.
3020 continue;
3021 }
3022
3023 string signature =
3024 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
3025 LocalVerifyMessage(message, signature,
3026 AuthorizationSetBuilder().Digest(digest).Padding(padding));
3027 }
3028 }
3029 }
3030
3031 /*
3032 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
3033 *
3034 * Verifies that using an RSA key requires the correct app data.
3035 */
TEST_P(SigningOperationsTest,RsaUseRequiresCorrectAppIdAppData)3036 TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
3037 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3038 .Authorization(TAG_NO_AUTH_REQUIRED)
3039 .RsaSigningKey(2048, 65537)
3040 .Digest(Digest::NONE)
3041 .Padding(PaddingMode::NONE)
3042 .Authorization(TAG_APPLICATION_ID, "clientid")
3043 .Authorization(TAG_APPLICATION_DATA, "appdata")
3044 .SetDefaultValidity()));
3045
3046 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3047
3048 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3049 Begin(KeyPurpose::SIGN,
3050 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3051 AbortIfNeeded();
3052 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3053 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3054 .Digest(Digest::NONE)
3055 .Padding(PaddingMode::NONE)
3056 .Authorization(TAG_APPLICATION_ID, "clientid")));
3057 AbortIfNeeded();
3058 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3059 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3060 .Digest(Digest::NONE)
3061 .Padding(PaddingMode::NONE)
3062 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3063 AbortIfNeeded();
3064 EXPECT_EQ(ErrorCode::OK,
3065 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3066 .Digest(Digest::NONE)
3067 .Padding(PaddingMode::NONE)
3068 .Authorization(TAG_APPLICATION_DATA, "appdata")
3069 .Authorization(TAG_APPLICATION_ID, "clientid")));
3070 AbortIfNeeded();
3071 }
3072
3073 /*
3074 * SigningOperationsTest.RsaPssSha256Success
3075 *
3076 * Verifies that RSA-PSS signature operations succeed.
3077 */
TEST_P(SigningOperationsTest,RsaPssSha256Success)3078 TEST_P(SigningOperationsTest, RsaPssSha256Success) {
3079 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3080 .RsaSigningKey(2048, 65537)
3081 .Digest(Digest::SHA_2_256)
3082 .Padding(PaddingMode::RSA_PSS)
3083 .Authorization(TAG_NO_AUTH_REQUIRED)
3084 .SetDefaultValidity()));
3085 // Use large message, which won't work without digesting.
3086 string message(1024, 'a');
3087 string signature = SignMessage(
3088 message,
3089 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
3090 }
3091
3092 /*
3093 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
3094 *
3095 * Verifies that keymint rejects signature operations that specify a padding mode when the key
3096 * supports only unpadded operations.
3097 */
TEST_P(SigningOperationsTest,RsaPaddingNoneDoesNotAllowOther)3098 TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
3099 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3100 .RsaSigningKey(2048, 65537)
3101 .Digest(Digest::NONE)
3102 .Authorization(TAG_NO_AUTH_REQUIRED)
3103 .Padding(PaddingMode::NONE)
3104 .SetDefaultValidity()));
3105 string message = "12345678901234567890123456789012";
3106 string signature;
3107
3108 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3109 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3110 .Digest(Digest::NONE)
3111 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3112 }
3113
3114 /*
3115 * SigningOperationsTest.NoUserConfirmation
3116 *
3117 * Verifies that keymint rejects signing operations for keys with
3118 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
3119 * presented.
3120 */
TEST_P(SigningOperationsTest,NoUserConfirmation)3121 TEST_P(SigningOperationsTest, NoUserConfirmation) {
3122 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3123 .RsaSigningKey(2048, 65537)
3124 .Digest(Digest::NONE)
3125 .Padding(PaddingMode::NONE)
3126 .Authorization(TAG_NO_AUTH_REQUIRED)
3127 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
3128 .SetDefaultValidity()));
3129
3130 const string message = "12345678901234567890123456789012";
3131 EXPECT_EQ(ErrorCode::OK,
3132 Begin(KeyPurpose::SIGN,
3133 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3134 string signature;
3135 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
3136 }
3137
3138 /*
3139 * SigningOperationsTest.RsaPkcs1Sha256Success
3140 *
3141 * Verifies that digested RSA-PKCS1 signature operations succeed.
3142 */
TEST_P(SigningOperationsTest,RsaPkcs1Sha256Success)3143 TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3144 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3145 .RsaSigningKey(2048, 65537)
3146 .Digest(Digest::SHA_2_256)
3147 .Authorization(TAG_NO_AUTH_REQUIRED)
3148 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3149 .SetDefaultValidity()));
3150 string message(1024, 'a');
3151 string signature = SignMessage(message, AuthorizationSetBuilder()
3152 .Digest(Digest::SHA_2_256)
3153 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3154 }
3155
3156 /*
3157 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3158 *
3159 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3160 */
TEST_P(SigningOperationsTest,RsaPkcs1NoDigestSuccess)3161 TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3162 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3163 .RsaSigningKey(2048, 65537)
3164 .Digest(Digest::NONE)
3165 .Authorization(TAG_NO_AUTH_REQUIRED)
3166 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3167 .SetDefaultValidity()));
3168 string message(53, 'a');
3169 string signature = SignMessage(message, AuthorizationSetBuilder()
3170 .Digest(Digest::NONE)
3171 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3172 }
3173
3174 /*
3175 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3176 *
3177 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3178 * given a too-long message.
3179 */
TEST_P(SigningOperationsTest,RsaPkcs1NoDigestTooLong)3180 TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3181 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3182 .RsaSigningKey(2048, 65537)
3183 .Digest(Digest::NONE)
3184 .Authorization(TAG_NO_AUTH_REQUIRED)
3185 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3186 .SetDefaultValidity()));
3187 string message(257, 'a');
3188
3189 EXPECT_EQ(ErrorCode::OK,
3190 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3191 .Digest(Digest::NONE)
3192 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3193 string signature;
3194 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3195 }
3196
3197 /*
3198 * SigningOperationsTest.RsaPssSha512TooSmallKey
3199 *
3200 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3201 * used with a key that is too small for the message.
3202 *
3203 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3204 * keymint specification requires that salt_size == digest_size, so the message will be
3205 * digest_size * 2 +
3206 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3207 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3208 * for a 1024-bit key.
3209 */
TEST_P(SigningOperationsTest,RsaPssSha512TooSmallKey)3210 TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
3211 if (SecLevel() == SecurityLevel::STRONGBOX) {
3212 GTEST_SKIP() << "Test not applicable to StrongBox device";
3213 }
3214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3215 .RsaSigningKey(1024, 65537)
3216 .Digest(Digest::SHA_2_512)
3217 .Authorization(TAG_NO_AUTH_REQUIRED)
3218 .Padding(PaddingMode::RSA_PSS)
3219 .SetDefaultValidity()));
3220 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3221 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3222 .Digest(Digest::SHA_2_512)
3223 .Padding(PaddingMode::RSA_PSS)));
3224 }
3225
3226 /*
3227 * SigningOperationsTest.RsaNoPaddingTooLong
3228 *
3229 * Verifies that raw RSA signature operations fail with the correct error code when
3230 * given a too-long message.
3231 */
TEST_P(SigningOperationsTest,RsaNoPaddingTooLong)3232 TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3233 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3234 .RsaSigningKey(2048, 65537)
3235 .Digest(Digest::NONE)
3236 .Authorization(TAG_NO_AUTH_REQUIRED)
3237 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3238 .SetDefaultValidity()));
3239 // One byte too long
3240 string message(2048 / 8 + 1, 'a');
3241 ASSERT_EQ(ErrorCode::OK,
3242 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3243 .Digest(Digest::NONE)
3244 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3245 string result;
3246 ErrorCode finish_error_code = Finish(message, &result);
3247 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3248 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3249
3250 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3251 message = string(128 * 1024, 'a');
3252 ASSERT_EQ(ErrorCode::OK,
3253 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3254 .Digest(Digest::NONE)
3255 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3256 finish_error_code = Finish(message, &result);
3257 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3258 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3259 }
3260
3261 /*
3262 * SigningOperationsTest.RsaAbort
3263 *
3264 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3265 * test, but the behavior should be algorithm and purpose-independent.
3266 */
TEST_P(SigningOperationsTest,RsaAbort)3267 TEST_P(SigningOperationsTest, RsaAbort) {
3268 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3269 .RsaSigningKey(2048, 65537)
3270 .Digest(Digest::NONE)
3271 .Authorization(TAG_NO_AUTH_REQUIRED)
3272 .Padding(PaddingMode::NONE)
3273 .SetDefaultValidity()));
3274
3275 ASSERT_EQ(ErrorCode::OK,
3276 Begin(KeyPurpose::SIGN,
3277 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3278 EXPECT_EQ(ErrorCode::OK, Abort());
3279
3280 // Another abort should fail
3281 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3282
3283 // Set to sentinel, so TearDown() doesn't try to abort again.
3284 op_.reset();
3285 }
3286
3287 /*
3288 * SigningOperationsTest.RsaNonUniqueParams
3289 *
3290 * Verifies that an operation with multiple padding modes is rejected.
3291 */
TEST_P(SigningOperationsTest,RsaNonUniqueParams)3292 TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3293 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3294 .RsaSigningKey(2048, 65537)
3295 .Digest(Digest::NONE)
3296 .Digest(Digest::SHA1)
3297 .Authorization(TAG_NO_AUTH_REQUIRED)
3298 .Padding(PaddingMode::NONE)
3299 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3300 .SetDefaultValidity()));
3301
3302 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3303 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3304 .Digest(Digest::NONE)
3305 .Padding(PaddingMode::NONE)
3306 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3307
3308 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3309 .Digest(Digest::NONE)
3310 .Digest(Digest::SHA1)
3311 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3312 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
3313
3314 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3315 Begin(KeyPurpose::SIGN,
3316 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3317 }
3318
3319 /*
3320 * SigningOperationsTest.RsaUnsupportedPadding
3321 *
3322 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3323 * with a padding mode inappropriate for RSA.
3324 */
TEST_P(SigningOperationsTest,RsaUnsupportedPadding)3325 TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3326 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3327 .RsaSigningKey(2048, 65537)
3328 .Authorization(TAG_NO_AUTH_REQUIRED)
3329 .Digest(Digest::SHA_2_256 /* supported digest */)
3330 .Padding(PaddingMode::PKCS7)
3331 .SetDefaultValidity()));
3332 ASSERT_EQ(
3333 ErrorCode::UNSUPPORTED_PADDING_MODE,
3334 Begin(KeyPurpose::SIGN,
3335 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
3336 CheckedDeleteKey();
3337
3338 ASSERT_EQ(ErrorCode::OK,
3339 GenerateKey(
3340 AuthorizationSetBuilder()
3341 .RsaSigningKey(2048, 65537)
3342 .Authorization(TAG_NO_AUTH_REQUIRED)
3343 .Digest(Digest::SHA_2_256 /* supported digest */)
3344 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3345 .SetDefaultValidity()));
3346 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3347 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3348 .Digest(Digest::SHA_2_256)
3349 .Padding(PaddingMode::RSA_OAEP)));
3350 }
3351
3352 /*
3353 * SigningOperationsTest.RsaPssNoDigest
3354 *
3355 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3356 */
TEST_P(SigningOperationsTest,RsaNoDigest)3357 TEST_P(SigningOperationsTest, RsaNoDigest) {
3358 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3359 .RsaSigningKey(2048, 65537)
3360 .Authorization(TAG_NO_AUTH_REQUIRED)
3361 .Digest(Digest::NONE)
3362 .Padding(PaddingMode::RSA_PSS)
3363 .SetDefaultValidity()));
3364 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3365 Begin(KeyPurpose::SIGN,
3366 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3367
3368 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3369 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3370 }
3371
3372 /*
3373 * SigningOperationsTest.RsaPssNoPadding
3374 *
3375 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3376 * supported in some cases (as validated in other tests), but a mode must be specified.
3377 */
TEST_P(SigningOperationsTest,RsaNoPadding)3378 TEST_P(SigningOperationsTest, RsaNoPadding) {
3379 // Padding must be specified
3380 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3381 .RsaKey(2048, 65537)
3382 .Authorization(TAG_NO_AUTH_REQUIRED)
3383 .SigningKey()
3384 .Digest(Digest::NONE)
3385 .SetDefaultValidity()));
3386 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3387 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3388 }
3389
3390 /*
3391 * SigningOperationsTest.RsaShortMessage
3392 *
3393 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3394 */
TEST_P(SigningOperationsTest,RsaTooShortMessage)3395 TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3396 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3397 .Authorization(TAG_NO_AUTH_REQUIRED)
3398 .RsaSigningKey(2048, 65537)
3399 .Digest(Digest::NONE)
3400 .Padding(PaddingMode::NONE)
3401 .SetDefaultValidity()));
3402
3403 // Barely shorter
3404 string message(2048 / 8 - 1, 'a');
3405 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3406
3407 // Much shorter
3408 message = "a";
3409 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3410 }
3411
3412 /*
3413 * SigningOperationsTest.RsaSignWithEncryptionKey
3414 *
3415 * Verifies that RSA encryption keys cannot be used to sign.
3416 */
TEST_P(SigningOperationsTest,RsaSignWithEncryptionKey)3417 TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3418 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3419 .Authorization(TAG_NO_AUTH_REQUIRED)
3420 .RsaEncryptionKey(2048, 65537)
3421 .Digest(Digest::NONE)
3422 .Padding(PaddingMode::NONE)
3423 .SetDefaultValidity()));
3424 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3425 Begin(KeyPurpose::SIGN,
3426 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3427 }
3428
3429 /*
3430 * SigningOperationsTest.RsaSignTooLargeMessage
3431 *
3432 * Verifies that attempting a raw signature of a message which is the same length as the key,
3433 * but numerically larger than the public modulus, fails with the correct error.
3434 */
TEST_P(SigningOperationsTest,RsaSignTooLargeMessage)3435 TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3436 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3437 .Authorization(TAG_NO_AUTH_REQUIRED)
3438 .RsaSigningKey(2048, 65537)
3439 .Digest(Digest::NONE)
3440 .Padding(PaddingMode::NONE)
3441 .SetDefaultValidity()));
3442
3443 // Largest possible message will always be larger than the public modulus.
3444 string message(2048 / 8, static_cast<char>(0xff));
3445 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3446 .Authorization(TAG_NO_AUTH_REQUIRED)
3447 .Digest(Digest::NONE)
3448 .Padding(PaddingMode::NONE)));
3449 string signature;
3450 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3451 }
3452
3453 /*
3454 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3455 *
3456 * Verifies ECDSA signature/verification for all digests and required curves.
3457 */
TEST_P(SigningOperationsTest,EcdsaAllDigestsAndCurves)3458 TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
3459
3460 string message = "1234567890";
3461 string corrupt_message = "2234567890";
3462 for (auto curve : ValidCurves()) {
3463 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
3464 // Ed25519 only allows Digest::NONE.
3465 auto digests = (curve == EcCurve::CURVE_25519)
3466 ? std::vector<Digest>(1, Digest::NONE)
3467 : ValidDigests(true /* withNone */, false /* withMD5 */);
3468
3469 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3470 .Authorization(TAG_NO_AUTH_REQUIRED)
3471 .EcdsaSigningKey(curve)
3472 .Digest(digests)
3473 .SetDefaultValidity());
3474 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3475 if (error != ErrorCode::OK) {
3476 continue;
3477 }
3478
3479 for (auto digest : digests) {
3480 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3481 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3482 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3483 }
3484
3485 auto rc = DeleteKey();
3486 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3487 }
3488 }
3489
3490 /*
3491 * SigningOperationsTest.EcdsaAllCurves
3492 *
3493 * Verifies that ECDSA operations succeed with all required curves.
3494 */
TEST_P(SigningOperationsTest,EcdsaAllCurves)3495 TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3496 for (auto curve : ValidCurves()) {
3497 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3498 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
3499 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3500 .Authorization(TAG_NO_AUTH_REQUIRED)
3501 .EcdsaSigningKey(curve)
3502 .Digest(digest)
3503 .SetDefaultValidity());
3504 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3505 if (error != ErrorCode::OK) continue;
3506
3507 string message(1024, 'a');
3508 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3509 CheckedDeleteKey();
3510 }
3511 }
3512
3513 /*
3514 * SigningOperationsTest.EcdsaCurve25519
3515 *
3516 * Verifies that ECDSA operations succeed with curve25519.
3517 */
TEST_P(SigningOperationsTest,EcdsaCurve25519)3518 TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3519 if (!Curve25519Supported()) {
3520 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3521 }
3522
3523 EcCurve curve = EcCurve::CURVE_25519;
3524 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3525 .Authorization(TAG_NO_AUTH_REQUIRED)
3526 .EcdsaSigningKey(curve)
3527 .Digest(Digest::NONE)
3528 .SetDefaultValidity());
3529 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3530
3531 string message(1024, 'a');
3532 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3533 CheckedDeleteKey();
3534 }
3535
3536 /*
3537 * SigningOperationsTest.EcdsaCurve25519MaxSize
3538 *
3539 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3540 */
TEST_P(SigningOperationsTest,EcdsaCurve25519MaxSize)3541 TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3542 if (!Curve25519Supported()) {
3543 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3544 }
3545
3546 EcCurve curve = EcCurve::CURVE_25519;
3547 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3548 .Authorization(TAG_NO_AUTH_REQUIRED)
3549 .EcdsaSigningKey(curve)
3550 .Digest(Digest::NONE)
3551 .SetDefaultValidity());
3552 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3553
3554 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3555
3556 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3557 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3558 string message(msg_size, 'a');
3559
3560 // Attempt to sign via Begin+Finish.
3561 AuthorizationSet out_params;
3562 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3563 EXPECT_TRUE(out_params.empty());
3564 string signature;
3565 auto result = Finish(message, &signature);
3566 EXPECT_EQ(result, ErrorCode::OK);
3567 LocalVerifyMessage(message, signature, params);
3568
3569 // Attempt to sign via Begin+Update+Finish
3570 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3571 EXPECT_TRUE(out_params.empty());
3572 string output;
3573 result = Update(message, &output);
3574 EXPECT_EQ(result, ErrorCode::OK);
3575 EXPECT_EQ(output.size(), 0);
3576 string signature2;
3577 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3578 LocalVerifyMessage(message, signature2, params);
3579 }
3580
3581 CheckedDeleteKey();
3582 }
3583
3584 /*
3585 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3586 *
3587 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3588 */
TEST_P(SigningOperationsTest,EcdsaCurve25519MaxSizeFail)3589 TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3590 if (!Curve25519Supported()) {
3591 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3592 }
3593
3594 EcCurve curve = EcCurve::CURVE_25519;
3595 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3596 .Authorization(TAG_NO_AUTH_REQUIRED)
3597 .EcdsaSigningKey(curve)
3598 .Digest(Digest::NONE)
3599 .SetDefaultValidity());
3600 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3601
3602 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3603
3604 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3605 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3606 string message(msg_size, 'a');
3607
3608 // Attempt to sign via Begin+Finish.
3609 AuthorizationSet out_params;
3610 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3611 EXPECT_TRUE(out_params.empty());
3612 string signature;
3613 auto result = Finish(message, &signature);
3614 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3615
3616 // Attempt to sign via Begin+Update (but never get to Finish)
3617 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3618 EXPECT_TRUE(out_params.empty());
3619 string output;
3620 result = Update(message, &output);
3621 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3622 }
3623
3624 CheckedDeleteKey();
3625 }
3626
3627 /*
3628 * SigningOperationsTest.EcdsaNoDigestHugeData
3629 *
3630 * Verifies that ECDSA operations support very large messages, even without digesting. This
3631 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3632 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3633 * the framework.
3634 */
TEST_P(SigningOperationsTest,EcdsaNoDigestHugeData)3635 TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3636 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3637 .Authorization(TAG_NO_AUTH_REQUIRED)
3638 .EcdsaSigningKey(EcCurve::P_256)
3639 .Digest(Digest::NONE)
3640 .SetDefaultValidity()));
3641 string message(1 * 1024, 'a');
3642 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3643 }
3644
3645 /*
3646 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3647 *
3648 * Verifies that using an EC key requires the correct app ID/data.
3649 */
TEST_P(SigningOperationsTest,EcUseRequiresCorrectAppIdAppData)3650 TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3651 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3652 .Authorization(TAG_NO_AUTH_REQUIRED)
3653 .EcdsaSigningKey(EcCurve::P_256)
3654 .Digest(Digest::NONE)
3655 .Authorization(TAG_APPLICATION_ID, "clientid")
3656 .Authorization(TAG_APPLICATION_DATA, "appdata")
3657 .SetDefaultValidity()));
3658
3659 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3660
3661 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3662 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3663 AbortIfNeeded();
3664 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3665 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3666 .Digest(Digest::NONE)
3667 .Authorization(TAG_APPLICATION_ID, "clientid")));
3668 AbortIfNeeded();
3669 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3670 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3671 .Digest(Digest::NONE)
3672 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3673 AbortIfNeeded();
3674 EXPECT_EQ(ErrorCode::OK,
3675 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3676 .Digest(Digest::NONE)
3677 .Authorization(TAG_APPLICATION_DATA, "appdata")
3678 .Authorization(TAG_APPLICATION_ID, "clientid")));
3679 AbortIfNeeded();
3680 }
3681
3682 /*
3683 * SigningOperationsTest.EcdsaIncompatibleDigest
3684 *
3685 * Verifies that using an EC key requires compatible digest.
3686 */
TEST_P(SigningOperationsTest,EcdsaIncompatibleDigest)3687 TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3688 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3689 .Authorization(TAG_NO_AUTH_REQUIRED)
3690 .EcdsaSigningKey(EcCurve::P_256)
3691 .Digest(Digest::NONE)
3692 .Digest(Digest::SHA1)
3693 .SetDefaultValidity()));
3694 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3695 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3696 AbortIfNeeded();
3697 }
3698
3699 /*
3700 * SigningOperationsTest.AesEcbSign
3701 *
3702 * Verifies that attempts to use AES keys to sign fail in the correct way.
3703 */
TEST_P(SigningOperationsTest,AesEcbSign)3704 TEST_P(SigningOperationsTest, AesEcbSign) {
3705 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3706 .Authorization(TAG_NO_AUTH_REQUIRED)
3707 .SigningKey()
3708 .AesEncryptionKey(128)
3709 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3710
3711 AuthorizationSet out_params;
3712 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3713 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3714 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3715 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3716 }
3717
3718 /*
3719 * SigningOperationsTest.HmacAllDigests
3720 *
3721 * Verifies that HMAC works with all digests.
3722 */
TEST_P(SigningOperationsTest,HmacAllDigests)3723 TEST_P(SigningOperationsTest, HmacAllDigests) {
3724 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
3725 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3726 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3727 .Authorization(TAG_NO_AUTH_REQUIRED)
3728 .HmacKey(128)
3729 .Digest(digest)
3730 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3731 << "Failed to create HMAC key with digest " << digest;
3732 string message = "12345678901234567890123456789012";
3733 string signature = MacMessage(message, digest, 160);
3734 EXPECT_EQ(160U / 8U, signature.size())
3735 << "Failed to sign with HMAC key with digest " << digest;
3736 CheckedDeleteKey();
3737 }
3738 }
3739
3740 /*
3741 * SigningOperationsTest.HmacSha256TooLargeMacLength
3742 *
3743 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3744 * digest size.
3745 */
TEST_P(SigningOperationsTest,HmacSha256TooLargeMacLength)3746 TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3747 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3748 .Authorization(TAG_NO_AUTH_REQUIRED)
3749 .HmacKey(128)
3750 .Digest(Digest::SHA_2_256)
3751 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3752 AuthorizationSet output_params;
3753 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3754 AuthorizationSetBuilder()
3755 .Digest(Digest::SHA_2_256)
3756 .Authorization(TAG_MAC_LENGTH, 264),
3757 &output_params));
3758 }
3759
3760 /*
3761 * SigningOperationsTest.HmacSha256InvalidMacLength
3762 *
3763 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3764 * not a multiple of 8.
3765 */
TEST_P(SigningOperationsTest,HmacSha256InvalidMacLength)3766 TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3767 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3768 .Authorization(TAG_NO_AUTH_REQUIRED)
3769 .HmacKey(128)
3770 .Digest(Digest::SHA_2_256)
3771 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3772 AuthorizationSet output_params;
3773 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3774 AuthorizationSetBuilder()
3775 .Digest(Digest::SHA_2_256)
3776 .Authorization(TAG_MAC_LENGTH, 161),
3777 &output_params));
3778 }
3779
3780 /*
3781 * SigningOperationsTest.HmacSha256TooSmallMacLength
3782 *
3783 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3784 * specified minimum MAC length.
3785 */
TEST_P(SigningOperationsTest,HmacSha256TooSmallMacLength)3786 TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3787 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3788 .Authorization(TAG_NO_AUTH_REQUIRED)
3789 .HmacKey(128)
3790 .Digest(Digest::SHA_2_256)
3791 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3792 AuthorizationSet output_params;
3793 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3794 AuthorizationSetBuilder()
3795 .Digest(Digest::SHA_2_256)
3796 .Authorization(TAG_MAC_LENGTH, 120),
3797 &output_params));
3798 }
3799
3800 /*
3801 * SigningOperationsTest.HmacRfc4231TestCase3
3802 *
3803 * Validates against the test vectors from RFC 4231 test case 3.
3804 */
TEST_P(SigningOperationsTest,HmacRfc4231TestCase3)3805 TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3806 string key(20, 0xaa);
3807 string message(50, 0xdd);
3808 uint8_t sha_224_expected[] = {
3809 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3810 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3811 };
3812 uint8_t sha_256_expected[] = {
3813 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3814 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3815 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3816 };
3817 uint8_t sha_384_expected[] = {
3818 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3819 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3820 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3821 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3822 };
3823 uint8_t sha_512_expected[] = {
3824 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3825 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3826 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3827 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3828 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3829 };
3830
3831 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3832 if (SecLevel() != SecurityLevel::STRONGBOX) {
3833 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3834 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3835 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3836 }
3837 }
3838
3839 /*
3840 * SigningOperationsTest.HmacRfc4231TestCase5
3841 *
3842 * Validates against the test vectors from RFC 4231 test case 5.
3843 */
TEST_P(SigningOperationsTest,HmacRfc4231TestCase5)3844 TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3845 string key(20, 0x0c);
3846 string message = "Test With Truncation";
3847
3848 uint8_t sha_224_expected[] = {
3849 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3850 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3851 };
3852 uint8_t sha_256_expected[] = {
3853 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3854 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3855 };
3856 uint8_t sha_384_expected[] = {
3857 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3858 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3859 };
3860 uint8_t sha_512_expected[] = {
3861 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3862 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3863 };
3864
3865 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3866 if (SecLevel() != SecurityLevel::STRONGBOX) {
3867 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3868 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3869 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3870 }
3871 }
3872
3873 INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3874
3875 typedef KeyMintAidlTestBase VerificationOperationsTest;
3876
3877 /*
3878 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3879 *
3880 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3881 */
TEST_P(VerificationOperationsTest,HmacSigningKeyCannotVerify)3882 TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3883 string key_material = "HelloThisIsAKey";
3884
3885 vector<uint8_t> signing_key, verification_key;
3886 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3887 EXPECT_EQ(ErrorCode::OK,
3888 ImportKey(AuthorizationSetBuilder()
3889 .Authorization(TAG_NO_AUTH_REQUIRED)
3890 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3891 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3892 .Digest(Digest::SHA_2_256)
3893 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3894 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3895 EXPECT_EQ(ErrorCode::OK,
3896 ImportKey(AuthorizationSetBuilder()
3897 .Authorization(TAG_NO_AUTH_REQUIRED)
3898 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3899 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3900 .Digest(Digest::SHA_2_256)
3901 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3902 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3903
3904 string message = "This is a message.";
3905 string signature = SignMessage(
3906 signing_key, message,
3907 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3908
3909 // Signing key should not work.
3910 AuthorizationSet out_params;
3911 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3912 Begin(KeyPurpose::VERIFY, signing_key,
3913 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3914
3915 // Verification key should work.
3916 VerifyMessage(verification_key, message, signature,
3917 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3918
3919 CheckedDeleteKey(&signing_key);
3920 CheckedDeleteKey(&verification_key);
3921 }
3922
3923 /*
3924 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3925 *
3926 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3927 */
TEST_P(VerificationOperationsTest,HmacVerificationFailsForCorruptSignature)3928 TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3929 string key_material = "HelloThisIsAKey";
3930
3931 vector<uint8_t> signing_key, verification_key;
3932 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3933 EXPECT_EQ(ErrorCode::OK,
3934 ImportKey(AuthorizationSetBuilder()
3935 .Authorization(TAG_NO_AUTH_REQUIRED)
3936 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3937 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3938 .Digest(Digest::SHA_2_256)
3939 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3940 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3941 EXPECT_EQ(ErrorCode::OK,
3942 ImportKey(AuthorizationSetBuilder()
3943 .Authorization(TAG_NO_AUTH_REQUIRED)
3944 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3945 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3946 .Digest(Digest::SHA_2_256)
3947 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3948 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3949
3950 string message = "This is a message.";
3951 string signature = SignMessage(
3952 signing_key, message,
3953 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3954
3955 AuthorizationSet begin_out_params;
3956 ASSERT_EQ(ErrorCode::OK,
3957 Begin(KeyPurpose::VERIFY, verification_key,
3958 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3959
3960 string corruptMessage = "This is b message."; // Corrupted message
3961 string output;
3962 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3963
3964 ASSERT_EQ(ErrorCode::OK,
3965 Begin(KeyPurpose::VERIFY, verification_key,
3966 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3967
3968 signature[0] += 1; // Corrupt a signature
3969 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3970
3971 CheckedDeleteKey(&signing_key);
3972 CheckedDeleteKey(&verification_key);
3973 }
3974
3975 INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3976
3977 typedef KeyMintAidlTestBase ExportKeyTest;
3978
3979 /*
3980 * ExportKeyTest.RsaUnsupportedKeyFormat
3981 *
3982 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3983 */
3984 // TODO(seleneh) add ExportKey to GenerateKey
3985 // check result
3986
3987 class ImportKeyTest : public NewKeyGenerationTest {
3988 public:
3989 template <TagType tag_type, Tag tag, typename ValueT>
CheckCryptoParam(TypedTag<tag_type,tag> ttag,ValueT expected)3990 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3991 SCOPED_TRACE("CheckCryptoParam");
3992 for (auto& entry : key_characteristics_) {
3993 if (entry.securityLevel == SecLevel()) {
3994 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3995 << "Tag " << tag << " with value " << expected
3996 << " not found at security level" << entry.securityLevel;
3997 } else {
3998 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3999 << "Tag " << tag << " found at security level " << entry.securityLevel;
4000 }
4001 }
4002 }
4003
CheckOrigin()4004 void CheckOrigin() {
4005 SCOPED_TRACE("CheckOrigin");
4006 // Origin isn't a crypto param, but it always lives with them.
4007 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
4008 }
4009 };
4010
4011 /*
4012 * ImportKeyTest.RsaSuccess
4013 *
4014 * Verifies that importing and using an RSA key pair works correctly.
4015 */
TEST_P(ImportKeyTest,RsaSuccess)4016 TEST_P(ImportKeyTest, RsaSuccess) {
4017 uint32_t key_size;
4018 string key;
4019
4020 if (SecLevel() == SecurityLevel::STRONGBOX) {
4021 key_size = 2048;
4022 key = rsa_2048_key;
4023 } else {
4024 key_size = 1024;
4025 key = rsa_key;
4026 }
4027
4028 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4029 .Authorization(TAG_NO_AUTH_REQUIRED)
4030 .RsaSigningKey(key_size, 65537)
4031 .Digest(Digest::SHA_2_256)
4032 .Padding(PaddingMode::RSA_PSS)
4033 .SetDefaultValidity(),
4034 KeyFormat::PKCS8, key));
4035
4036 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4037 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4038 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4039 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4040 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4041 CheckOrigin();
4042
4043 string message(1024 / 8, 'a');
4044 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4045 string signature = SignMessage(message, params);
4046 LocalVerifyMessage(message, signature, params);
4047 }
4048
4049 /*
4050 * ImportKeyTest.RsaSuccessWithoutParams
4051 *
4052 * Verifies that importing and using an RSA key pair without specifying parameters
4053 * works correctly.
4054 */
TEST_P(ImportKeyTest,RsaSuccessWithoutParams)4055 TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
4056 uint32_t key_size;
4057 string key;
4058
4059 if (SecLevel() == SecurityLevel::STRONGBOX) {
4060 key_size = 2048;
4061 key = rsa_2048_key;
4062 } else {
4063 key_size = 1024;
4064 key = rsa_key;
4065 }
4066
4067 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4068 .Authorization(TAG_NO_AUTH_REQUIRED)
4069 .SigningKey()
4070 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
4071 .Digest(Digest::SHA_2_256)
4072 .Padding(PaddingMode::RSA_PSS)
4073 .SetDefaultValidity(),
4074 KeyFormat::PKCS8, key));
4075
4076 // Key size and public exponent are determined from the imported key material.
4077 CheckCryptoParam(TAG_KEY_SIZE, key_size);
4078 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
4079
4080 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
4081 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4082 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
4083 CheckOrigin();
4084
4085 string message(1024 / 8, 'a');
4086 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
4087 string signature = SignMessage(message, params);
4088 LocalVerifyMessage(message, signature, params);
4089 }
4090
4091 /*
4092 * ImportKeyTest.RsaKeySizeMismatch
4093 *
4094 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
4095 * correct way.
4096 */
TEST_P(ImportKeyTest,RsaKeySizeMismatch)4097 TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
4098 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4099 ImportKey(AuthorizationSetBuilder()
4100 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
4101 .Digest(Digest::NONE)
4102 .Padding(PaddingMode::NONE)
4103 .SetDefaultValidity(),
4104 KeyFormat::PKCS8, rsa_key));
4105 }
4106
4107 /*
4108 * ImportKeyTest.RsaPublicExponentMismatch
4109 *
4110 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
4111 * fails in the correct way.
4112 */
TEST_P(ImportKeyTest,RsaPublicExponentMismatch)4113 TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
4114 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4115 ImportKey(AuthorizationSetBuilder()
4116 .RsaSigningKey(1024, 3 /* Doesn't match key */)
4117 .Digest(Digest::NONE)
4118 .Padding(PaddingMode::NONE)
4119 .SetDefaultValidity(),
4120 KeyFormat::PKCS8, rsa_key));
4121 }
4122
4123 /*
4124 * ImportKeyTest.RsaAttestMultiPurposeFail
4125 *
4126 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
4127 */
TEST_P(ImportKeyTest,RsaAttestMultiPurposeFail)4128 TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
4129 if (AidlVersion() < 2) {
4130 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4131 // with other key purposes. However, this was not checked at the time
4132 // so we can only be strict about checking this for implementations of KeyMint
4133 // version 2 and above.
4134 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4135 }
4136 uint32_t key_size = 2048;
4137 string key = rsa_2048_key;
4138
4139 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4140 ImportKey(AuthorizationSetBuilder()
4141 .Authorization(TAG_NO_AUTH_REQUIRED)
4142 .RsaSigningKey(key_size, 65537)
4143 .AttestKey()
4144 .Digest(Digest::SHA_2_256)
4145 .Padding(PaddingMode::RSA_PSS)
4146 .SetDefaultValidity(),
4147 KeyFormat::PKCS8, key));
4148 }
4149
4150 /*
4151 * ImportKeyTest.EcdsaSuccess
4152 *
4153 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4154 */
TEST_P(ImportKeyTest,EcdsaSuccess)4155 TEST_P(ImportKeyTest, EcdsaSuccess) {
4156 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4157 .Authorization(TAG_NO_AUTH_REQUIRED)
4158 .EcdsaSigningKey(EcCurve::P_256)
4159 .Digest(Digest::SHA_2_256)
4160 .SetDefaultValidity(),
4161 KeyFormat::PKCS8, ec_256_key));
4162
4163 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4164 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4165 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4166
4167 CheckOrigin();
4168
4169 string message(32, 'a');
4170 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4171 string signature = SignMessage(message, params);
4172 LocalVerifyMessage(message, signature, params);
4173 }
4174
4175 /*
4176 * ImportKeyTest.EcdsaP256RFC5915Success
4177 *
4178 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4179 * correctly.
4180 */
TEST_P(ImportKeyTest,EcdsaP256RFC5915Success)4181 TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4182 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4183 .Authorization(TAG_NO_AUTH_REQUIRED)
4184 .EcdsaSigningKey(EcCurve::P_256)
4185 .Digest(Digest::SHA_2_256)
4186 .SetDefaultValidity(),
4187 KeyFormat::PKCS8, ec_256_key_rfc5915));
4188
4189 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4190 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4191 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4192
4193 CheckOrigin();
4194
4195 string message(32, 'a');
4196 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4197 string signature = SignMessage(message, params);
4198 LocalVerifyMessage(message, signature, params);
4199 }
4200
4201 /*
4202 * ImportKeyTest.EcdsaP256SEC1Success
4203 *
4204 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4205 */
TEST_P(ImportKeyTest,EcdsaP256SEC1Success)4206 TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4207 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4208 .Authorization(TAG_NO_AUTH_REQUIRED)
4209 .EcdsaSigningKey(EcCurve::P_256)
4210 .Digest(Digest::SHA_2_256)
4211 .SetDefaultValidity(),
4212 KeyFormat::PKCS8, ec_256_key_sec1));
4213
4214 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4215 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4216 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4217
4218 CheckOrigin();
4219
4220 string message(32, 'a');
4221 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4222 string signature = SignMessage(message, params);
4223 LocalVerifyMessage(message, signature, params);
4224 }
4225
4226 /*
4227 * ImportKeyTest.Ecdsa521Success
4228 *
4229 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4230 */
TEST_P(ImportKeyTest,Ecdsa521Success)4231 TEST_P(ImportKeyTest, Ecdsa521Success) {
4232 if (SecLevel() == SecurityLevel::STRONGBOX) {
4233 GTEST_SKIP() << "Test not applicable to StrongBox device";
4234 }
4235 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4236 .Authorization(TAG_NO_AUTH_REQUIRED)
4237 .EcdsaSigningKey(EcCurve::P_521)
4238 .Digest(Digest::SHA_2_256)
4239 .SetDefaultValidity(),
4240 KeyFormat::PKCS8, ec_521_key));
4241
4242 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4243 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4244 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4245 CheckOrigin();
4246
4247 string message(32, 'a');
4248 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4249 string signature = SignMessage(message, params);
4250 LocalVerifyMessage(message, signature, params);
4251 }
4252
4253 /*
4254 * ImportKeyTest.EcdsaCurveMismatch
4255 *
4256 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4257 * the correct way.
4258 */
TEST_P(ImportKeyTest,EcdsaCurveMismatch)4259 TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4260 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4261 ImportKey(AuthorizationSetBuilder()
4262 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4263 .Digest(Digest::NONE)
4264 .SetDefaultValidity(),
4265 KeyFormat::PKCS8, ec_256_key));
4266 }
4267
4268 /*
4269 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4270 *
4271 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4272 */
TEST_P(ImportKeyTest,EcdsaAttestMultiPurposeFail)4273 TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
4274 if (AidlVersion() < 2) {
4275 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4276 // with other key purposes. However, this was not checked at the time
4277 // so we can only be strict about checking this for implementations of KeyMint
4278 // version 2 and above.
4279 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4280 }
4281 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4282 ImportKey(AuthorizationSetBuilder()
4283 .Authorization(TAG_NO_AUTH_REQUIRED)
4284 .EcdsaSigningKey(EcCurve::P_256)
4285 .AttestKey()
4286 .Digest(Digest::SHA_2_256)
4287 .SetDefaultValidity(),
4288 KeyFormat::PKCS8, ec_256_key));
4289 }
4290
4291 /*
4292 * ImportKeyTest.Ed25519RawSuccess
4293 *
4294 * Verifies that importing and using a raw Ed25519 private key works correctly.
4295 */
TEST_P(ImportKeyTest,Ed25519RawSuccess)4296 TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4297 if (!Curve25519Supported()) {
4298 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4299 }
4300
4301 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4302 .Authorization(TAG_NO_AUTH_REQUIRED)
4303 .EcdsaSigningKey(EcCurve::CURVE_25519)
4304 .Digest(Digest::NONE)
4305 .SetDefaultValidity(),
4306 KeyFormat::RAW, ed25519_key));
4307 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4308 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4309 CheckOrigin();
4310
4311 // The returned cert should hold the correct public key.
4312 ASSERT_GT(cert_chain_.size(), 0);
4313 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4314 ASSERT_NE(kmKeyCert, nullptr);
4315 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4316 ASSERT_NE(kmPubKey.get(), nullptr);
4317 size_t kmPubKeySize = 32;
4318 uint8_t kmPubKeyData[32];
4319 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4320 ASSERT_EQ(kmPubKeySize, 32);
4321 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4322
4323 string message(32, 'a');
4324 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4325 string signature = SignMessage(message, params);
4326 LocalVerifyMessage(message, signature, params);
4327 }
4328
4329 /*
4330 * ImportKeyTest.Ed25519Pkcs8Success
4331 *
4332 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4333 */
TEST_P(ImportKeyTest,Ed25519Pkcs8Success)4334 TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4335 if (!Curve25519Supported()) {
4336 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4337 }
4338
4339 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4340 .Authorization(TAG_NO_AUTH_REQUIRED)
4341 .EcdsaSigningKey(EcCurve::CURVE_25519)
4342 .Digest(Digest::NONE)
4343 .SetDefaultValidity(),
4344 KeyFormat::PKCS8, ed25519_pkcs8_key));
4345 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4346 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4347 CheckOrigin();
4348
4349 // The returned cert should hold the correct public key.
4350 ASSERT_GT(cert_chain_.size(), 0);
4351 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4352 ASSERT_NE(kmKeyCert, nullptr);
4353 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4354 ASSERT_NE(kmPubKey.get(), nullptr);
4355 size_t kmPubKeySize = 32;
4356 uint8_t kmPubKeyData[32];
4357 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4358 ASSERT_EQ(kmPubKeySize, 32);
4359 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4360
4361 string message(32, 'a');
4362 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4363 string signature = SignMessage(message, params);
4364 LocalVerifyMessage(message, signature, params);
4365 }
4366
4367 /*
4368 * ImportKeyTest.Ed25519CurveMismatch
4369 *
4370 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4371 * the correct way.
4372 */
TEST_P(ImportKeyTest,Ed25519CurveMismatch)4373 TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4374 if (!Curve25519Supported()) {
4375 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4376 }
4377
4378 ASSERT_NE(ErrorCode::OK,
4379 ImportKey(AuthorizationSetBuilder()
4380 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4381 .Digest(Digest::NONE)
4382 .SetDefaultValidity(),
4383 KeyFormat::RAW, ed25519_key));
4384 }
4385
4386 /*
4387 * ImportKeyTest.Ed25519FormatMismatch
4388 *
4389 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4390 */
TEST_P(ImportKeyTest,Ed25519FormatMismatch)4391 TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4392 if (!Curve25519Supported()) {
4393 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4394 }
4395
4396 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4397 .EcdsaSigningKey(EcCurve::CURVE_25519)
4398 .Digest(Digest::NONE)
4399 .SetDefaultValidity(),
4400 KeyFormat::PKCS8, ed25519_key));
4401 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4402 .EcdsaSigningKey(EcCurve::CURVE_25519)
4403 .Digest(Digest::NONE)
4404 .SetDefaultValidity(),
4405 KeyFormat::RAW, ed25519_pkcs8_key));
4406 }
4407
4408 /*
4409 * ImportKeyTest.Ed25519PurposeMismatch
4410 *
4411 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4412 */
TEST_P(ImportKeyTest,Ed25519PurposeMismatch)4413 TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4414 if (!Curve25519Supported()) {
4415 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4416 }
4417
4418 // Can't have both SIGN and ATTEST_KEY
4419 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4420 .EcdsaSigningKey(EcCurve::CURVE_25519)
4421 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4422 .Digest(Digest::NONE)
4423 .SetDefaultValidity(),
4424 KeyFormat::RAW, ed25519_key));
4425 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4426 // PKCS#8 format and so includes an OID).
4427 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4428 .EcdsaKey(EcCurve::CURVE_25519)
4429 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4430 .Digest(Digest::NONE)
4431 .SetDefaultValidity(),
4432 KeyFormat::PKCS8, ed25519_pkcs8_key));
4433 }
4434
4435 /*
4436 * ImportKeyTest.X25519RawSuccess
4437 *
4438 * Verifies that importing and using a raw X25519 private key works correctly.
4439 */
TEST_P(ImportKeyTest,X25519RawSuccess)4440 TEST_P(ImportKeyTest, X25519RawSuccess) {
4441 if (!Curve25519Supported()) {
4442 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4443 }
4444
4445 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4446 .Authorization(TAG_NO_AUTH_REQUIRED)
4447 .EcdsaKey(EcCurve::CURVE_25519)
4448 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4449 .SetDefaultValidity(),
4450 KeyFormat::RAW, x25519_key));
4451
4452 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4453 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4454 CheckOrigin();
4455 }
4456
4457 /*
4458 * ImportKeyTest.X25519Pkcs8Success
4459 *
4460 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4461 */
TEST_P(ImportKeyTest,X25519Pkcs8Success)4462 TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4463 if (!Curve25519Supported()) {
4464 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4465 }
4466
4467 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4468 .Authorization(TAG_NO_AUTH_REQUIRED)
4469 .EcdsaKey(EcCurve::CURVE_25519)
4470 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4471 .SetDefaultValidity(),
4472 KeyFormat::PKCS8, x25519_pkcs8_key));
4473
4474 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4475 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4476 CheckOrigin();
4477 }
4478
4479 /*
4480 * ImportKeyTest.X25519CurveMismatch
4481 *
4482 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4483 * the correct way.
4484 */
TEST_P(ImportKeyTest,X25519CurveMismatch)4485 TEST_P(ImportKeyTest, X25519CurveMismatch) {
4486 if (!Curve25519Supported()) {
4487 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4488 }
4489
4490 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4491 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4492 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4493 .SetDefaultValidity(),
4494 KeyFormat::RAW, x25519_key));
4495 }
4496
4497 /*
4498 * ImportKeyTest.X25519FormatMismatch
4499 *
4500 * Verifies that importing an X25519 key with an invalid format fails.
4501 */
TEST_P(ImportKeyTest,X25519FormatMismatch)4502 TEST_P(ImportKeyTest, X25519FormatMismatch) {
4503 if (!Curve25519Supported()) {
4504 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4505 }
4506
4507 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4508 .EcdsaKey(EcCurve::CURVE_25519)
4509 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4510 .SetDefaultValidity(),
4511 KeyFormat::PKCS8, x25519_key));
4512 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4513 .EcdsaKey(EcCurve::CURVE_25519)
4514 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4515 .SetDefaultValidity(),
4516 KeyFormat::RAW, x25519_pkcs8_key));
4517 }
4518
4519 /*
4520 * ImportKeyTest.X25519PurposeMismatch
4521 *
4522 * Verifies that importing an X25519 key pair with an invalid format fails.
4523 */
TEST_P(ImportKeyTest,X25519PurposeMismatch)4524 TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4525 if (!Curve25519Supported()) {
4526 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4527 }
4528
4529 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4530 .EcdsaKey(EcCurve::CURVE_25519)
4531 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4532 .SetDefaultValidity(),
4533 KeyFormat::PKCS8, x25519_pkcs8_key));
4534 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4535 .EcdsaSigningKey(EcCurve::CURVE_25519)
4536 .SetDefaultValidity(),
4537 KeyFormat::PKCS8, x25519_pkcs8_key));
4538 }
4539
4540 /*
4541 * ImportKeyTest.AesSuccess
4542 *
4543 * Verifies that importing and using an AES key works.
4544 */
TEST_P(ImportKeyTest,AesSuccess)4545 TEST_P(ImportKeyTest, AesSuccess) {
4546 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4547 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4548 .Authorization(TAG_NO_AUTH_REQUIRED)
4549 .AesEncryptionKey(key.size() * 8)
4550 .EcbMode()
4551 .Padding(PaddingMode::PKCS7),
4552 KeyFormat::RAW, key));
4553
4554 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4555 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4556 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4557 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4558 CheckOrigin();
4559
4560 string message = "Hello World!";
4561 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4562 string ciphertext = EncryptMessage(message, params);
4563 string plaintext = DecryptMessage(ciphertext, params);
4564 EXPECT_EQ(message, plaintext);
4565 }
4566
4567 /*
4568 * ImportKeyTest.AesFailure
4569 *
4570 * Verifies that importing an invalid AES key fails.
4571 */
TEST_P(ImportKeyTest,AesFailure)4572 TEST_P(ImportKeyTest, AesFailure) {
4573 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4574 uint32_t bitlen = key.size() * 8;
4575 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
4576 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
4577 // Explicit key size doesn't match that of the provided key.
4578 auto result = ImportKey(AuthorizationSetBuilder()
4579 .Authorization(TAG_NO_AUTH_REQUIRED)
4580 .AesEncryptionKey(key_size)
4581 .EcbMode()
4582 .Padding(PaddingMode::PKCS7),
4583 KeyFormat::RAW, key);
4584 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
4585 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4586 << "unexpected result: " << result;
4587 }
4588
4589 // Explicit key size matches that of the provided key, but it's not a valid size.
4590 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4591 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4592 ImportKey(AuthorizationSetBuilder()
4593 .Authorization(TAG_NO_AUTH_REQUIRED)
4594 .AesEncryptionKey(long_key.size() * 8)
4595 .EcbMode()
4596 .Padding(PaddingMode::PKCS7),
4597 KeyFormat::RAW, long_key));
4598 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4599 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4600 ImportKey(AuthorizationSetBuilder()
4601 .Authorization(TAG_NO_AUTH_REQUIRED)
4602 .AesEncryptionKey(short_key.size() * 8)
4603 .EcbMode()
4604 .Padding(PaddingMode::PKCS7),
4605 KeyFormat::RAW, short_key));
4606 }
4607
4608 /*
4609 * ImportKeyTest.TripleDesSuccess
4610 *
4611 * Verifies that importing and using a 3DES key works.
4612 */
TEST_P(ImportKeyTest,TripleDesSuccess)4613 TEST_P(ImportKeyTest, TripleDesSuccess) {
4614 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4615 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4616 .Authorization(TAG_NO_AUTH_REQUIRED)
4617 .TripleDesEncryptionKey(168)
4618 .EcbMode()
4619 .Padding(PaddingMode::PKCS7),
4620 KeyFormat::RAW, key));
4621
4622 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4623 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4624 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4625 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4626 CheckOrigin();
4627
4628 string message = "Hello World!";
4629 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4630 string ciphertext = EncryptMessage(message, params);
4631 string plaintext = DecryptMessage(ciphertext, params);
4632 EXPECT_EQ(message, plaintext);
4633 }
4634
4635 /*
4636 * ImportKeyTest.TripleDesFailure
4637 *
4638 * Verifies that importing an invalid 3DES key fails.
4639 */
TEST_P(ImportKeyTest,TripleDesFailure)4640 TEST_P(ImportKeyTest, TripleDesFailure) {
4641 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4642 uint32_t bitlen = key.size() * 7;
4643 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
4644 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
4645 // Explicit key size doesn't match that of the provided key.
4646 auto result = ImportKey(AuthorizationSetBuilder()
4647 .Authorization(TAG_NO_AUTH_REQUIRED)
4648 .TripleDesEncryptionKey(key_size)
4649 .EcbMode()
4650 .Padding(PaddingMode::PKCS7),
4651 KeyFormat::RAW, key);
4652 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
4653 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4654 << "unexpected result: " << result;
4655 }
4656 // Explicit key size matches that of the provided key, but it's not a valid size.
4657 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
4658 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4659 ImportKey(AuthorizationSetBuilder()
4660 .Authorization(TAG_NO_AUTH_REQUIRED)
4661 .TripleDesEncryptionKey(long_key.size() * 7)
4662 .EcbMode()
4663 .Padding(PaddingMode::PKCS7),
4664 KeyFormat::RAW, long_key));
4665 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
4666 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4667 ImportKey(AuthorizationSetBuilder()
4668 .Authorization(TAG_NO_AUTH_REQUIRED)
4669 .TripleDesEncryptionKey(short_key.size() * 7)
4670 .EcbMode()
4671 .Padding(PaddingMode::PKCS7),
4672 KeyFormat::RAW, short_key));
4673 }
4674
4675 /*
4676 * ImportKeyTest.HmacKeySuccess
4677 *
4678 * Verifies that importing and using an HMAC key works.
4679 */
TEST_P(ImportKeyTest,HmacKeySuccess)4680 TEST_P(ImportKeyTest, HmacKeySuccess) {
4681 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4682 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4683 .Authorization(TAG_NO_AUTH_REQUIRED)
4684 .HmacKey(key.size() * 8)
4685 .Digest(Digest::SHA_2_256)
4686 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4687 KeyFormat::RAW, key));
4688
4689 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4690 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4691 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4692 CheckOrigin();
4693
4694 string message = "Hello World!";
4695 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4696 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4697 }
4698
4699 /*
4700 * ImportKeyTest.GetKeyCharacteristics
4701 *
4702 * Verifies that imported keys have the correct characteristics.
4703 */
TEST_P(ImportKeyTest,GetKeyCharacteristics)4704 TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4705 vector<uint8_t> key_blob;
4706 vector<KeyCharacteristics> key_characteristics;
4707 auto base_builder = AuthorizationSetBuilder()
4708 .Padding(PaddingMode::NONE)
4709 .Authorization(TAG_NO_AUTH_REQUIRED)
4710 .SetDefaultValidity();
4711 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4712 Algorithm::TRIPLE_DES};
4713 ErrorCode result;
4714 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4715 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4716 for (auto alg : algorithms) {
4717 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4718 AuthorizationSetBuilder builder(base_builder);
4719 switch (alg) {
4720 case Algorithm::RSA:
4721 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4722
4723 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4724 &key_characteristics);
4725 break;
4726 case Algorithm::EC:
4727 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4728 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4729 &key_characteristics);
4730 break;
4731 case Algorithm::HMAC:
4732 builder.HmacKey(128)
4733 .Digest(Digest::SHA_2_256)
4734 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4735 result =
4736 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4737 break;
4738 case Algorithm::AES:
4739 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4740 result =
4741 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4742 break;
4743 case Algorithm::TRIPLE_DES:
4744 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4745 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4746 &key_characteristics);
4747 break;
4748 default:
4749 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4750 continue;
4751 }
4752 ASSERT_EQ(ErrorCode::OK, result);
4753 CheckCharacteristics(key_blob, key_characteristics);
4754 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4755 }
4756 }
4757
4758 INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4759
4760 auto wrapped_key = hex2str(
4761 // IKeyMintDevice.aidl
4762 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4763 "020100" // INTEGER length 1 value 0x00 (version)
4764 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4765 "934bf94e2aa28a3f83c9f79297250262"
4766 "fbe3276b5a1c91159bbfa3ef8957aac8"
4767 "4b59b30b455a79c2973480823d8b3863"
4768 "c3deef4a8e243590268d80e18751a0e1"
4769 "30f67ce6a1ace9f79b95e097474febc9"
4770 "81195b1d13a69086c0863f66a7b7fdb4"
4771 "8792227b1ac5e2489febdf087ab54864"
4772 "83033a6f001ca5d1ec1e27f5c30f4cec"
4773 "2642074a39ae68aee552e196627a8e3d"
4774 "867e67a8c01b11e75f13cca0a97ab668"
4775 "b50cda07a8ecb7cd8e3dd7009c963653"
4776 "4f6f239cffe1fc8daa466f78b676c711"
4777 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4778 "99b801597d5220e307eaa5bee507fb94"
4779 "d1fa69f9e519b2de315bac92c36f2ea1"
4780 "fa1df4478c0ddedeae8c70e0233cd098"
4781 "040c" // OCTET STRING length 0x0c (initializationVector)
4782 "d796b02c370f1fa4cc0124f1"
4783 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4784 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4785 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4786 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4787 "3106" // SET length 0x06
4788 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4789 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4790 // } end SET
4791 // } end [1]
4792 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4793 "020120" // INTEGER length 1 value 0x20 (AES)
4794 // } end [2]
4795 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4796 "02020100" // INTEGER length 2 value 0x100
4797 // } end [3]
4798 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4799 "3103" // SET length 0x03 {
4800 "020101" // INTEGER length 1 value 0x01 (ECB)
4801 // } end SET
4802 // } end [4]
4803 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4804 "3103" // SET length 0x03 {
4805 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4806 // } end SET
4807 // } end [5]
4808 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4809 // (noAuthRequired)
4810 "0500" // NULL
4811 // } end [503]
4812 // } end SEQUENCE (AuthorizationList)
4813 // } end SEQUENCE (KeyDescription)
4814 "0420" // OCTET STRING length 0x20 (encryptedKey)
4815 "ccd540855f833a5e1480bfd2d36faf3a"
4816 "eee15df5beabe2691bc82dde2a7aa910"
4817 "0410" // OCTET STRING length 0x10 (tag)
4818 "64c9f689c60ff6223ab6e6999e0eb6e5"
4819 // } SEQUENCE (SecureKeyWrapper)
4820 );
4821
4822 auto wrapped_key_masked = hex2str(
4823 // IKeyMintDevice.aidl
4824 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4825 "020100" // INTEGER length 1 value 0x00 (version)
4826 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4827 "aad93ed5924f283b4bb5526fbe7a1412"
4828 "f9d9749ec30db9062b29e574a8546f33"
4829 "c88732452f5b8e6a391ee76c39ed1712"
4830 "c61d8df6213dec1cffbc17a8c6d04c7b"
4831 "30893d8daa9b2015213e219468215532"
4832 "07f8f9931c4caba23ed3bee28b36947e"
4833 "47f10e0a5c3dc51c988a628daad3e5e1"
4834 "f4005e79c2d5a96c284b4b8d7e4948f3"
4835 "31e5b85dd5a236f85579f3ea1d1b8484"
4836 "87470bdb0ab4f81a12bee42c99fe0df4"
4837 "bee3759453e69ad1d68a809ce06b949f"
4838 "7694a990429b2fe81e066ff43e56a216"
4839 "02db70757922a4bcc23ab89f1e35da77"
4840 "586775f423e519c2ea394caf48a28d0c"
4841 "8020f1dcf6b3a68ec246f615ae96dae9"
4842 "a079b1f6eb959033c1af5c125fd94168"
4843 "040c" // OCTET STRING length 0x0c (initializationVector)
4844 "6d9721d08589581ab49204a3"
4845 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4846 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4847 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4848 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4849 "3106" // SET length 0x06
4850 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4851 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4852 // } end SET
4853 // } end [1]
4854 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4855 "020120" // INTEGER length 1 value 0x20 (AES)
4856 // } end [2]
4857 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4858 "02020100" // INTEGER length 2 value 0x100
4859 // } end [3]
4860 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4861 "3103" // SET length 0x03 {
4862 "020101" // INTEGER length 1 value 0x01 (ECB)
4863 // } end SET
4864 // } end [4]
4865 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4866 "3103" // SET length 0x03 {
4867 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4868 // } end SET
4869 // } end [5]
4870 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4871 // (noAuthRequired)
4872 "0500" // NULL
4873 // } end [503]
4874 // } end SEQUENCE (AuthorizationList)
4875 // } end SEQUENCE (KeyDescription)
4876 "0420" // OCTET STRING length 0x20 (encryptedKey)
4877 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4878 "c20d1f99a9a024a76f35c8e2cab9b68d"
4879 "0410" // OCTET STRING length 0x10 (tag)
4880 "2560c70109ae67c030f00b98b512a670"
4881 // } SEQUENCE (SecureKeyWrapper)
4882 );
4883
4884 auto wrapping_key = hex2str(
4885 // RFC 5208 s5
4886 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4887 "020100" // INTEGER length 1 value 0x00 (version)
4888 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4889 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4890 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4891 "0500" // NULL (parameters)
4892 // } SEQUENCE (AlgorithmIdentifier)
4893 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4894 // RFC 8017 A.1.2
4895 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4896 "020100" // INTEGER length 1 value 0x00 (version)
4897 "02820101" // INTEGER length 0x0101 (modulus) value...
4898 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4899 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4900 "7b06e673a837313d56b1c725150a3fef" // 0x30
4901 "86acbddc41bb759c2854eae32d35841e" // 0x40
4902 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4903 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4904 "312d7bd5921ffaea1347c157406fef71" // 0x70
4905 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4906 "f4645c11f5c1374c3886427411c44979" // 0x90
4907 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4908 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4909 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4910 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4911 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4912 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4913 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4914 "55" // 0x101
4915 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4916 "02820100" // INTEGER length 0x100 (privateExponent) value...
4917 "431447b6251908112b1ee76f99f3711a" // 0x10
4918 "52b6630960046c2de70de188d833f8b8" // 0x20
4919 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4920 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4921 "e710b630a03adc683b5d2c43080e52be" // 0x50
4922 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4923 "822bccff087d63c940ba8a45f670feb2" // 0x70
4924 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4925 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4926 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4927 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4928 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4929 "52659d5a5ba05b663737a8696281865b" // 0xd0
4930 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4931 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4932 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4933 "028181" // INTEGER length 0x81 (prime1) value...
4934 "00de392e18d682c829266cc3454e1d61" // 0x10
4935 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4936 "ff841be5bac82a164c5970007047b8c5" // 0x30
4937 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4938 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4939 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4940 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4941 "9e91346130748a6e3c124f9149d71c74" // 0x80
4942 "35"
4943 "028181" // INTEGER length 0x81 (prime2) value...
4944 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4945 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4946 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4947 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4948 "9ed39a2d934c880440aed8832f984316" // 0x50
4949 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4950 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4951 "b880677c068e1be936e81288815252a8" // 0x80
4952 "a1"
4953 "028180" // INTEGER length 0x80 (exponent1) value...
4954 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4955 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4956 "5a063212a4f105a3764743e53281988a" // 0x30
4957 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4958 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4959 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4960 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4961 "4719d6e2b9439823719cd08bcd031781" // 0x80
4962 "028181" // INTEGER length 0x81 (exponent2) value...
4963 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4964 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4965 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4966 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4967 "1254186af30b22c10582a8a43e34fe94" // 0x50
4968 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4969 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4970 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4971 "61"
4972 "028181" // INTEGER length 0x81 (coefficient) value...
4973 "00c931617c77829dfb1270502be9195c" // 0x10
4974 "8f2830885f57dba869536811e6864236" // 0x20
4975 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4976 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4977 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4978 "959356210723287b0affcc9f727044d4" // 0x60
4979 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4980 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4981 "22"
4982 // } SEQUENCE
4983 // } SEQUENCE ()
4984 );
4985
4986 string zero_masking_key =
4987 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4988 string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4989
4990 class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4991
TEST_P(ImportWrappedKeyTest,Success)4992 TEST_P(ImportWrappedKeyTest, Success) {
4993 auto wrapping_key_desc = AuthorizationSetBuilder()
4994 .RsaEncryptionKey(2048, 65537)
4995 .Digest(Digest::SHA_2_256)
4996 .Padding(PaddingMode::RSA_OAEP)
4997 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4998 .SetDefaultValidity();
4999
5000 ASSERT_EQ(ErrorCode::OK,
5001 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5002 AuthorizationSetBuilder()
5003 .Digest(Digest::SHA_2_256)
5004 .Padding(PaddingMode::RSA_OAEP)));
5005
5006 string message = "Hello World!";
5007 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5008 string ciphertext = EncryptMessage(message, params);
5009 string plaintext = DecryptMessage(ciphertext, params);
5010 EXPECT_EQ(message, plaintext);
5011 }
5012
5013 /*
5014 * ImportWrappedKeyTest.SuccessSidsIgnored
5015 *
5016 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
5017 * include Tag:USER_SECURE_ID.
5018 */
TEST_P(ImportWrappedKeyTest,SuccessSidsIgnored)5019 TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
5020 auto wrapping_key_desc = AuthorizationSetBuilder()
5021 .RsaEncryptionKey(2048, 65537)
5022 .Digest(Digest::SHA_2_256)
5023 .Padding(PaddingMode::RSA_OAEP)
5024 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5025 .SetDefaultValidity();
5026
5027 int64_t password_sid = 42;
5028 int64_t biometric_sid = 24;
5029 ASSERT_EQ(ErrorCode::OK,
5030 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5031 AuthorizationSetBuilder()
5032 .Digest(Digest::SHA_2_256)
5033 .Padding(PaddingMode::RSA_OAEP),
5034 password_sid, biometric_sid));
5035
5036 string message = "Hello World!";
5037 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5038 string ciphertext = EncryptMessage(message, params);
5039 string plaintext = DecryptMessage(ciphertext, params);
5040 EXPECT_EQ(message, plaintext);
5041 }
5042
TEST_P(ImportWrappedKeyTest,SuccessMasked)5043 TEST_P(ImportWrappedKeyTest, SuccessMasked) {
5044 auto wrapping_key_desc = AuthorizationSetBuilder()
5045 .RsaEncryptionKey(2048, 65537)
5046 .Digest(Digest::SHA_2_256)
5047 .Padding(PaddingMode::RSA_OAEP)
5048 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5049 .SetDefaultValidity();
5050
5051 ASSERT_EQ(ErrorCode::OK,
5052 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
5053 AuthorizationSetBuilder()
5054 .Digest(Digest::SHA_2_256)
5055 .Padding(PaddingMode::RSA_OAEP)));
5056 }
5057
TEST_P(ImportWrappedKeyTest,WrongMask)5058 TEST_P(ImportWrappedKeyTest, WrongMask) {
5059 auto wrapping_key_desc = AuthorizationSetBuilder()
5060 .RsaEncryptionKey(2048, 65537)
5061 .Digest(Digest::SHA_2_256)
5062 .Padding(PaddingMode::RSA_OAEP)
5063 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5064 .SetDefaultValidity();
5065
5066 ASSERT_EQ(
5067 ErrorCode::VERIFICATION_FAILED,
5068 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5069 AuthorizationSetBuilder()
5070 .Digest(Digest::SHA_2_256)
5071 .Padding(PaddingMode::RSA_OAEP)));
5072 }
5073
TEST_P(ImportWrappedKeyTest,WrongPurpose)5074 TEST_P(ImportWrappedKeyTest, WrongPurpose) {
5075 auto wrapping_key_desc = AuthorizationSetBuilder()
5076 .RsaEncryptionKey(2048, 65537)
5077 .Digest(Digest::SHA_2_256)
5078 .Padding(PaddingMode::RSA_OAEP)
5079 .SetDefaultValidity();
5080
5081 ASSERT_EQ(
5082 ErrorCode::INCOMPATIBLE_PURPOSE,
5083 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
5084 AuthorizationSetBuilder()
5085 .Digest(Digest::SHA_2_256)
5086 .Padding(PaddingMode::RSA_OAEP)));
5087 }
5088
TEST_P(ImportWrappedKeyTest,WrongPaddingMode)5089 TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
5090 auto wrapping_key_desc = AuthorizationSetBuilder()
5091 .RsaEncryptionKey(2048, 65537)
5092 .Digest(Digest::SHA_2_256)
5093 .Padding(PaddingMode::RSA_PSS)
5094 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5095 .SetDefaultValidity();
5096
5097 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
5098 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5099 AuthorizationSetBuilder()
5100 .Digest(Digest::SHA_2_256)
5101 .Padding(PaddingMode::RSA_OAEP)));
5102 }
5103
TEST_P(ImportWrappedKeyTest,WrongDigest)5104 TEST_P(ImportWrappedKeyTest, WrongDigest) {
5105 auto wrapping_key_desc = AuthorizationSetBuilder()
5106 .RsaEncryptionKey(2048, 65537)
5107 .Padding(PaddingMode::RSA_OAEP)
5108 .Digest(Digest::SHA_2_256)
5109 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
5110 .SetDefaultValidity();
5111
5112 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
5113 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
5114 AuthorizationSetBuilder()
5115 .Digest(Digest::SHA_2_512)
5116 .Padding(PaddingMode::RSA_OAEP)));
5117 }
5118
5119 INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
5120
5121 typedef KeyMintAidlTestBase EncryptionOperationsTest;
5122
5123 /*
5124 * EncryptionOperationsTest.RsaNoPaddingSuccess
5125 *
5126 * Verifies that raw RSA decryption works.
5127 */
TEST_P(EncryptionOperationsTest,RsaNoPaddingSuccess)5128 TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
5129 for (uint64_t exponent : ValidExponents()) {
5130 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
5131 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5132 .Authorization(TAG_NO_AUTH_REQUIRED)
5133 .RsaEncryptionKey(2048, exponent)
5134 .Padding(PaddingMode::NONE)
5135 .SetDefaultValidity()));
5136
5137 string message = string(2048 / 8, 'a');
5138 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5139 string ciphertext1 = LocalRsaEncryptMessage(message, params);
5140 EXPECT_EQ(2048U / 8, ciphertext1.size());
5141
5142 string ciphertext2 = LocalRsaEncryptMessage(message, params);
5143 EXPECT_EQ(2048U / 8, ciphertext2.size());
5144
5145 // Unpadded RSA is deterministic
5146 EXPECT_EQ(ciphertext1, ciphertext2);
5147
5148 CheckedDeleteKey();
5149 }
5150 }
5151
5152 /*
5153 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5154 *
5155 * Verifies that raw RSA decryption of short messages works.
5156 */
TEST_P(EncryptionOperationsTest,RsaNoPaddingShortMessage)5157 TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5158 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5159 .Authorization(TAG_NO_AUTH_REQUIRED)
5160 .RsaEncryptionKey(2048, 65537)
5161 .Padding(PaddingMode::NONE)
5162 .SetDefaultValidity()));
5163
5164 string message = "1";
5165 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5166
5167 string ciphertext = LocalRsaEncryptMessage(message, params);
5168 EXPECT_EQ(2048U / 8, ciphertext.size());
5169
5170 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5171 string plaintext = DecryptMessage(ciphertext, params);
5172
5173 EXPECT_EQ(expected_plaintext, plaintext);
5174 }
5175
5176 /*
5177 * EncryptionOperationsTest.RsaOaepSuccess
5178 *
5179 * Verifies that RSA-OAEP decryption operations work, with all digests.
5180 */
TEST_P(EncryptionOperationsTest,RsaOaepSuccess)5181 TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5182 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5183
5184 size_t key_size = 2048; // Need largish key for SHA-512 test.
5185 ASSERT_EQ(ErrorCode::OK,
5186 GenerateKey(AuthorizationSetBuilder()
5187 .Authorization(TAG_NO_AUTH_REQUIRED)
5188 .RsaEncryptionKey(key_size, 65537)
5189 .Padding(PaddingMode::RSA_OAEP)
5190 .Digest(digests)
5191 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
5192 .SetDefaultValidity()));
5193
5194 string message = "Hello";
5195
5196 for (auto digest : digests) {
5197 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5198
5199 auto params = AuthorizationSetBuilder()
5200 .Digest(digest)
5201 .Padding(PaddingMode::RSA_OAEP)
5202 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5203 string ciphertext1 = LocalRsaEncryptMessage(message, params);
5204 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5205 EXPECT_EQ(key_size / 8, ciphertext1.size());
5206
5207 string ciphertext2 = LocalRsaEncryptMessage(message, params);
5208 EXPECT_EQ(key_size / 8, ciphertext2.size());
5209
5210 // OAEP randomizes padding so every result should be different (with astronomically high
5211 // probability).
5212 EXPECT_NE(ciphertext1, ciphertext2);
5213
5214 string plaintext1 = DecryptMessage(ciphertext1, params);
5215 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5216 string plaintext2 = DecryptMessage(ciphertext2, params);
5217 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5218
5219 // Decrypting corrupted ciphertext should fail.
5220 size_t offset_to_corrupt = random() % ciphertext1.size();
5221 char corrupt_byte;
5222 do {
5223 corrupt_byte = static_cast<char>(random() % 256);
5224 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5225 ciphertext1[offset_to_corrupt] = corrupt_byte;
5226
5227 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5228 string result;
5229 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5230 EXPECT_EQ(0U, result.size());
5231 }
5232 }
5233
5234 /*
5235 * EncryptionOperationsTest.RsaOaepInvalidDigest
5236 *
5237 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
5238 * without a digest.
5239 */
TEST_P(EncryptionOperationsTest,RsaOaepInvalidDigest)5240 TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5241 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5242 .Authorization(TAG_NO_AUTH_REQUIRED)
5243 .RsaEncryptionKey(2048, 65537)
5244 .Padding(PaddingMode::RSA_OAEP)
5245 .Digest(Digest::NONE)
5246 .SetDefaultValidity()));
5247
5248 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
5249 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
5250 }
5251
5252 /*
5253 * EncryptionOperationsTest.RsaOaepInvalidPadding
5254 *
5255 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
5256 * with a padding value that is only suitable for signing/verifying.
5257 */
TEST_P(EncryptionOperationsTest,RsaOaepInvalidPadding)5258 TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5259 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5260 .Authorization(TAG_NO_AUTH_REQUIRED)
5261 .RsaEncryptionKey(2048, 65537)
5262 .Padding(PaddingMode::RSA_PSS)
5263 .Digest(Digest::NONE)
5264 .SetDefaultValidity()));
5265
5266 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
5267 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
5268 }
5269
5270 /*
5271 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
5272 *
5273 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
5274 * with a different digest than was used to encrypt.
5275 */
TEST_P(EncryptionOperationsTest,RsaOaepDecryptWithWrongDigest)5276 TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
5277 if (SecLevel() == SecurityLevel::STRONGBOX) {
5278 GTEST_SKIP() << "Test not applicable to StrongBox device";
5279 }
5280
5281 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5282 .Authorization(TAG_NO_AUTH_REQUIRED)
5283 .RsaEncryptionKey(1024, 65537)
5284 .Padding(PaddingMode::RSA_OAEP)
5285 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5286 .SetDefaultValidity()));
5287 string message = "Hello World!";
5288 string ciphertext = LocalRsaEncryptMessage(
5289 message,
5290 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5291
5292 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5293 .Digest(Digest::SHA_2_256)
5294 .Padding(PaddingMode::RSA_OAEP)));
5295 string result;
5296 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5297 EXPECT_EQ(0U, result.size());
5298 }
5299
5300 /*
5301 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5302 *
5303 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
5304 * digests.
5305 */
TEST_P(EncryptionOperationsTest,RsaOaepWithMGFDigestSuccess)5306 TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5307 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5308
5309 size_t key_size = 2048; // Need largish key for SHA-512 test.
5310 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5311 .OaepMGFDigest(digests)
5312 .Authorization(TAG_NO_AUTH_REQUIRED)
5313 .RsaEncryptionKey(key_size, 65537)
5314 .Padding(PaddingMode::RSA_OAEP)
5315 .Digest(Digest::SHA_2_256)
5316 .SetDefaultValidity()));
5317
5318 string message = "Hello";
5319
5320 for (auto digest : digests) {
5321 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5322 auto params = AuthorizationSetBuilder()
5323 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5324 .Digest(Digest::SHA_2_256)
5325 .Padding(PaddingMode::RSA_OAEP);
5326 string ciphertext1 = LocalRsaEncryptMessage(message, params);
5327 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5328 EXPECT_EQ(key_size / 8, ciphertext1.size());
5329
5330 string ciphertext2 = LocalRsaEncryptMessage(message, params);
5331 EXPECT_EQ(key_size / 8, ciphertext2.size());
5332
5333 // OAEP randomizes padding so every result should be different (with astronomically high
5334 // probability).
5335 EXPECT_NE(ciphertext1, ciphertext2);
5336
5337 string plaintext1 = DecryptMessage(ciphertext1, params);
5338 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5339 string plaintext2 = DecryptMessage(ciphertext2, params);
5340 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5341
5342 // Decrypting corrupted ciphertext should fail.
5343 size_t offset_to_corrupt = random() % ciphertext1.size();
5344 char corrupt_byte;
5345 do {
5346 corrupt_byte = static_cast<char>(random() % 256);
5347 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5348 ciphertext1[offset_to_corrupt] = corrupt_byte;
5349
5350 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5351 string result;
5352 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5353 EXPECT_EQ(0U, result.size());
5354 }
5355 }
5356
5357 /*
5358 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5359 *
5360 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5361 * specified, defaulting to SHA-1.
5362 */
TEST_P(EncryptionOperationsTest,RsaOaepMGFDigestDefaultSuccess)5363 TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5364 size_t key_size = 2048;
5365 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5366 .Authorization(TAG_NO_AUTH_REQUIRED)
5367 .RsaEncryptionKey(key_size, 65537)
5368 .Padding(PaddingMode::RSA_OAEP)
5369 .Digest(Digest::SHA_2_256)
5370 .SetDefaultValidity()));
5371
5372 // Do local RSA encryption using the default MGF digest of SHA-1.
5373 string message = "Hello";
5374 auto params =
5375 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5376 string ciphertext = LocalRsaEncryptMessage(message, params);
5377 EXPECT_EQ(key_size / 8, ciphertext.size());
5378
5379 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5380 string plaintext = DecryptMessage(ciphertext, params);
5381 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5382
5383 // Decrypting corrupted ciphertext should fail.
5384 size_t offset_to_corrupt = random() % ciphertext.size();
5385 char corrupt_byte;
5386 do {
5387 corrupt_byte = static_cast<char>(random() % 256);
5388 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5389 ciphertext[offset_to_corrupt] = corrupt_byte;
5390
5391 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5392 string result;
5393 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5394 EXPECT_EQ(0U, result.size());
5395 }
5396
5397 /*
5398 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5399 *
5400 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5401 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5402 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5403 */
TEST_P(EncryptionOperationsTest,RsaOaepMGFDigestDefaultFail)5404 TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5405 size_t key_size = 2048;
5406 ASSERT_EQ(ErrorCode::OK,
5407 GenerateKey(AuthorizationSetBuilder()
5408 .Authorization(TAG_NO_AUTH_REQUIRED)
5409 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5410 .RsaEncryptionKey(key_size, 65537)
5411 .Padding(PaddingMode::RSA_OAEP)
5412 .Digest(Digest::SHA_2_256)
5413 .SetDefaultValidity()));
5414
5415 // Do local RSA encryption using the default MGF digest of SHA-1.
5416 string message = "Hello";
5417 auto params =
5418 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5419 string ciphertext = LocalRsaEncryptMessage(message, params);
5420 EXPECT_EQ(key_size / 8, ciphertext.size());
5421
5422 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5423 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5424 // is checked against those values, and found absent.
5425 auto result = Begin(KeyPurpose::DECRYPT, params);
5426 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5427 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5428 }
5429
5430 /*
5431 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5432 *
5433 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
5434 * with incompatible MGF digest.
5435 */
TEST_P(EncryptionOperationsTest,RsaOaepWithMGFIncompatibleDigest)5436 TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5437 ASSERT_EQ(ErrorCode::OK,
5438 GenerateKey(AuthorizationSetBuilder()
5439 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5440 .Authorization(TAG_NO_AUTH_REQUIRED)
5441 .RsaEncryptionKey(2048, 65537)
5442 .Padding(PaddingMode::RSA_OAEP)
5443 .Digest(Digest::SHA_2_256)
5444 .SetDefaultValidity()));
5445 string message = "Hello World!";
5446
5447 auto params = AuthorizationSetBuilder()
5448 .Padding(PaddingMode::RSA_OAEP)
5449 .Digest(Digest::SHA_2_256)
5450 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
5451 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
5452 }
5453
5454 /*
5455 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5456 *
5457 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5458 * with unsupported MGF digest.
5459 */
TEST_P(EncryptionOperationsTest,RsaOaepWithMGFUnsupportedDigest)5460 TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5461 ASSERT_EQ(ErrorCode::OK,
5462 GenerateKey(AuthorizationSetBuilder()
5463 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5464 .Authorization(TAG_NO_AUTH_REQUIRED)
5465 .RsaEncryptionKey(2048, 65537)
5466 .Padding(PaddingMode::RSA_OAEP)
5467 .Digest(Digest::SHA_2_256)
5468 .SetDefaultValidity()));
5469 string message = "Hello World!";
5470
5471 auto params = AuthorizationSetBuilder()
5472 .Padding(PaddingMode::RSA_OAEP)
5473 .Digest(Digest::SHA_2_256)
5474 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
5475 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
5476 }
5477
5478 /*
5479 * EncryptionOperationsTest.RsaPkcs1Success
5480 *
5481 * Verifies that RSA PKCS encryption/decrypts works.
5482 */
TEST_P(EncryptionOperationsTest,RsaPkcs1Success)5483 TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5484 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5485 .Authorization(TAG_NO_AUTH_REQUIRED)
5486 .RsaEncryptionKey(2048, 65537)
5487 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5488 .SetDefaultValidity()));
5489
5490 string message = "Hello World!";
5491 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
5492 string ciphertext1 = LocalRsaEncryptMessage(message, params);
5493 EXPECT_EQ(2048U / 8, ciphertext1.size());
5494
5495 string ciphertext2 = LocalRsaEncryptMessage(message, params);
5496 EXPECT_EQ(2048U / 8, ciphertext2.size());
5497
5498 // PKCS1 v1.5 randomizes padding so every result should be different.
5499 EXPECT_NE(ciphertext1, ciphertext2);
5500
5501 string plaintext = DecryptMessage(ciphertext1, params);
5502 EXPECT_EQ(message, plaintext);
5503
5504 // Decrypting corrupted ciphertext should fail.
5505 size_t offset_to_corrupt = random() % ciphertext1.size();
5506 char corrupt_byte;
5507 do {
5508 corrupt_byte = static_cast<char>(random() % 256);
5509 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5510 ciphertext1[offset_to_corrupt] = corrupt_byte;
5511
5512 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5513 string result;
5514 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5515 EXPECT_EQ(0U, result.size());
5516 }
5517
5518 /*
5519 * EncryptionOperationsTest.EcdsaEncrypt
5520 *
5521 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5522 */
TEST_P(EncryptionOperationsTest,EcdsaEncrypt)5523 TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5524 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5525 .Authorization(TAG_NO_AUTH_REQUIRED)
5526 .EcdsaSigningKey(EcCurve::P_256)
5527 .Digest(Digest::NONE)
5528 .SetDefaultValidity()));
5529 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5530 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5531 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5532 }
5533
5534 /*
5535 * EncryptionOperationsTest.HmacEncrypt
5536 *
5537 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5538 */
TEST_P(EncryptionOperationsTest,HmacEncrypt)5539 TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5540 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5541 .Authorization(TAG_NO_AUTH_REQUIRED)
5542 .HmacKey(128)
5543 .Digest(Digest::SHA_2_256)
5544 .Padding(PaddingMode::NONE)
5545 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5546 auto params = AuthorizationSetBuilder()
5547 .Digest(Digest::SHA_2_256)
5548 .Padding(PaddingMode::NONE)
5549 .Authorization(TAG_MAC_LENGTH, 128);
5550 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5551 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5552 }
5553
5554 /*
5555 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5556 *
5557 * Verifies that AES ECB mode works.
5558 */
TEST_P(EncryptionOperationsTest,AesEcbRoundTripSuccess)5559 TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5560 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5561 .Authorization(TAG_NO_AUTH_REQUIRED)
5562 .AesEncryptionKey(128)
5563 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5564 .Padding(PaddingMode::NONE)));
5565
5566 ASSERT_GT(key_blob_.size(), 0U);
5567 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5568
5569 // Two-block message.
5570 string message = "12345678901234567890123456789012";
5571 string ciphertext1 = EncryptMessage(message, params);
5572 EXPECT_EQ(message.size(), ciphertext1.size());
5573
5574 string ciphertext2 = EncryptMessage(string(message), params);
5575 EXPECT_EQ(message.size(), ciphertext2.size());
5576
5577 // ECB is deterministic.
5578 EXPECT_EQ(ciphertext1, ciphertext2);
5579
5580 string plaintext = DecryptMessage(ciphertext1, params);
5581 EXPECT_EQ(message, plaintext);
5582 }
5583
5584 /*
5585 * EncryptionOperationsTest.AesEcbUnknownTag
5586 *
5587 * Verifies that AES ECB operations ignore unknown tags.
5588 */
TEST_P(EncryptionOperationsTest,AesEcbUnknownTag)5589 TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5590 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5591 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5592 KeyParameter unknown_param;
5593 unknown_param.tag = unknown_tag;
5594
5595 vector<KeyCharacteristics> key_characteristics;
5596 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5597 .Authorization(TAG_NO_AUTH_REQUIRED)
5598 .AesEncryptionKey(128)
5599 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5600 .Padding(PaddingMode::NONE)
5601 .Authorization(unknown_param),
5602 &key_blob_, &key_characteristics));
5603 ASSERT_GT(key_blob_.size(), 0U);
5604
5605 // Unknown tags should not be returned in key characteristics.
5606 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5607 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5608 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5609 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5610
5611 // Encrypt without mentioning the unknown parameter.
5612 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5613 string message = "12345678901234567890123456789012";
5614 string ciphertext = EncryptMessage(message, params);
5615 EXPECT_EQ(message.size(), ciphertext.size());
5616
5617 // Decrypt including the unknown parameter.
5618 auto decrypt_params = AuthorizationSetBuilder()
5619 .BlockMode(BlockMode::ECB)
5620 .Padding(PaddingMode::NONE)
5621 .Authorization(unknown_param);
5622 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5623 EXPECT_EQ(message, plaintext);
5624 }
5625
5626 /*
5627 * EncryptionOperationsTest.AesWrongMode
5628 *
5629 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5630 */
TEST_P(EncryptionOperationsTest,AesWrongMode)5631 TEST_P(EncryptionOperationsTest, AesWrongMode) {
5632 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5633 .Authorization(TAG_NO_AUTH_REQUIRED)
5634 .AesEncryptionKey(128)
5635 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5636 .Padding(PaddingMode::NONE)));
5637 ASSERT_GT(key_blob_.size(), 0U);
5638
5639 EXPECT_EQ(
5640 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5641 Begin(KeyPurpose::ENCRYPT,
5642 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5643 }
5644
5645 /*
5646 * EncryptionOperationsTest.AesWrongPadding
5647 *
5648 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5649 */
TEST_P(EncryptionOperationsTest,AesWrongPadding)5650 TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5651 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5652 .Authorization(TAG_NO_AUTH_REQUIRED)
5653 .AesEncryptionKey(128)
5654 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5655 .Padding(PaddingMode::NONE)));
5656 ASSERT_GT(key_blob_.size(), 0U);
5657
5658 EXPECT_EQ(
5659 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5660 Begin(KeyPurpose::ENCRYPT,
5661 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5662 }
5663
5664 /*
5665 * EncryptionOperationsTest.AesInvalidParams
5666 *
5667 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5668 */
TEST_P(EncryptionOperationsTest,AesInvalidParams)5669 TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5670 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5671 .Authorization(TAG_NO_AUTH_REQUIRED)
5672 .AesEncryptionKey(128)
5673 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5674 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5675 .Padding(PaddingMode::NONE)
5676 .Padding(PaddingMode::PKCS7)));
5677 ASSERT_GT(key_blob_.size(), 0U);
5678
5679 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5680 .BlockMode(BlockMode::CBC)
5681 .BlockMode(BlockMode::ECB)
5682 .Padding(PaddingMode::NONE));
5683 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5684 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5685
5686 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5687 .BlockMode(BlockMode::ECB)
5688 .Padding(PaddingMode::NONE)
5689 .Padding(PaddingMode::PKCS7));
5690 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5691 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5692 }
5693
5694 /*
5695 * EncryptionOperationsTest.AesWrongPurpose
5696 *
5697 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5698 * specified.
5699 */
TEST_P(EncryptionOperationsTest,AesWrongPurpose)5700 TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5701 auto err = GenerateKey(AuthorizationSetBuilder()
5702 .Authorization(TAG_NO_AUTH_REQUIRED)
5703 .AesKey(128)
5704 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5705 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5706 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5707 .Padding(PaddingMode::NONE));
5708 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5709 ASSERT_GT(key_blob_.size(), 0U);
5710
5711 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5712 .BlockMode(BlockMode::GCM)
5713 .Padding(PaddingMode::NONE)
5714 .Authorization(TAG_MAC_LENGTH, 128));
5715 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5716
5717 CheckedDeleteKey();
5718
5719 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5720 .Authorization(TAG_NO_AUTH_REQUIRED)
5721 .AesKey(128)
5722 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5723 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5724 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5725 .Padding(PaddingMode::NONE)));
5726
5727 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5728 .BlockMode(BlockMode::GCM)
5729 .Padding(PaddingMode::NONE)
5730 .Authorization(TAG_MAC_LENGTH, 128));
5731 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5732 }
5733
5734 /*
5735 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
5736 *
5737 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5738 * multiple of the block size and no padding is specified.
5739 */
TEST_P(EncryptionOperationsTest,AesEcbCbcNoPaddingWrongInputSize)5740 TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5741 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5742 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
5743 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5744 .Authorization(TAG_NO_AUTH_REQUIRED)
5745 .AesEncryptionKey(128)
5746 .Authorization(TAG_BLOCK_MODE, blockMode)
5747 .Padding(PaddingMode::NONE)));
5748 // Message is slightly shorter than two blocks.
5749 string message(16 * 2 - 1, 'a');
5750
5751 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5752 AuthorizationSet out_params;
5753 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5754 string ciphertext;
5755 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5756 EXPECT_EQ(0U, ciphertext.size());
5757
5758 CheckedDeleteKey();
5759 }
5760 }
5761
5762 /*
5763 * EncryptionOperationsTest.AesEcbPkcs7Padding
5764 *
5765 * Verifies that AES PKCS7 padding works for any message length.
5766 */
TEST_P(EncryptionOperationsTest,AesEcbPkcs7Padding)5767 TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5768 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5769 .Authorization(TAG_NO_AUTH_REQUIRED)
5770 .AesEncryptionKey(128)
5771 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5772 .Padding(PaddingMode::PKCS7)));
5773
5774 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5775
5776 // Try various message lengths; all should work.
5777 for (size_t i = 0; i <= 48; i++) {
5778 SCOPED_TRACE(testing::Message() << "i = " << i);
5779 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5780 string message(i, '\t');
5781 string ciphertext = EncryptMessage(message, params);
5782 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5783 string plaintext = DecryptMessage(ciphertext, params);
5784 EXPECT_EQ(message, plaintext);
5785 }
5786 }
5787
5788 /*
5789 * EncryptionOperationsTest.AesEcbWrongPadding
5790 *
5791 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5792 * specified.
5793 */
TEST_P(EncryptionOperationsTest,AesEcbWrongPadding)5794 TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5795 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5796 .Authorization(TAG_NO_AUTH_REQUIRED)
5797 .AesEncryptionKey(128)
5798 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5799 .Padding(PaddingMode::NONE)));
5800
5801 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5802
5803 // Try various message lengths; all should fail
5804 for (size_t i = 0; i <= 48; i++) {
5805 string message(i, 'a');
5806 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5807 }
5808 }
5809
5810 /*
5811 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5812 *
5813 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5814 */
TEST_P(EncryptionOperationsTest,AesEcbPkcs7PaddingCorrupted)5815 TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5816 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5817 .Authorization(TAG_NO_AUTH_REQUIRED)
5818 .AesEncryptionKey(128)
5819 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5820 .Padding(PaddingMode::PKCS7)));
5821
5822 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5823
5824 string message = "a";
5825 string ciphertext = EncryptMessage(message, params);
5826 EXPECT_EQ(16U, ciphertext.size());
5827 EXPECT_NE(ciphertext, message);
5828
5829 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5830 ++ciphertext[ciphertext.size() / 2];
5831
5832 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5833 string plaintext;
5834 ErrorCode error = Finish(ciphertext, &plaintext);
5835 if (error == ErrorCode::INVALID_ARGUMENT) {
5836 // This is the expected error, we can exit the test now.
5837 return;
5838 } else {
5839 // Very small chance we got valid decryption, so try again.
5840 ASSERT_EQ(error, ErrorCode::OK)
5841 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
5842 }
5843 }
5844 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
5845 }
5846
5847 /*
5848 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5849 *
5850 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5851 */
TEST_P(EncryptionOperationsTest,AesEcbPkcs7CiphertextTooShort)5852 TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5853 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5854 .Authorization(TAG_NO_AUTH_REQUIRED)
5855 .AesEncryptionKey(128)
5856 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5857 .Padding(PaddingMode::PKCS7)));
5858
5859 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5860
5861 string message = "a";
5862 string ciphertext = EncryptMessage(message, params);
5863 EXPECT_EQ(16U, ciphertext.size());
5864 EXPECT_NE(ciphertext, message);
5865
5866 // Shorten the ciphertext.
5867 ciphertext.resize(ciphertext.size() - 1);
5868 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5869 string plaintext;
5870 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5871 }
5872
CopyIv(const AuthorizationSet & set)5873 vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5874 auto iv = set.GetTagValue(TAG_NONCE);
5875 EXPECT_TRUE(iv);
5876 return iv->get();
5877 }
5878
5879 /*
5880 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5881 *
5882 * Verifies that AES CTR mode works.
5883 */
TEST_P(EncryptionOperationsTest,AesCtrRoundTripSuccess)5884 TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5885 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5886 .Authorization(TAG_NO_AUTH_REQUIRED)
5887 .AesEncryptionKey(128)
5888 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5889 .Padding(PaddingMode::NONE)));
5890
5891 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5892
5893 string message = "123";
5894 AuthorizationSet out_params;
5895 string ciphertext1 = EncryptMessage(message, params, &out_params);
5896 vector<uint8_t> iv1 = CopyIv(out_params);
5897 EXPECT_EQ(16U, iv1.size());
5898
5899 EXPECT_EQ(message.size(), ciphertext1.size());
5900
5901 out_params.Clear();
5902 string ciphertext2 = EncryptMessage(message, params, &out_params);
5903 vector<uint8_t> iv2 = CopyIv(out_params);
5904 EXPECT_EQ(16U, iv2.size());
5905
5906 // IVs should be random, so ciphertexts should differ.
5907 EXPECT_NE(ciphertext1, ciphertext2);
5908
5909 auto params_iv1 =
5910 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5911 auto params_iv2 =
5912 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5913
5914 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5915 EXPECT_EQ(message, plaintext);
5916 plaintext = DecryptMessage(ciphertext2, params_iv2);
5917 EXPECT_EQ(message, plaintext);
5918
5919 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5920 plaintext = DecryptMessage(ciphertext1, params_iv2);
5921 EXPECT_NE(message, plaintext);
5922 plaintext = DecryptMessage(ciphertext2, params_iv1);
5923 EXPECT_NE(message, plaintext);
5924 }
5925
5926 /*
5927 * EncryptionOperationsTest.AesEcbIncremental
5928 *
5929 * Verifies that AES works for ECB block mode, when provided data in various size increments.
5930 */
TEST_P(EncryptionOperationsTest,AesEcbIncremental)5931 TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5932 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5933 }
5934
5935 /*
5936 * EncryptionOperationsTest.AesCbcIncremental
5937 *
5938 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5939 */
TEST_P(EncryptionOperationsTest,AesCbcIncremental)5940 TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5941 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5942 }
5943
5944 /*
5945 * EncryptionOperationsTest.AesCtrIncremental
5946 *
5947 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5948 */
TEST_P(EncryptionOperationsTest,AesCtrIncremental)5949 TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5950 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5951 }
5952
5953 /*
5954 * EncryptionOperationsTest.AesGcmIncremental
5955 *
5956 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5957 */
TEST_P(EncryptionOperationsTest,AesGcmIncremental)5958 TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5959 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
5960 }
5961
5962 /*
5963 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
5964 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5965 */
TEST_P(EncryptionOperationsTest,Aes128CBCNoPaddingOneByteAtATime)5966 TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
5967 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
5968 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
5969 string kat_plaintext =
5970 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
5971 "809FFF37081C22EF278F896AB213A2A631");
5972 string kat_ciphertext =
5973 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
5974 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
5975 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5976 kat_ciphertext);
5977 }
5978
5979 /*
5980 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
5981 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5982 */
TEST_P(EncryptionOperationsTest,Aes128CBCPKCS7PaddingOneByteAtATime)5983 TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
5984 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
5985 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
5986 string kat_plaintext =
5987 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
5988 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
5989 string kat_ciphertext =
5990 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
5991 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
5992 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5993 kat_plaintext, kat_ciphertext);
5994 }
5995
5996 /*
5997 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
5998 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5999 */
TEST_P(EncryptionOperationsTest,Aes128CTRNoPaddingOneByteAtATime)6000 TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
6001 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
6002 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
6003 string kat_plaintext =
6004 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
6005 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
6006 string kat_ciphertext =
6007 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
6008 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
6009 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6010 kat_ciphertext);
6011 }
6012
6013 /*
6014 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
6015 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6016 */
TEST_P(EncryptionOperationsTest,Aes128ECBNoPaddingOneByteAtATime)6017 TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
6018 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
6019 string kat_plaintext =
6020 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
6021 "7B6168A9A27BCE554BEA94EF26E6C742A0");
6022 string kat_ciphertext =
6023 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
6024 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
6025 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6026 kat_ciphertext);
6027 }
6028
6029 /*
6030 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
6031 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6032 */
TEST_P(EncryptionOperationsTest,Aes128ECBPKCS7PaddingOneByteAtATime)6033 TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
6034 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
6035 string kat_plaintext =
6036 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
6037 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
6038 string kat_ciphertext =
6039 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
6040 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
6041 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6042 kat_ciphertext);
6043 }
6044
6045 /*
6046 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
6047 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6048 */
TEST_P(EncryptionOperationsTest,Aes128GCMNoPaddingOneByteAtATime)6049 TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
6050 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
6051 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
6052 string kat_plaintext =
6053 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
6054 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
6055 string kat_ciphertext =
6056 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
6057 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
6058 "bdfcc0cba0");
6059
6060 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6061 kat_ciphertext);
6062 }
6063
6064 /*
6065 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
6066 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6067 */
TEST_P(EncryptionOperationsTest,Aes192CBCNoPaddingOneByteAtATime)6068 TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
6069 if (SecLevel() == SecurityLevel::STRONGBOX) {
6070 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6071 }
6072 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
6073 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
6074 string kat_plaintext =
6075 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
6076 "167f2497c994bd496eb80bfb2ba2c9d5af");
6077 string kat_ciphertext =
6078 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
6079 "72c134552f3a138e726fbe493b3a839598");
6080 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6081 kat_ciphertext);
6082 }
6083
6084 /*
6085 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
6086 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6087 */
TEST_P(EncryptionOperationsTest,Aes192CBCPKCS7PaddingOneByteAtATime)6088 TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
6089 if (SecLevel() == SecurityLevel::STRONGBOX) {
6090 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6091 }
6092 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
6093 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
6094 string kat_plaintext =
6095 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
6096 "b170");
6097 string kat_ciphertext =
6098 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
6099 "4e3884138ff403a41fd99818708ada301c");
6100 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6101 kat_plaintext, kat_ciphertext);
6102 }
6103
6104 /*
6105 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
6106 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6107 */
TEST_P(EncryptionOperationsTest,Aes192CTRNoPaddingOneByteAtATime)6108 TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
6109 if (SecLevel() == SecurityLevel::STRONGBOX) {
6110 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6111 }
6112 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
6113 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
6114 string kat_plaintext =
6115 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
6116 "28091e09cdbbd3b42b");
6117 string kat_ciphertext =
6118 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
6119 "2ae0f90f0c19f42b4a");
6120 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6121 kat_ciphertext);
6122 }
6123
6124 /*
6125 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
6126 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6127 */
TEST_P(EncryptionOperationsTest,Aes192ECBNoPaddingOneByteAtATime)6128 TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
6129 if (SecLevel() == SecurityLevel::STRONGBOX) {
6130 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6131 }
6132 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
6133 string kat_plaintext =
6134 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
6135 "44ab");
6136 string kat_ciphertext =
6137 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
6138 "2453");
6139 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6140 kat_ciphertext);
6141 }
6142
6143 /*
6144 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6145 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6146 */
TEST_P(EncryptionOperationsTest,Aes192ECBPKCS7PaddingOneByteAtATime)6147 TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6148 if (SecLevel() == SecurityLevel::STRONGBOX) {
6149 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6150 }
6151 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6152 string kat_plaintext =
6153 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6154 "e2c7");
6155 string kat_ciphertext =
6156 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6157 "bb7e3a889dd4a9589098b44acf1056e7aa");
6158 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6159 kat_ciphertext);
6160 }
6161
6162 /*
6163 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6164 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6165 */
TEST_P(EncryptionOperationsTest,Aes192GCMNoPaddingOneByteAtATime)6166 TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6167 if (SecLevel() == SecurityLevel::STRONGBOX) {
6168 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6169 }
6170 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6171 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6172 string kat_plaintext =
6173 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6174 "ff52");
6175 string kat_ciphertext =
6176 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6177 "1413ad70fb0e1970669095ad77ebb5974ae8");
6178
6179 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6180 kat_ciphertext);
6181 }
6182
6183 /*
6184 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6185 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6186 */
TEST_P(EncryptionOperationsTest,Aes256CBCNoPaddingOneByteAtATime)6187 TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6188 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6189 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6190 string kat_plaintext =
6191 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6192 "494cb53caca353e4b637ba05687be20f8d");
6193 string kat_ciphertext =
6194 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6195 "6047da1e4fd7c4e1cf2656097f75ae8685");
6196 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6197 kat_ciphertext);
6198 }
6199
6200 /*
6201 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6202 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6203 */
TEST_P(EncryptionOperationsTest,Aes256CBCPKCS7PaddingOneByteAtATime)6204 TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6205 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6206 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6207 string kat_plaintext =
6208 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6209 "2545a82b73c48078b9dae62261c65909");
6210 string kat_ciphertext =
6211 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6212 "9403a71987b95124073d69f2a3cb95b0ab");
6213 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6214 kat_plaintext, kat_ciphertext);
6215 }
6216
6217 /*
6218 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6219 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6220 */
TEST_P(EncryptionOperationsTest,Aes256CTRNoPaddingOneByteAtATime)6221 TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6222 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6223 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6224 string kat_plaintext =
6225 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6226 "1f6db3c884");
6227 string kat_ciphertext =
6228 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6229 "a7be30d4c3");
6230 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6231 kat_ciphertext);
6232 }
6233
6234 /*
6235 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6236 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6237 */
TEST_P(EncryptionOperationsTest,Aes256ECBNoPaddingOneByteAtATime)6238 TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6239 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6240 string kat_plaintext =
6241 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6242 "31a476d6806b8116089c6ec50bb543200f");
6243 string kat_ciphertext =
6244 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6245 "c83e377faf246288931136bef2a07c0be4");
6246 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6247 kat_ciphertext);
6248 }
6249
6250 /*
6251 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6252 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6253 */
TEST_P(EncryptionOperationsTest,Aes256ECBPKCS7PaddingOneByteAtATime)6254 TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6255 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6256 string kat_plaintext =
6257 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6258 "6f");
6259 string kat_ciphertext =
6260 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6261 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6262 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6263 kat_ciphertext);
6264 }
6265
6266 /*
6267 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6268 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6269 */
TEST_P(EncryptionOperationsTest,Aes256GCMNoPaddingOneByteAtATime)6270 TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6271 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6272 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6273 string kat_plaintext =
6274 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6275 "f0");
6276 string kat_ciphertext =
6277 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6278 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6279
6280 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6281 kat_ciphertext);
6282 }
6283
6284 struct AesCtrSp80038aTestVector {
6285 const char* key;
6286 const char* nonce;
6287 const char* plaintext;
6288 const char* ciphertext;
6289 };
6290
6291 // These test vectors are taken from
6292 // http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6293 static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6294 // AES-128
6295 {
6296 "2b7e151628aed2a6abf7158809cf4f3c",
6297 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6298 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6299 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6300 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6301 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6302 },
6303 // AES-192
6304 {
6305 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6306 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6307 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6308 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6309 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6310 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6311 },
6312 // AES-256
6313 {
6314 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6315 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6316 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6317 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6318 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6319 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6320 },
6321 };
6322
6323 /*
6324 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6325 *
6326 * Verifies AES CTR implementation against SP800-38A test vectors.
6327 */
TEST_P(EncryptionOperationsTest,AesCtrSp80038aTestVector)6328 TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6329 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6330 for (size_t i = 0; i < 3; i++) {
6331 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6332 const string key = hex2str(test.key);
6333 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6334 InvalidSizes.end())
6335 continue;
6336 const string nonce = hex2str(test.nonce);
6337 const string plaintext = hex2str(test.plaintext);
6338 const string ciphertext = hex2str(test.ciphertext);
6339 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6340 }
6341 }
6342
6343 /*
6344 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6345 *
6346 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6347 */
TEST_P(EncryptionOperationsTest,AesCtrIncompatiblePaddingMode)6348 TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6349 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6350 .Authorization(TAG_NO_AUTH_REQUIRED)
6351 .AesEncryptionKey(128)
6352 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6353 .Padding(PaddingMode::PKCS7)));
6354 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6355 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6356 }
6357
6358 /*
6359 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6360 *
6361 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6362 */
TEST_P(EncryptionOperationsTest,AesCtrInvalidCallerNonce)6363 TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6364 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6365 .Authorization(TAG_NO_AUTH_REQUIRED)
6366 .AesEncryptionKey(128)
6367 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6368 .Authorization(TAG_CALLER_NONCE)
6369 .Padding(PaddingMode::NONE)));
6370
6371 auto params = AuthorizationSetBuilder()
6372 .BlockMode(BlockMode::CTR)
6373 .Padding(PaddingMode::NONE)
6374 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6375 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6376
6377 params = AuthorizationSetBuilder()
6378 .BlockMode(BlockMode::CTR)
6379 .Padding(PaddingMode::NONE)
6380 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6381 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6382
6383 params = AuthorizationSetBuilder()
6384 .BlockMode(BlockMode::CTR)
6385 .Padding(PaddingMode::NONE)
6386 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6387 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6388 }
6389
6390 /*
6391 * EncryptionOperationsTest.AesCbcRoundTripSuccess
6392 *
6393 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6394 */
TEST_P(EncryptionOperationsTest,AesCbcRoundTripSuccess)6395 TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6396 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6397 .Authorization(TAG_NO_AUTH_REQUIRED)
6398 .AesEncryptionKey(128)
6399 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6400 .Padding(PaddingMode::NONE)));
6401 // Two-block message.
6402 string message = "12345678901234567890123456789012";
6403 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6404 AuthorizationSet out_params;
6405 string ciphertext1 = EncryptMessage(message, params, &out_params);
6406 vector<uint8_t> iv1 = CopyIv(out_params);
6407 EXPECT_EQ(message.size(), ciphertext1.size());
6408
6409 out_params.Clear();
6410
6411 string ciphertext2 = EncryptMessage(message, params, &out_params);
6412 vector<uint8_t> iv2 = CopyIv(out_params);
6413 EXPECT_EQ(message.size(), ciphertext2.size());
6414
6415 // IVs should be random, so ciphertexts should differ.
6416 EXPECT_NE(ciphertext1, ciphertext2);
6417
6418 params.push_back(TAG_NONCE, iv1);
6419 string plaintext = DecryptMessage(ciphertext1, params);
6420 EXPECT_EQ(message, plaintext);
6421 }
6422
6423 /*
6424 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6425 *
6426 * Verifies that keymaster generates correct output on zero-input with
6427 * NonePadding mode
6428 */
TEST_P(EncryptionOperationsTest,AesCbcZeroInputSuccess)6429 TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6430 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6431 .Authorization(TAG_NO_AUTH_REQUIRED)
6432 .AesEncryptionKey(128)
6433 .BlockMode(BlockMode::CBC)
6434 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6435
6436 // Zero input message
6437 string message = "";
6438 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
6439 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
6440 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6441 AuthorizationSet out_params;
6442 string ciphertext1 = EncryptMessage(message, params, &out_params);
6443 vector<uint8_t> iv1 = CopyIv(out_params);
6444 if (padding == PaddingMode::NONE)
6445 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6446 else
6447 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6448
6449 out_params.Clear();
6450
6451 string ciphertext2 = EncryptMessage(message, params, &out_params);
6452 vector<uint8_t> iv2 = CopyIv(out_params);
6453 if (padding == PaddingMode::NONE)
6454 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6455 else
6456 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6457
6458 // IVs should be random
6459 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6460
6461 params.push_back(TAG_NONCE, iv1);
6462 string plaintext = DecryptMessage(ciphertext1, params);
6463 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6464 }
6465 }
6466
6467 /*
6468 * EncryptionOperationsTest.AesCallerNonce
6469 *
6470 * Verifies that AES caller-provided nonces work correctly.
6471 */
TEST_P(EncryptionOperationsTest,AesCallerNonce)6472 TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6473 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6474 .Authorization(TAG_NO_AUTH_REQUIRED)
6475 .AesEncryptionKey(128)
6476 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6477 .Authorization(TAG_CALLER_NONCE)
6478 .Padding(PaddingMode::NONE)));
6479
6480 string message = "12345678901234567890123456789012";
6481
6482 // Don't specify nonce, should get a random one.
6483 AuthorizationSetBuilder params =
6484 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6485 AuthorizationSet out_params;
6486 string ciphertext = EncryptMessage(message, params, &out_params);
6487 EXPECT_EQ(message.size(), ciphertext.size());
6488 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
6489
6490 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
6491 string plaintext = DecryptMessage(ciphertext, params);
6492 EXPECT_EQ(message, plaintext);
6493
6494 // Now specify a nonce, should also work.
6495 params = AuthorizationSetBuilder()
6496 .BlockMode(BlockMode::CBC)
6497 .Padding(PaddingMode::NONE)
6498 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6499 out_params.Clear();
6500 ciphertext = EncryptMessage(message, params, &out_params);
6501
6502 // Decrypt with correct nonce.
6503 plaintext = DecryptMessage(ciphertext, params);
6504 EXPECT_EQ(message, plaintext);
6505
6506 // Try with wrong nonce.
6507 params = AuthorizationSetBuilder()
6508 .BlockMode(BlockMode::CBC)
6509 .Padding(PaddingMode::NONE)
6510 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6511 plaintext = DecryptMessage(ciphertext, params);
6512 EXPECT_NE(message, plaintext);
6513 }
6514
6515 /*
6516 * EncryptionOperationsTest.AesCallerNonceProhibited
6517 *
6518 * Verifies that caller-provided nonces are not permitted when not specified in the key
6519 * authorizations.
6520 */
TEST_P(EncryptionOperationsTest,AesCallerNonceProhibited)6521 TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6522 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6523 .Authorization(TAG_NO_AUTH_REQUIRED)
6524 .AesEncryptionKey(128)
6525 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6526 .Padding(PaddingMode::NONE)));
6527
6528 string message = "12345678901234567890123456789012";
6529
6530 // Don't specify nonce, should get a random one.
6531 AuthorizationSetBuilder params =
6532 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6533 AuthorizationSet out_params;
6534 string ciphertext = EncryptMessage(message, params, &out_params);
6535 EXPECT_EQ(message.size(), ciphertext.size());
6536 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
6537
6538 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
6539 string plaintext = DecryptMessage(ciphertext, params);
6540 EXPECT_EQ(message, plaintext);
6541
6542 // Now specify a nonce, should fail
6543 params = AuthorizationSetBuilder()
6544 .BlockMode(BlockMode::CBC)
6545 .Padding(PaddingMode::NONE)
6546 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6547 out_params.Clear();
6548 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6549 }
6550
6551 /*
6552 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6553 *
6554 * Verifies that AES GCM mode works.
6555 */
TEST_P(EncryptionOperationsTest,AesGcmRoundTripSuccess)6556 TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6557 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6558 .Authorization(TAG_NO_AUTH_REQUIRED)
6559 .AesEncryptionKey(128)
6560 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6561 .Padding(PaddingMode::NONE)
6562 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6563
6564 string aad = "foobar";
6565 string message = "123456789012345678901234567890123456";
6566
6567 auto begin_params = AuthorizationSetBuilder()
6568 .BlockMode(BlockMode::GCM)
6569 .Padding(PaddingMode::NONE)
6570 .Authorization(TAG_MAC_LENGTH, 128);
6571
6572 // Encrypt
6573 AuthorizationSet begin_out_params;
6574 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6575 << "Begin encrypt";
6576 string ciphertext;
6577 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6578 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
6579 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6580
6581 // Grab nonce
6582 begin_params.push_back(begin_out_params);
6583
6584 // Decrypt.
6585 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6586 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6587 string plaintext;
6588 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
6589 EXPECT_EQ(message.length(), plaintext.length());
6590 EXPECT_EQ(message, plaintext);
6591 }
6592
6593 /*
6594 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6595 *
6596 * Verifies that AES GCM mode works, even when there's a long delay
6597 * between operations.
6598 */
TEST_P(EncryptionOperationsTest,AesGcmRoundTripWithDelaySuccess)6599 TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6600 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6601 .Authorization(TAG_NO_AUTH_REQUIRED)
6602 .AesEncryptionKey(128)
6603 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6604 .Padding(PaddingMode::NONE)
6605 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6606
6607 string aad = "foobar";
6608 string message = "123456789012345678901234567890123456";
6609
6610 auto begin_params = AuthorizationSetBuilder()
6611 .BlockMode(BlockMode::GCM)
6612 .Padding(PaddingMode::NONE)
6613 .Authorization(TAG_MAC_LENGTH, 128);
6614
6615 // Encrypt
6616 AuthorizationSet begin_out_params;
6617 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6618 << "Begin encrypt";
6619 string ciphertext;
6620 AuthorizationSet update_out_params;
6621 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6622 sleep(5);
6623 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
6624
6625 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6626
6627 // Grab nonce
6628 begin_params.push_back(begin_out_params);
6629
6630 // Decrypt.
6631 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6632 string plaintext;
6633 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6634 sleep(5);
6635 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6636 sleep(5);
6637 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6638 EXPECT_EQ(message.length(), plaintext.length());
6639 EXPECT_EQ(message, plaintext);
6640 }
6641
6642 /*
6643 * EncryptionOperationsTest.AesGcmDifferentNonces
6644 *
6645 * Verifies that encrypting the same data with different nonces produces different outputs.
6646 */
TEST_P(EncryptionOperationsTest,AesGcmDifferentNonces)6647 TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6648 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6649 .Authorization(TAG_NO_AUTH_REQUIRED)
6650 .AesEncryptionKey(128)
6651 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6652 .Padding(PaddingMode::NONE)
6653 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6654 .Authorization(TAG_CALLER_NONCE)));
6655
6656 string aad = "foobar";
6657 string message = "123456789012345678901234567890123456";
6658 string nonce1 = "000000000000";
6659 string nonce2 = "111111111111";
6660 string nonce3 = "222222222222";
6661
6662 string ciphertext1 =
6663 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6664 string ciphertext2 =
6665 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6666 string ciphertext3 =
6667 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6668
6669 ASSERT_NE(ciphertext1, ciphertext2);
6670 ASSERT_NE(ciphertext1, ciphertext3);
6671 ASSERT_NE(ciphertext2, ciphertext3);
6672 }
6673
6674 /*
6675 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6676 *
6677 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6678 */
TEST_P(EncryptionOperationsTest,AesGcmDifferentAutoNonces)6679 TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6680 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6681 .Authorization(TAG_NO_AUTH_REQUIRED)
6682 .AesEncryptionKey(128)
6683 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6684 .Padding(PaddingMode::NONE)
6685 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6686
6687 string aad = "foobar";
6688 string message = "123456789012345678901234567890123456";
6689
6690 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6691 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6692 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6693
6694 ASSERT_NE(ciphertext1, ciphertext2);
6695 ASSERT_NE(ciphertext1, ciphertext3);
6696 ASSERT_NE(ciphertext2, ciphertext3);
6697 }
6698
6699 /*
6700 * EncryptionOperationsTest.AesGcmTooShortTag
6701 *
6702 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6703 */
TEST_P(EncryptionOperationsTest,AesGcmTooShortTag)6704 TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6705 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6706 .Authorization(TAG_NO_AUTH_REQUIRED)
6707 .AesEncryptionKey(128)
6708 .BlockMode(BlockMode::GCM)
6709 .Padding(PaddingMode::NONE)
6710 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6711 string message = "123456789012345678901234567890123456";
6712 auto params = AuthorizationSetBuilder()
6713 .BlockMode(BlockMode::GCM)
6714 .Padding(PaddingMode::NONE)
6715 .Authorization(TAG_MAC_LENGTH, 96);
6716
6717 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6718 }
6719
6720 /*
6721 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6722 *
6723 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6724 */
TEST_P(EncryptionOperationsTest,AesGcmTooShortTagOnDecrypt)6725 TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6726 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6727 .Authorization(TAG_NO_AUTH_REQUIRED)
6728 .AesEncryptionKey(128)
6729 .BlockMode(BlockMode::GCM)
6730 .Padding(PaddingMode::NONE)
6731 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6732 string aad = "foobar";
6733 string message = "123456789012345678901234567890123456";
6734 auto params = AuthorizationSetBuilder()
6735 .BlockMode(BlockMode::GCM)
6736 .Padding(PaddingMode::NONE)
6737 .Authorization(TAG_MAC_LENGTH, 128);
6738
6739 // Encrypt
6740 AuthorizationSet begin_out_params;
6741 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6742 EXPECT_EQ(1U, begin_out_params.size());
6743 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
6744
6745 AuthorizationSet finish_out_params;
6746 string ciphertext;
6747 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6748 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
6749
6750 params = AuthorizationSetBuilder()
6751 .Authorizations(begin_out_params)
6752 .BlockMode(BlockMode::GCM)
6753 .Padding(PaddingMode::NONE)
6754 .Authorization(TAG_MAC_LENGTH, 96);
6755
6756 // Decrypt.
6757 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6758 }
6759
6760 /*
6761 * EncryptionOperationsTest.AesGcmCorruptKey
6762 *
6763 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6764 */
TEST_P(EncryptionOperationsTest,AesGcmCorruptKey)6765 TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6766 const uint8_t nonce_bytes[] = {
6767 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6768 };
6769 string nonce = make_string(nonce_bytes);
6770 const uint8_t ciphertext_bytes[] = {
6771 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6772 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6773 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6774 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6775 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6776 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6777 };
6778 string ciphertext = make_string(ciphertext_bytes);
6779
6780 auto params = AuthorizationSetBuilder()
6781 .BlockMode(BlockMode::GCM)
6782 .Padding(PaddingMode::NONE)
6783 .Authorization(TAG_MAC_LENGTH, 128)
6784 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6785
6786 auto import_params = AuthorizationSetBuilder()
6787 .Authorization(TAG_NO_AUTH_REQUIRED)
6788 .AesEncryptionKey(128)
6789 .BlockMode(BlockMode::GCM)
6790 .Padding(PaddingMode::NONE)
6791 .Authorization(TAG_CALLER_NONCE)
6792 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6793
6794 // Import correct key and decrypt
6795 const uint8_t key_bytes[] = {
6796 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6797 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6798 };
6799 string key = make_string(key_bytes);
6800 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6801 string plaintext = DecryptMessage(ciphertext, params);
6802 CheckedDeleteKey();
6803
6804 // Corrupt key and attempt to decrypt
6805 key[0] = 0;
6806 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6807 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6808 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6809 CheckedDeleteKey();
6810 }
6811
6812 /*
6813 * EncryptionOperationsTest.AesGcmAadNoData
6814 *
6815 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6816 * encrypt.
6817 */
TEST_P(EncryptionOperationsTest,AesGcmAadNoData)6818 TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6819 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6820 .Authorization(TAG_NO_AUTH_REQUIRED)
6821 .AesEncryptionKey(128)
6822 .BlockMode(BlockMode::GCM)
6823 .Padding(PaddingMode::NONE)
6824 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6825
6826 string aad = "1234567890123456";
6827 auto params = AuthorizationSetBuilder()
6828 .BlockMode(BlockMode::GCM)
6829 .Padding(PaddingMode::NONE)
6830 .Authorization(TAG_MAC_LENGTH, 128);
6831
6832 // Encrypt
6833 AuthorizationSet begin_out_params;
6834 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6835 string ciphertext;
6836 AuthorizationSet finish_out_params;
6837 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6838 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
6839 EXPECT_TRUE(finish_out_params.empty());
6840
6841 // Grab nonce
6842 params.push_back(begin_out_params);
6843
6844 // Decrypt.
6845 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6846 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6847 string plaintext;
6848 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
6849
6850 EXPECT_TRUE(finish_out_params.empty());
6851
6852 EXPECT_EQ("", plaintext);
6853 }
6854
6855 /*
6856 * EncryptionOperationsTest.AesGcmMultiPartAad
6857 *
6858 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6859 * chunks.
6860 */
TEST_P(EncryptionOperationsTest,AesGcmMultiPartAad)6861 TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6862 const size_t tag_bits = 128;
6863 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6864 .Authorization(TAG_NO_AUTH_REQUIRED)
6865 .AesEncryptionKey(128)
6866 .BlockMode(BlockMode::GCM)
6867 .Padding(PaddingMode::NONE)
6868 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6869
6870 string message = "123456789012345678901234567890123456";
6871 auto begin_params = AuthorizationSetBuilder()
6872 .BlockMode(BlockMode::GCM)
6873 .Padding(PaddingMode::NONE)
6874 .Authorization(TAG_MAC_LENGTH, tag_bits);
6875 AuthorizationSet begin_out_params;
6876
6877 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6878
6879 // No data, AAD only.
6880 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6881 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6882 string ciphertext;
6883 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6884 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
6885
6886 // Expect 128-bit (16-byte) tag appended to ciphertext.
6887 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
6888
6889 // Grab nonce.
6890 begin_params.push_back(begin_out_params);
6891
6892 // Decrypt
6893 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6894 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
6895 string plaintext;
6896 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
6897 EXPECT_EQ(message, plaintext);
6898 }
6899
6900 /*
6901 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6902 *
6903 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6904 */
TEST_P(EncryptionOperationsTest,AesGcmAadOutOfOrder)6905 TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6906 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6907 .Authorization(TAG_NO_AUTH_REQUIRED)
6908 .AesEncryptionKey(128)
6909 .BlockMode(BlockMode::GCM)
6910 .Padding(PaddingMode::NONE)
6911 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6912
6913 string message = "123456789012345678901234567890123456";
6914 auto begin_params = AuthorizationSetBuilder()
6915 .BlockMode(BlockMode::GCM)
6916 .Padding(PaddingMode::NONE)
6917 .Authorization(TAG_MAC_LENGTH, 128);
6918 AuthorizationSet begin_out_params;
6919
6920 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6921
6922 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6923 string ciphertext;
6924 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6925 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
6926
6927 // The failure should have already cancelled the operation.
6928 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6929
6930 op_ = {};
6931 }
6932
6933 /*
6934 * EncryptionOperationsTest.AesGcmBadAad
6935 *
6936 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6937 */
TEST_P(EncryptionOperationsTest,AesGcmBadAad)6938 TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6939 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6940 .Authorization(TAG_NO_AUTH_REQUIRED)
6941 .AesEncryptionKey(128)
6942 .BlockMode(BlockMode::GCM)
6943 .Padding(PaddingMode::NONE)
6944 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6945
6946 string message = "12345678901234567890123456789012";
6947 auto begin_params = AuthorizationSetBuilder()
6948 .BlockMode(BlockMode::GCM)
6949 .Padding(PaddingMode::NONE)
6950 .Authorization(TAG_MAC_LENGTH, 128);
6951
6952 // Encrypt
6953 AuthorizationSet begin_out_params;
6954 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6955 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
6956 string ciphertext;
6957 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
6958
6959 // Grab nonce
6960 begin_params.push_back(begin_out_params);
6961
6962 // Decrypt.
6963 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
6964 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
6965 string plaintext;
6966 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6967 }
6968
6969 /*
6970 * EncryptionOperationsTest.AesGcmWrongNonce
6971 *
6972 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6973 */
TEST_P(EncryptionOperationsTest,AesGcmWrongNonce)6974 TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6975 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6976 .Authorization(TAG_NO_AUTH_REQUIRED)
6977 .AesEncryptionKey(128)
6978 .BlockMode(BlockMode::GCM)
6979 .Padding(PaddingMode::NONE)
6980 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6981
6982 string message = "12345678901234567890123456789012";
6983 auto begin_params = AuthorizationSetBuilder()
6984 .BlockMode(BlockMode::GCM)
6985 .Padding(PaddingMode::NONE)
6986 .Authorization(TAG_MAC_LENGTH, 128);
6987
6988 // Encrypt
6989 AuthorizationSet begin_out_params;
6990 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6991 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
6992 string ciphertext;
6993 AuthorizationSet finish_out_params;
6994 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
6995
6996 // Wrong nonce
6997 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6998
6999 // Decrypt.
7000 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
7001 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
7002 string plaintext;
7003 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
7004
7005 // With wrong nonce, should have gotten garbage plaintext (or none).
7006 EXPECT_NE(message, plaintext);
7007 }
7008
7009 /*
7010 * EncryptionOperationsTest.AesGcmCorruptTag
7011 *
7012 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
7013 */
TEST_P(EncryptionOperationsTest,AesGcmCorruptTag)7014 TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
7015 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7016 .Authorization(TAG_NO_AUTH_REQUIRED)
7017 .AesEncryptionKey(128)
7018 .BlockMode(BlockMode::GCM)
7019 .Padding(PaddingMode::NONE)
7020 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
7021
7022 string aad = "1234567890123456";
7023 string message = "123456789012345678901234567890123456";
7024
7025 auto params = AuthorizationSetBuilder()
7026 .BlockMode(BlockMode::GCM)
7027 .Padding(PaddingMode::NONE)
7028 .Authorization(TAG_MAC_LENGTH, 128);
7029
7030 // Encrypt
7031 AuthorizationSet begin_out_params;
7032 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
7033 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
7034 string ciphertext;
7035 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
7036
7037 // Corrupt tag
7038 ++(*ciphertext.rbegin());
7039
7040 // Grab nonce
7041 params.push_back(begin_out_params);
7042
7043 // Decrypt.
7044 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
7045 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
7046 string plaintext;
7047 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
7048 }
7049
7050 /*
7051 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
7052 *
7053 * Verifies that 3DES is basically functional.
7054 */
TEST_P(EncryptionOperationsTest,TripleDesEcbRoundTripSuccess)7055 TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
7056 auto auths = AuthorizationSetBuilder()
7057 .TripleDesEncryptionKey(168)
7058 .BlockMode(BlockMode::ECB)
7059 .Authorization(TAG_NO_AUTH_REQUIRED)
7060 .Padding(PaddingMode::NONE);
7061
7062 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
7063 // Two-block message.
7064 string message = "1234567890123456";
7065 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7066 string ciphertext1 = EncryptMessage(message, inParams);
7067 EXPECT_EQ(message.size(), ciphertext1.size());
7068
7069 string ciphertext2 = EncryptMessage(string(message), inParams);
7070 EXPECT_EQ(message.size(), ciphertext2.size());
7071
7072 // ECB is deterministic.
7073 EXPECT_EQ(ciphertext1, ciphertext2);
7074
7075 string plaintext = DecryptMessage(ciphertext1, inParams);
7076 EXPECT_EQ(message, plaintext);
7077 }
7078
7079 /*
7080 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
7081 *
7082 * Verifies that CBC keys reject ECB usage.
7083 */
TEST_P(EncryptionOperationsTest,TripleDesEcbNotAuthorized)7084 TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
7085 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7086 .TripleDesEncryptionKey(168)
7087 .BlockMode(BlockMode::CBC)
7088 .Authorization(TAG_NO_AUTH_REQUIRED)
7089 .Padding(PaddingMode::NONE)));
7090
7091 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7092 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7093 }
7094
7095 /*
7096 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
7097 *
7098 * Tests ECB mode with PKCS#7 padding, various message sizes.
7099 */
TEST_P(EncryptionOperationsTest,TripleDesEcbPkcs7Padding)7100 TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
7101 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7102 .TripleDesEncryptionKey(168)
7103 .BlockMode(BlockMode::ECB)
7104 .Authorization(TAG_NO_AUTH_REQUIRED)
7105 .Padding(PaddingMode::PKCS7)));
7106
7107 for (size_t i = 0; i < 32; ++i) {
7108 SCOPED_TRACE(testing::Message() << "msg size=" << i);
7109 string message(i, 'a');
7110 auto inParams =
7111 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7112 string ciphertext = EncryptMessage(message, inParams);
7113 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7114 string plaintext = DecryptMessage(ciphertext, inParams);
7115 EXPECT_EQ(message, plaintext);
7116 }
7117 }
7118
7119 /*
7120 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
7121 *
7122 * Verifies that keys configured for no padding reject PKCS7 padding
7123 */
TEST_P(EncryptionOperationsTest,TripleDesEcbNoPaddingKeyWithPkcs7Padding)7124 TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
7125 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7126 .TripleDesEncryptionKey(168)
7127 .BlockMode(BlockMode::ECB)
7128 .Authorization(TAG_NO_AUTH_REQUIRED)
7129 .Padding(PaddingMode::NONE)));
7130 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
7131 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
7132 }
7133
7134 /*
7135 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
7136 *
7137 * Verifies that corrupted padding is detected.
7138 */
TEST_P(EncryptionOperationsTest,TripleDesEcbPkcs7PaddingCorrupted)7139 TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7140 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7141 .TripleDesEncryptionKey(168)
7142 .BlockMode(BlockMode::ECB)
7143 .Authorization(TAG_NO_AUTH_REQUIRED)
7144 .Padding(PaddingMode::PKCS7)));
7145
7146 string message = "a";
7147 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7148 EXPECT_EQ(8U, ciphertext.size());
7149 EXPECT_NE(ciphertext, message);
7150
7151 AuthorizationSetBuilder begin_params;
7152 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7153 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
7154
7155 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7156 ++ciphertext[ciphertext.size() / 2];
7157
7158 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
7159 string plaintext;
7160 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7161 ErrorCode error = Finish(&plaintext);
7162 if (error == ErrorCode::INVALID_ARGUMENT) {
7163 // This is the expected error, we can exit the test now.
7164 return;
7165 } else {
7166 // Very small chance we got valid decryption, so try again.
7167 ASSERT_EQ(error, ErrorCode::OK);
7168 }
7169 }
7170 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
7171 }
7172
7173 struct TripleDesTestVector {
7174 const char* name;
7175 const KeyPurpose purpose;
7176 const BlockMode block_mode;
7177 const PaddingMode padding_mode;
7178 const char* key;
7179 const char* iv;
7180 const char* input;
7181 const char* output;
7182 };
7183
7184 // These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7185 // of the NIST vectors are multiples of the block size.
7186 static const TripleDesTestVector kTripleDesTestVectors[] = {
7187 {
7188 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7189 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7190 "", // IV
7191 "329d86bdf1bc5af4", // input
7192 "d946c2756d78633f", // output
7193 },
7194 {
7195 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7196 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7197 "", // IV
7198 "6b1540781b01ce1997adae102dbf3c5b", // input
7199 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7200 },
7201 {
7202 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7203 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7204 "", // IV
7205 "6daad94ce08acfe7", // input
7206 "660e7d32dcc90e79", // output
7207 },
7208 {
7209 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7210 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7211 "", // IV
7212 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7213 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7214 },
7215 {
7216 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7217 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7218 "43f791134c5647ba", // IV
7219 "dcc153cef81d6f24", // input
7220 "92538bd8af18d3ba", // output
7221 },
7222 {
7223 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7224 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7225 "c2e999cb6249023c", // IV
7226 "c689aee38a301bb316da75db36f110b5", // input
7227 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7228 },
7229 {
7230 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7231 PaddingMode::PKCS7,
7232 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7233 "c2e999cb6249023c", // IV
7234 "c689aee38a301bb316da75db36f110b500", // input
7235 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7236 },
7237 {
7238 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7239 PaddingMode::PKCS7,
7240 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7241 "c2e999cb6249023c", // IV
7242 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7243 "c689aee38a301bb316da75db36f110b500", // output
7244 },
7245 {
7246 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7247 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7248 "41746c7e442d3681", // IV
7249 "c53a7b0ec40600fe", // input
7250 "d4f00eb455de1034", // output
7251 },
7252 {
7253 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7254 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7255 "3982bc02c3727d45", // IV
7256 "6006f10adef52991fcc777a1238bbb65", // input
7257 "edae09288e9e3bc05746d872b48e3b29", // output
7258 },
7259 };
7260
7261 /*
7262 * EncryptionOperationsTest.TripleDesTestVector
7263 *
7264 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7265 */
TEST_P(EncryptionOperationsTest,TripleDesTestVector)7266 TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7267 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7268 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7269 SCOPED_TRACE(test->name);
7270 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7271 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7272 hex2str(test->output));
7273 }
7274 }
7275
7276 /*
7277 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7278 *
7279 * Validates CBC mode functionality.
7280 */
TEST_P(EncryptionOperationsTest,TripleDesCbcRoundTripSuccess)7281 TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7282 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7283 .TripleDesEncryptionKey(168)
7284 .BlockMode(BlockMode::CBC)
7285 .Authorization(TAG_NO_AUTH_REQUIRED)
7286 .Padding(PaddingMode::NONE)));
7287
7288 ASSERT_GT(key_blob_.size(), 0U);
7289
7290 // Four-block message.
7291 string message = "12345678901234561234567890123456";
7292 vector<uint8_t> iv1;
7293 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7294 EXPECT_EQ(message.size(), ciphertext1.size());
7295
7296 vector<uint8_t> iv2;
7297 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7298 EXPECT_EQ(message.size(), ciphertext2.size());
7299
7300 // IVs should be random, so ciphertexts should differ.
7301 EXPECT_NE(iv1, iv2);
7302 EXPECT_NE(ciphertext1, ciphertext2);
7303
7304 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7305 EXPECT_EQ(message, plaintext);
7306 }
7307
7308 /*
7309 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7310 *
7311 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7312 */
TEST_P(EncryptionOperationsTest,TripleDesInvalidCallerIv)7313 TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7314 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7315 .TripleDesEncryptionKey(168)
7316 .BlockMode(BlockMode::CBC)
7317 .Authorization(TAG_NO_AUTH_REQUIRED)
7318 .Authorization(TAG_CALLER_NONCE)
7319 .Padding(PaddingMode::NONE)));
7320 auto params = AuthorizationSetBuilder()
7321 .BlockMode(BlockMode::CBC)
7322 .Padding(PaddingMode::NONE)
7323 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7324 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7325 }
7326
7327 /*
7328 * EncryptionOperationsTest.TripleDesCallerIv
7329 *
7330 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7331 */
TEST_P(EncryptionOperationsTest,TripleDesCallerIv)7332 TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7333 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7334 .TripleDesEncryptionKey(168)
7335 .BlockMode(BlockMode::CBC)
7336 .Authorization(TAG_NO_AUTH_REQUIRED)
7337 .Authorization(TAG_CALLER_NONCE)
7338 .Padding(PaddingMode::NONE)));
7339 string message = "1234567890123456";
7340 vector<uint8_t> iv;
7341 // Don't specify IV, should get a random one.
7342 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7343 EXPECT_EQ(message.size(), ciphertext1.size());
7344 EXPECT_EQ(8U, iv.size());
7345
7346 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7347 EXPECT_EQ(message, plaintext);
7348
7349 // Now specify an IV, should also work.
7350 iv = AidlBuf("abcdefgh");
7351 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7352
7353 // Decrypt with correct IV.
7354 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7355 EXPECT_EQ(message, plaintext);
7356
7357 // Now try with wrong IV.
7358 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7359 EXPECT_NE(message, plaintext);
7360 }
7361
7362 /*
7363 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7364 *
7365 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
7366 */
TEST_P(EncryptionOperationsTest,TripleDesCallerNonceProhibited)7367 TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7368 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7369 .TripleDesEncryptionKey(168)
7370 .BlockMode(BlockMode::CBC)
7371 .Authorization(TAG_NO_AUTH_REQUIRED)
7372 .Padding(PaddingMode::NONE)));
7373
7374 string message = "12345678901234567890123456789012";
7375 vector<uint8_t> iv;
7376 // Don't specify nonce, should get a random one.
7377 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7378 EXPECT_EQ(message.size(), ciphertext1.size());
7379 EXPECT_EQ(8U, iv.size());
7380
7381 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7382 EXPECT_EQ(message, plaintext);
7383
7384 // Now specify a nonce, should fail.
7385 auto input_params = AuthorizationSetBuilder()
7386 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7387 .BlockMode(BlockMode::CBC)
7388 .Padding(PaddingMode::NONE);
7389 AuthorizationSet output_params;
7390 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7391 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7392 }
7393
7394 /*
7395 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7396 *
7397 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7398 */
TEST_P(EncryptionOperationsTest,TripleDesCbcNotAuthorized)7399 TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7400 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7401 .TripleDesEncryptionKey(168)
7402 .BlockMode(BlockMode::ECB)
7403 .Authorization(TAG_NO_AUTH_REQUIRED)
7404 .Padding(PaddingMode::NONE)));
7405 // Two-block message.
7406 string message = "1234567890123456";
7407 auto begin_params =
7408 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7409 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7410 }
7411
7412 /*
7413 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
7414 *
7415 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7416 */
TEST_P(EncryptionOperationsTest,TripleDesEcbCbcNoPaddingWrongInputSize)7417 TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7418 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
7419 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
7420 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7421 .TripleDesEncryptionKey(168)
7422 .BlockMode(blockMode)
7423 .Authorization(TAG_NO_AUTH_REQUIRED)
7424 .Padding(PaddingMode::NONE)));
7425 // Message is slightly shorter than two blocks.
7426 string message = "123456789012345";
7427
7428 auto begin_params =
7429 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7430 AuthorizationSet output_params;
7431 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
7432 string ciphertext;
7433 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7434
7435 CheckedDeleteKey();
7436 }
7437 }
7438
7439 /*
7440 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7441 *
7442 * Verifies that PKCS7 padding works correctly in CBC mode.
7443 */
TEST_P(EncryptionOperationsTest,TripleDesCbcPkcs7Padding)7444 TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7445 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7446 .TripleDesEncryptionKey(168)
7447 .BlockMode(BlockMode::CBC)
7448 .Authorization(TAG_NO_AUTH_REQUIRED)
7449 .Padding(PaddingMode::PKCS7)));
7450
7451 // Try various message lengths; all should work.
7452 for (size_t i = 0; i <= 32; i++) {
7453 SCOPED_TRACE(testing::Message() << "i = " << i);
7454 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7455 string message(i, '\t');
7456 vector<uint8_t> iv;
7457 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7458 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7459 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7460 EXPECT_EQ(message, plaintext);
7461 }
7462 }
7463
7464 /*
7465 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7466 *
7467 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7468 */
TEST_P(EncryptionOperationsTest,TripleDesCbcNoPaddingKeyWithPkcs7Padding)7469 TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7470 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7471 .TripleDesEncryptionKey(168)
7472 .BlockMode(BlockMode::CBC)
7473 .Authorization(TAG_NO_AUTH_REQUIRED)
7474 .Padding(PaddingMode::NONE)));
7475
7476 // Try various message lengths; all should fail.
7477 for (size_t i = 0; i <= 32; i++) {
7478 SCOPED_TRACE(testing::Message() << "i = " << i);
7479 auto begin_params =
7480 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7481 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7482 }
7483 }
7484
7485 /*
7486 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7487 *
7488 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7489 */
TEST_P(EncryptionOperationsTest,TripleDesCbcPkcs7PaddingCorrupted)7490 TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7491 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7492 .TripleDesEncryptionKey(168)
7493 .BlockMode(BlockMode::CBC)
7494 .Authorization(TAG_NO_AUTH_REQUIRED)
7495 .Padding(PaddingMode::PKCS7)));
7496
7497 string message = "a";
7498 vector<uint8_t> iv;
7499 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7500 EXPECT_EQ(8U, ciphertext.size());
7501 EXPECT_NE(ciphertext, message);
7502
7503 auto begin_params = AuthorizationSetBuilder()
7504 .BlockMode(BlockMode::CBC)
7505 .Padding(PaddingMode::PKCS7)
7506 .Authorization(TAG_NONCE, iv);
7507
7508 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7509 SCOPED_TRACE(testing::Message() << "i = " << i);
7510 ++ciphertext[ciphertext.size() / 2];
7511 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
7512 string plaintext;
7513 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7514 ErrorCode error = Finish(&plaintext);
7515 if (error == ErrorCode::INVALID_ARGUMENT) {
7516 // This is the expected error, we can exit the test now.
7517 return;
7518 } else {
7519 // Very small chance we got valid decryption, so try again.
7520 ASSERT_EQ(error, ErrorCode::OK);
7521 }
7522 }
7523 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
7524 }
7525
7526 /*
7527 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7528 *
7529 * Verifies that 3DES CBC works with many different input sizes.
7530 */
TEST_P(EncryptionOperationsTest,TripleDesCbcIncrementalNoPadding)7531 TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7532 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7533 .TripleDesEncryptionKey(168)
7534 .BlockMode(BlockMode::CBC)
7535 .Authorization(TAG_NO_AUTH_REQUIRED)
7536 .Padding(PaddingMode::NONE)));
7537
7538 int increment = 7;
7539 string message(240, 'a');
7540 AuthorizationSet input_params =
7541 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7542 AuthorizationSet output_params;
7543 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7544
7545 string ciphertext;
7546 for (size_t i = 0; i < message.size(); i += increment)
7547 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
7548 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7549 EXPECT_EQ(message.size(), ciphertext.size());
7550
7551 // Move TAG_NONCE into input_params
7552 input_params = output_params;
7553 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7554 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7555 output_params.Clear();
7556
7557 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
7558 string plaintext;
7559 for (size_t i = 0; i < ciphertext.size(); i += increment)
7560 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
7561 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7562 EXPECT_EQ(ciphertext.size(), plaintext.size());
7563 EXPECT_EQ(message, plaintext);
7564 }
7565
7566 INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7567
7568 typedef KeyMintAidlTestBase MaxOperationsTest;
7569
7570 /*
7571 * MaxOperationsTest.TestLimitAes
7572 *
7573 * Verifies that the max uses per boot tag works correctly with AES keys.
7574 */
TEST_P(MaxOperationsTest,TestLimitAes)7575 TEST_P(MaxOperationsTest, TestLimitAes) {
7576 if (SecLevel() == SecurityLevel::STRONGBOX) {
7577 GTEST_SKIP() << "Test not applicable to StrongBox device";
7578 }
7579
7580 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7581 .Authorization(TAG_NO_AUTH_REQUIRED)
7582 .AesEncryptionKey(128)
7583 .EcbMode()
7584 .Padding(PaddingMode::NONE)
7585 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7586
7587 string message = "1234567890123456";
7588
7589 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7590
7591 EncryptMessage(message, params);
7592 EncryptMessage(message, params);
7593 EncryptMessage(message, params);
7594
7595 // Fourth time should fail.
7596 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7597 }
7598
7599 /*
7600 * MaxOperationsTest.TestLimitRsa
7601 *
7602 * Verifies that the max uses per boot tag works correctly with RSA keys.
7603 */
TEST_P(MaxOperationsTest,TestLimitRsa)7604 TEST_P(MaxOperationsTest, TestLimitRsa) {
7605 if (SecLevel() == SecurityLevel::STRONGBOX) {
7606 GTEST_SKIP() << "Test not applicable to StrongBox device";
7607 }
7608
7609 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7610 .Authorization(TAG_NO_AUTH_REQUIRED)
7611 .RsaSigningKey(1024, 65537)
7612 .NoDigestOrPadding()
7613 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7614 .SetDefaultValidity()));
7615
7616 string message = "1234567890123456";
7617
7618 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7619
7620 SignMessage(message, params);
7621 SignMessage(message, params);
7622 SignMessage(message, params);
7623
7624 // Fourth time should fail.
7625 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7626 }
7627
7628 INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7629
7630 typedef KeyMintAidlTestBase UsageCountLimitTest;
7631
7632 /*
7633 * UsageCountLimitTest.TestSingleUseAes
7634 *
7635 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
7636 */
TEST_P(UsageCountLimitTest,TestSingleUseAes)7637 TEST_P(UsageCountLimitTest, TestSingleUseAes) {
7638 if (SecLevel() == SecurityLevel::STRONGBOX) {
7639 GTEST_SKIP() << "Test not applicable to StrongBox device";
7640 }
7641
7642 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7643 .Authorization(TAG_NO_AUTH_REQUIRED)
7644 .AesEncryptionKey(128)
7645 .EcbMode()
7646 .Padding(PaddingMode::NONE)
7647 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7648
7649 // Check the usage count limit tag appears in the authorizations.
7650 AuthorizationSet auths;
7651 for (auto& entry : key_characteristics_) {
7652 auths.push_back(AuthorizationSet(entry.authorizations));
7653 }
7654 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7655 << "key usage count limit " << 1U << " missing";
7656
7657 string message = "1234567890123456";
7658 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7659
7660 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7661 AuthorizationSet keystore_auths =
7662 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7663
7664 // First usage of AES key should work.
7665 EncryptMessage(message, params);
7666
7667 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7668 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7669 // must be invalidated from secure storage (such as RPMB partition).
7670 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7671 } else {
7672 // Usage count limit tag is enforced by keystore, keymint does nothing.
7673 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
7674 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
7675 }
7676 }
7677
7678 /*
7679 * UsageCountLimitTest.TestLimitedUseAes
7680 *
7681 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
7682 */
TEST_P(UsageCountLimitTest,TestLimitedUseAes)7683 TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
7684 if (SecLevel() == SecurityLevel::STRONGBOX) {
7685 GTEST_SKIP() << "Test not applicable to StrongBox device";
7686 }
7687
7688 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7689 .Authorization(TAG_NO_AUTH_REQUIRED)
7690 .AesEncryptionKey(128)
7691 .EcbMode()
7692 .Padding(PaddingMode::NONE)
7693 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7694
7695 // Check the usage count limit tag appears in the authorizations.
7696 AuthorizationSet auths;
7697 for (auto& entry : key_characteristics_) {
7698 auths.push_back(AuthorizationSet(entry.authorizations));
7699 }
7700 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7701 << "key usage count limit " << 3U << " missing";
7702
7703 string message = "1234567890123456";
7704 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7705
7706 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7707 AuthorizationSet keystore_auths =
7708 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7709
7710 EncryptMessage(message, params);
7711 EncryptMessage(message, params);
7712 EncryptMessage(message, params);
7713
7714 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7715 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7716 // must be invalidated from secure storage (such as RPMB partition).
7717 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7718 } else {
7719 // Usage count limit tag is enforced by keystore, keymint does nothing.
7720 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
7721 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
7722 }
7723 }
7724
7725 /*
7726 * UsageCountLimitTest.TestSingleUseRsa
7727 *
7728 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7729 */
TEST_P(UsageCountLimitTest,TestSingleUseRsa)7730 TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
7731 if (SecLevel() == SecurityLevel::STRONGBOX) {
7732 GTEST_SKIP() << "Test not applicable to StrongBox device";
7733 }
7734
7735 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7736 .Authorization(TAG_NO_AUTH_REQUIRED)
7737 .RsaSigningKey(1024, 65537)
7738 .NoDigestOrPadding()
7739 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7740 .SetDefaultValidity()));
7741
7742 // Check the usage count limit tag appears in the authorizations.
7743 AuthorizationSet auths;
7744 for (auto& entry : key_characteristics_) {
7745 auths.push_back(AuthorizationSet(entry.authorizations));
7746 }
7747 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7748 << "key usage count limit " << 1U << " missing";
7749
7750 string message = "1234567890123456";
7751 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7752
7753 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7754 AuthorizationSet keystore_auths =
7755 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7756
7757 // First usage of RSA key should work.
7758 SignMessage(message, params);
7759
7760 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7761 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7762 // must be invalidated from secure storage (such as RPMB partition).
7763 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7764 } else {
7765 // Usage count limit tag is enforced by keystore, keymint does nothing.
7766 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
7767 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
7768 }
7769 }
7770
7771 /*
7772 * UsageCountLimitTest.TestLimitUseRsa
7773 *
7774 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7775 */
TEST_P(UsageCountLimitTest,TestLimitUseRsa)7776 TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
7777 if (SecLevel() == SecurityLevel::STRONGBOX) {
7778 GTEST_SKIP() << "Test not applicable to StrongBox device";
7779 }
7780
7781 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7782 .Authorization(TAG_NO_AUTH_REQUIRED)
7783 .RsaSigningKey(1024, 65537)
7784 .NoDigestOrPadding()
7785 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7786 .SetDefaultValidity()));
7787
7788 // Check the usage count limit tag appears in the authorizations.
7789 AuthorizationSet auths;
7790 for (auto& entry : key_characteristics_) {
7791 auths.push_back(AuthorizationSet(entry.authorizations));
7792 }
7793 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7794 << "key usage count limit " << 3U << " missing";
7795
7796 string message = "1234567890123456";
7797 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7798
7799 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7800 AuthorizationSet keystore_auths =
7801 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7802
7803 SignMessage(message, params);
7804 SignMessage(message, params);
7805 SignMessage(message, params);
7806
7807 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7808 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7809 // must be invalidated from secure storage (such as RPMB partition).
7810 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7811 } else {
7812 // Usage count limit tag is enforced by keystore, keymint does nothing.
7813 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
7814 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
7815 }
7816 }
7817
7818 /*
7819 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7820 *
7821 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7822 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7823 * in hardware.
7824 */
TEST_P(UsageCountLimitTest,TestSingleUseKeyAndRollbackResistance)7825 TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
7826 auto error = GenerateKey(AuthorizationSetBuilder()
7827 .RsaSigningKey(2048, 65537)
7828 .Digest(Digest::NONE)
7829 .Padding(PaddingMode::NONE)
7830 .Authorization(TAG_NO_AUTH_REQUIRED)
7831 .Authorization(TAG_ROLLBACK_RESISTANCE)
7832 .SetDefaultValidity());
7833 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7834 GTEST_SKIP() << "Rollback resistance not supported";
7835 }
7836
7837 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7838 ASSERT_EQ(ErrorCode::OK, error);
7839 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7840 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7841 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7842
7843 // The KeyMint should also enforce single use key in hardware when it supports rollback
7844 // resistance.
7845 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7846 .Authorization(TAG_NO_AUTH_REQUIRED)
7847 .RsaSigningKey(1024, 65537)
7848 .NoDigestOrPadding()
7849 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7850 .SetDefaultValidity()));
7851
7852 // Check the usage count limit tag appears in the hardware authorizations.
7853 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7854 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7855 << "key usage count limit " << 1U << " missing";
7856
7857 string message = "1234567890123456";
7858 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7859
7860 // First usage of RSA key should work.
7861 SignMessage(message, params);
7862
7863 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7864 // must be invalidated from secure storage (such as RPMB partition).
7865 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7866 }
7867
7868 INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7869
7870 typedef KeyMintAidlTestBase GetHardwareInfoTest;
7871
TEST_P(GetHardwareInfoTest,GetHardwareInfo)7872 TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7873 // Retrieving hardware info should give the same result each time.
7874 KeyMintHardwareInfo info;
7875 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7876 KeyMintHardwareInfo info2;
7877 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7878 EXPECT_EQ(info, info2);
7879 }
7880
7881 INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7882
7883 typedef KeyMintAidlTestBase AddEntropyTest;
7884
7885 /*
7886 * AddEntropyTest.AddEntropy
7887 *
7888 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7889 * is actually added.
7890 */
TEST_P(AddEntropyTest,AddEntropy)7891 TEST_P(AddEntropyTest, AddEntropy) {
7892 string data = "foo";
7893 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7894 }
7895
7896 /*
7897 * AddEntropyTest.AddEmptyEntropy
7898 *
7899 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7900 */
TEST_P(AddEntropyTest,AddEmptyEntropy)7901 TEST_P(AddEntropyTest, AddEmptyEntropy) {
7902 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7903 }
7904
7905 /*
7906 * AddEntropyTest.AddLargeEntropy
7907 *
7908 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7909 */
TEST_P(AddEntropyTest,AddLargeEntropy)7910 TEST_P(AddEntropyTest, AddLargeEntropy) {
7911 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7912 }
7913
7914 /*
7915 * AddEntropyTest.AddTooLargeEntropy
7916 *
7917 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7918 */
TEST_P(AddEntropyTest,AddTooLargeEntropy)7919 TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7920 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7921 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7922 }
7923
7924 INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7925
7926 typedef KeyMintAidlTestBase KeyDeletionTest;
7927
7928 /**
7929 * KeyDeletionTest.DeleteKey
7930 *
7931 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7932 * valid key blob.
7933 */
TEST_P(KeyDeletionTest,DeleteKey)7934 TEST_P(KeyDeletionTest, DeleteKey) {
7935 auto error = GenerateKey(AuthorizationSetBuilder()
7936 .RsaSigningKey(2048, 65537)
7937 .Digest(Digest::NONE)
7938 .Padding(PaddingMode::NONE)
7939 .Authorization(TAG_NO_AUTH_REQUIRED)
7940 .Authorization(TAG_ROLLBACK_RESISTANCE)
7941 .SetDefaultValidity());
7942 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7943 GTEST_SKIP() << "Rollback resistance not supported";
7944 }
7945
7946 // Delete must work if rollback protection is implemented
7947 ASSERT_EQ(ErrorCode::OK, error);
7948 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7949 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7950
7951 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
7952
7953 string message = "12345678901234567890123456789012";
7954 AuthorizationSet begin_out_params;
7955 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7956 Begin(KeyPurpose::SIGN, key_blob_,
7957 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7958 &begin_out_params));
7959 AbortIfNeeded();
7960 key_blob_ = AidlBuf();
7961 }
7962
7963 /**
7964 * KeyDeletionTest.DeleteInvalidKey
7965 *
7966 * This test checks that the HAL excepts invalid key blobs..
7967 */
TEST_P(KeyDeletionTest,DeleteInvalidKey)7968 TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7969 // Generate key just to check if rollback protection is implemented
7970 auto error = GenerateKey(AuthorizationSetBuilder()
7971 .RsaSigningKey(2048, 65537)
7972 .Digest(Digest::NONE)
7973 .Padding(PaddingMode::NONE)
7974 .Authorization(TAG_NO_AUTH_REQUIRED)
7975 .Authorization(TAG_ROLLBACK_RESISTANCE)
7976 .SetDefaultValidity());
7977 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7978 GTEST_SKIP() << "Rollback resistance not supported";
7979 }
7980
7981 // Delete must work if rollback protection is implemented
7982 ASSERT_EQ(ErrorCode::OK, error);
7983 AuthorizationSet enforced(SecLevelAuthorizations());
7984 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
7985
7986 // Delete the key we don't care about the result at this point.
7987 DeleteKey();
7988
7989 // Now create an invalid key blob and delete it.
7990 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
7991
7992 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7993 }
7994
7995 /**
7996 * KeyDeletionTest.DeleteAllKeys
7997 *
7998 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7999 *
8000 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
8001 * FBE/FDE encryption keys, which means that the device will not even boot until after the
8002 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
8003 * been provisioned. Use this test only on dedicated testing devices that have no valuable
8004 * credentials stored in Keystore/Keymint.
8005 */
TEST_P(KeyDeletionTest,DeleteAllKeys)8006 TEST_P(KeyDeletionTest, DeleteAllKeys) {
8007 if (!arm_deleteAllKeys) {
8008 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
8009 return;
8010 }
8011 auto error = GenerateKey(AuthorizationSetBuilder()
8012 .RsaSigningKey(2048, 65537)
8013 .Digest(Digest::NONE)
8014 .Padding(PaddingMode::NONE)
8015 .Authorization(TAG_NO_AUTH_REQUIRED)
8016 .Authorization(TAG_ROLLBACK_RESISTANCE)
8017 .SetDefaultValidity());
8018 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
8019 GTEST_SKIP() << "Rollback resistance not supported";
8020 }
8021
8022 // Delete must work if rollback protection is implemented
8023 ASSERT_EQ(ErrorCode::OK, error);
8024 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
8025 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
8026
8027 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
8028
8029 string message = "12345678901234567890123456789012";
8030 AuthorizationSet begin_out_params;
8031
8032 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
8033 Begin(KeyPurpose::SIGN, key_blob_,
8034 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
8035 &begin_out_params));
8036 AbortIfNeeded();
8037 key_blob_ = AidlBuf();
8038 }
8039
8040 INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
8041
8042 typedef KeyMintAidlTestBase KeyUpgradeTest;
8043
8044 /**
8045 * KeyUpgradeTest.UpgradeInvalidKey
8046 *
8047 * This test checks that the HAL excepts invalid key blobs..
8048 */
TEST_P(KeyUpgradeTest,UpgradeInvalidKey)8049 TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
8050 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
8051
8052 std::vector<uint8_t> new_blob;
8053 Status result = keymint_->upgradeKey(key_blob,
8054 AuthorizationSetBuilder()
8055 .Authorization(TAG_APPLICATION_ID, "clientid")
8056 .Authorization(TAG_APPLICATION_DATA, "appdata")
8057 .vector_data(),
8058 &new_blob);
8059 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
8060 }
8061
8062 INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
8063
8064 using UpgradeKeyTest = KeyMintAidlTestBase;
8065
8066 /*
8067 * UpgradeKeyTest.UpgradeKey
8068 *
8069 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
8070 */
TEST_P(UpgradeKeyTest,UpgradeKey)8071 TEST_P(UpgradeKeyTest, UpgradeKey) {
8072 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8073 .AesEncryptionKey(128)
8074 .Padding(PaddingMode::NONE)
8075 .Authorization(TAG_NO_AUTH_REQUIRED)));
8076
8077 auto result = UpgradeKey(key_blob_);
8078
8079 // Key doesn't need upgrading. Should get okay, but no new key blob.
8080 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
8081 }
8082
8083 INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
8084
8085 using ClearOperationsTest = KeyMintAidlTestBase;
8086
8087 /*
8088 * ClearSlotsTest.TooManyOperations
8089 *
8090 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
8091 * operations are started without being finished or aborted. Also verifies
8092 * that aborting the operations clears the operations.
8093 *
8094 */
TEST_P(ClearOperationsTest,TooManyOperations)8095 TEST_P(ClearOperationsTest, TooManyOperations) {
8096 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8097 .Authorization(TAG_NO_AUTH_REQUIRED)
8098 .RsaEncryptionKey(2048, 65537)
8099 .Padding(PaddingMode::NONE)
8100 .SetDefaultValidity()));
8101
8102 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
8103 constexpr size_t max_operations = 100; // set to arbituary large number
8104 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
8105 AuthorizationSet out_params;
8106 ErrorCode result;
8107 size_t i;
8108
8109 for (i = 0; i < max_operations; i++) {
8110 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
8111 if (ErrorCode::OK != result) {
8112 break;
8113 }
8114 }
8115 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
8116 // Try again just in case there's a weird overflow bug
8117 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
8118 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
8119 for (size_t j = 0; j < i; j++) {
8120 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
8121 << "Aboort failed for i = " << j << std::endl;
8122 }
8123 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
8124 AbortIfNeeded();
8125 }
8126
8127 INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
8128
8129 typedef KeyMintAidlTestBase TransportLimitTest;
8130
8131 /*
8132 * TransportLimitTest.LargeFinishInput
8133 *
8134 * Verifies that passing input data to finish succeeds as expected.
8135 */
TEST_P(TransportLimitTest,LargeFinishInput)8136 TEST_P(TransportLimitTest, LargeFinishInput) {
8137 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8138 .Authorization(TAG_NO_AUTH_REQUIRED)
8139 .AesEncryptionKey(128)
8140 .BlockMode(BlockMode::ECB)
8141 .Padding(PaddingMode::NONE)));
8142
8143 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
8144 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
8145 auto cipher_params =
8146 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8147
8148 AuthorizationSet out_params;
8149 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
8150
8151 string plain_message = std::string(1 << msg_size, 'x');
8152 string encrypted_message;
8153 auto rc = Finish(plain_message, &encrypted_message);
8154
8155 EXPECT_EQ(ErrorCode::OK, rc);
8156 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8157 << "Encrypt finish returned OK, but did not consume all of the given input";
8158 cipher_params.push_back(out_params);
8159
8160 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
8161
8162 string decrypted_message;
8163 rc = Finish(encrypted_message, &decrypted_message);
8164 EXPECT_EQ(ErrorCode::OK, rc);
8165 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8166 << "Decrypt finish returned OK, did not consume all of the given input";
8167 }
8168 }
8169
8170 INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8171
EcdhCurveToOpenSslCurveName(EcCurve curve)8172 static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
8173 switch (curve) {
8174 case EcCurve::P_224:
8175 return NID_secp224r1;
8176 case EcCurve::P_256:
8177 return NID_X9_62_prime256v1;
8178 case EcCurve::P_384:
8179 return NID_secp384r1;
8180 case EcCurve::P_521:
8181 return NID_secp521r1;
8182 case EcCurve::CURVE_25519:
8183 return NID_X25519;
8184 }
8185 }
8186
8187 class KeyAgreementTest : public KeyMintAidlTestBase {
8188 protected:
GenerateLocalEcKey(EcCurve localCurve,EVP_PKEY_Ptr * localPrivKey,std::vector<uint8_t> * localPublicKey)8189 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8190 std::vector<uint8_t>* localPublicKey) {
8191 // Generate EC key locally (with access to private key material)
8192 if (localCurve == EcCurve::CURVE_25519) {
8193 uint8_t privKeyData[32];
8194 uint8_t pubKeyData[32];
8195 X25519_keypair(pubKeyData, privKeyData);
8196 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8197 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8198 } else {
8199 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8200 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8201 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8202 ASSERT_NE(group, nullptr);
8203 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8204 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8205 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8206 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
8207 }
8208
8209 // Get encoded form of the public part of the locally generated key...
8210 unsigned char* p = nullptr;
8211 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8212 ASSERT_GT(localPublicKeySize, 0);
8213 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8214 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8215 OPENSSL_free(p);
8216 }
8217
GenerateKeyMintEcKey(EcCurve curve,EVP_PKEY_Ptr * kmPubKey)8218 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8219 vector<uint8_t> challenge = {0x41, 0x42};
8220 auto builder = AuthorizationSetBuilder()
8221 .Authorization(TAG_NO_AUTH_REQUIRED)
8222 .Authorization(TAG_EC_CURVE, curve)
8223 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8224 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8225 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8226 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8227 .SetDefaultValidity();
8228 ErrorCode result = GenerateKey(builder);
8229
8230 if (SecLevel() == SecurityLevel::STRONGBOX) {
8231 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8232 result = GenerateKeyWithSelfSignedAttestKey(
8233 AuthorizationSetBuilder()
8234 .EcdsaKey(EcCurve::P_256)
8235 .AttestKey()
8236 .SetDefaultValidity(), /* attest key params */
8237 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8238 }
8239 }
8240 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8241 ASSERT_GT(cert_chain_.size(), 0);
8242 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8243 ASSERT_NE(kmKeyCert, nullptr);
8244 // Check that keyAgreement (bit 4) is set in KeyUsage
8245 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8246 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8247 ASSERT_NE(*kmPubKey, nullptr);
8248 if (dump_Attestations) {
8249 for (size_t n = 0; n < cert_chain_.size(); n++) {
8250 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8251 }
8252 }
8253 }
8254
CheckAgreement(EVP_PKEY_Ptr kmPubKey,EVP_PKEY_Ptr localPrivKey,const std::vector<uint8_t> & localPublicKey)8255 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8256 const std::vector<uint8_t>& localPublicKey) {
8257 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8258 string ZabFromKeyMintStr;
8259 ASSERT_EQ(ErrorCode::OK,
8260 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8261 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8262 vector<uint8_t> ZabFromTest;
8263
8264 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8265 size_t kmPubKeySize = 32;
8266 uint8_t kmPubKeyData[32];
8267 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8268 ASSERT_EQ(kmPubKeySize, 32);
8269
8270 uint8_t localPrivKeyData[32];
8271 size_t localPrivKeySize = 32;
8272 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8273 &localPrivKeySize));
8274 ASSERT_EQ(localPrivKeySize, 32);
8275
8276 uint8_t sharedKey[32];
8277 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8278 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8279 } else {
8280 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8281 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8282 ASSERT_NE(ctx, nullptr);
8283 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8284 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8285 size_t ZabFromTestLen = 0;
8286 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8287 ZabFromTest.resize(ZabFromTestLen);
8288 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8289 }
8290 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8291 }
8292 };
8293
8294 /*
8295 * KeyAgreementTest.Ecdh
8296 *
8297 * Verifies that ECDH works for all required curves
8298 */
TEST_P(KeyAgreementTest,Ecdh)8299 TEST_P(KeyAgreementTest, Ecdh) {
8300 // Because it's possible to use this API with keys on different curves, we
8301 // check all N^2 combinations where N is the number of supported
8302 // curves.
8303 //
8304 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8305 // lot more curves we can be smart about things and just pick |otherCurve| so
8306 // it's not |curve| and that way we end up with only 2*N runs
8307 //
8308 for (auto curve : ValidCurves()) {
8309 for (auto localCurve : ValidCurves()) {
8310 SCOPED_TRACE(testing::Message()
8311 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8312
8313 // Generate EC key locally (with access to private key material)
8314 EVP_PKEY_Ptr localPrivKey;
8315 vector<uint8_t> localPublicKey;
8316 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
8317
8318 // Generate EC key in KeyMint (only access to public key material)
8319 EVP_PKEY_Ptr kmPubKey;
8320 GenerateKeyMintEcKey(curve, &kmPubKey);
8321
8322 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8323 if (curve != localCurve) {
8324 // If the keys are using different curves KeyMint should fail with
8325 // ErrorCode:INVALID_ARGUMENT. Check that.
8326 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8327 string ZabFromKeyMintStr;
8328 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8329 Finish(string(localPublicKey.begin(), localPublicKey.end()),
8330 &ZabFromKeyMintStr));
8331
8332 } else {
8333 // Otherwise if the keys are using the same curve, it should work.
8334 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
8335 }
8336
8337 CheckedDeleteKey();
8338 }
8339 }
8340 }
8341
8342 /*
8343 * KeyAgreementTest.EcdhCurve25519
8344 *
8345 * Verifies that ECDH works for curve25519. This is also covered by the general
8346 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8347 * KeyMint 1.0.
8348 */
TEST_P(KeyAgreementTest,EcdhCurve25519)8349 TEST_P(KeyAgreementTest, EcdhCurve25519) {
8350 if (!Curve25519Supported()) {
8351 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8352 }
8353
8354 // Generate EC key in KeyMint (only access to public key material)
8355 EcCurve curve = EcCurve::CURVE_25519;
8356 EVP_PKEY_Ptr kmPubKey = nullptr;
8357 GenerateKeyMintEcKey(curve, &kmPubKey);
8358
8359 // Generate EC key on same curve locally (with access to private key material).
8360 EVP_PKEY_Ptr privKey;
8361 vector<uint8_t> encodedPublicKey;
8362 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8363
8364 // Agree on a key between local and KeyMint and check it.
8365 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8366
8367 CheckedDeleteKey();
8368 }
8369
8370 /*
8371 * KeyAgreementTest.EcdhCurve25519Imported
8372 *
8373 * Verifies that ECDH works for an imported curve25519 key.
8374 */
TEST_P(KeyAgreementTest,EcdhCurve25519Imported)8375 TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8376 if (!Curve25519Supported()) {
8377 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8378 }
8379
8380 // Import x25519 key into KeyMint.
8381 EcCurve curve = EcCurve::CURVE_25519;
8382 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8383 .Authorization(TAG_NO_AUTH_REQUIRED)
8384 .EcdsaKey(EcCurve::CURVE_25519)
8385 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8386 .SetDefaultValidity(),
8387 KeyFormat::PKCS8, x25519_pkcs8_key));
8388 ASSERT_GT(cert_chain_.size(), 0);
8389 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8390 ASSERT_NE(kmKeyCert, nullptr);
8391 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8392 ASSERT_NE(kmPubKey.get(), nullptr);
8393
8394 // Expect the import to emit corresponding public key data.
8395 size_t kmPubKeySize = 32;
8396 uint8_t kmPubKeyData[32];
8397 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8398 ASSERT_EQ(kmPubKeySize, 32);
8399 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8400 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8401
8402 // Generate EC key on same curve locally (with access to private key material).
8403 EVP_PKEY_Ptr privKey;
8404 vector<uint8_t> encodedPublicKey;
8405 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8406
8407 // Agree on a key between local and KeyMint and check it.
8408 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8409
8410 CheckedDeleteKey();
8411 }
8412
8413 /*
8414 * KeyAgreementTest.EcdhCurve25519InvalidSize
8415 *
8416 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8417 */
TEST_P(KeyAgreementTest,EcdhCurve25519InvalidSize)8418 TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8419 if (!Curve25519Supported()) {
8420 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8421 }
8422
8423 // Generate EC key in KeyMint (only access to public key material)
8424 EcCurve curve = EcCurve::CURVE_25519;
8425 EVP_PKEY_Ptr kmPubKey = nullptr;
8426 GenerateKeyMintEcKey(curve, &kmPubKey);
8427
8428 // Generate EC key on same curve locally (with access to private key material).
8429 EVP_PKEY_Ptr privKey;
8430 vector<uint8_t> encodedPublicKey;
8431 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8432
8433 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8434 string ZabFromKeyMintStr;
8435 // Send in an incomplete public key.
8436 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8437 &ZabFromKeyMintStr));
8438
8439 CheckedDeleteKey();
8440 }
8441
8442 /*
8443 * KeyAgreementTest.EcdhCurve25519Mismatch
8444 *
8445 * Verifies that ECDH fails between curve25519 and other curves.
8446 */
TEST_P(KeyAgreementTest,EcdhCurve25519Mismatch)8447 TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8448 if (!Curve25519Supported()) {
8449 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8450 }
8451
8452 // Generate EC key in KeyMint (only access to public key material)
8453 EcCurve curve = EcCurve::CURVE_25519;
8454 EVP_PKEY_Ptr kmPubKey = nullptr;
8455 GenerateKeyMintEcKey(curve, &kmPubKey);
8456
8457 for (auto localCurve : ValidCurves()) {
8458 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
8459 if (localCurve == curve) {
8460 continue;
8461 }
8462 // Generate EC key on a different curve locally (with access to private key material).
8463 EVP_PKEY_Ptr privKey;
8464 vector<uint8_t> encodedPublicKey;
8465 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8466
8467 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8468 string ZabFromKeyMintStr;
8469 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8470 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8471 &ZabFromKeyMintStr));
8472 }
8473
8474 CheckedDeleteKey();
8475 }
8476
8477 INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8478
8479 using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8480
8481 // This is a problematic test, as it can render the device under test permanently unusable.
8482 // Re-enable and run at your own risk.
TEST_P(DestroyAttestationIdsTest,DISABLED_DestroyTest)8483 TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8484 auto result = DestroyAttestationIds();
8485 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8486 }
8487
8488 INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8489
8490 using EarlyBootKeyTest = KeyMintAidlTestBase;
8491
8492 /*
8493 * EarlyBootKeyTest.CreateEarlyBootKeys
8494 *
8495 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8496 */
TEST_P(EarlyBootKeyTest,CreateEarlyBootKeys)8497 TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
8498 // Early boot keys can be created after early boot.
8499 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8500 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8501
8502 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8503 ASSERT_GT(keyData.blob.size(), 0U);
8504 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8505 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8506 }
8507 CheckedDeleteKey(&aesKeyData.blob);
8508 CheckedDeleteKey(&hmacKeyData.blob);
8509 CheckedDeleteKey(&rsaKeyData.blob);
8510 CheckedDeleteKey(&ecdsaKeyData.blob);
8511 }
8512
8513 /*
8514 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8515 *
8516 * Verifies that creating an early boot key with attestation succeeds.
8517 */
TEST_P(EarlyBootKeyTest,CreateAttestedEarlyBootKey)8518 TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8519 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8520 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8521 builder->AttestationChallenge("challenge");
8522 builder->AttestationApplicationId("app_id");
8523 });
8524
8525 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8526 // Strongbox may not support factory attestation. Key creation might fail with
8527 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8528 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8529 continue;
8530 }
8531 ASSERT_GT(keyData.blob.size(), 0U);
8532 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8533 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8534 }
8535 CheckedDeleteKey(&aesKeyData.blob);
8536 CheckedDeleteKey(&hmacKeyData.blob);
8537 if (rsaKeyData.blob.size() != 0U) {
8538 CheckedDeleteKey(&rsaKeyData.blob);
8539 }
8540 if (ecdsaKeyData.blob.size() != 0U) {
8541 CheckedDeleteKey(&ecdsaKeyData.blob);
8542 }
8543 }
8544
8545 /*
8546 * EarlyBootKeyTest.UseEarlyBootKeyFailure
8547 *
8548 * Verifies that using early boot keys at a later stage fails.
8549 */
TEST_P(EarlyBootKeyTest,UseEarlyBootKeyFailure)8550 TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8551 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8552 .Authorization(TAG_NO_AUTH_REQUIRED)
8553 .Authorization(TAG_EARLY_BOOT_ONLY)
8554 .HmacKey(128)
8555 .Digest(Digest::SHA_2_256)
8556 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8557 AuthorizationSet output_params;
8558 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8559 AuthorizationSetBuilder()
8560 .Digest(Digest::SHA_2_256)
8561 .Authorization(TAG_MAC_LENGTH, 256),
8562 &output_params));
8563 }
8564
8565 /*
8566 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8567 *
8568 * Verifies that importing early boot keys fails.
8569 */
TEST_P(EarlyBootKeyTest,ImportEarlyBootKeyFailure)8570 TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8571 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8572 .Authorization(TAG_NO_AUTH_REQUIRED)
8573 .Authorization(TAG_EARLY_BOOT_ONLY)
8574 .EcdsaSigningKey(EcCurve::P_256)
8575 .Digest(Digest::SHA_2_256)
8576 .SetDefaultValidity(),
8577 KeyFormat::PKCS8, ec_256_key));
8578 }
8579
8580 // This is a more comprehensive test, but it can only be run on a machine which is still in early
8581 // boot stage, which no proper Android device is by the time we can run VTS. To use this,
8582 // un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8583 // early boot, so you'll have to reboot between runs.
TEST_P(EarlyBootKeyTest,DISABLED_FullTest)8584 TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8585 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8586 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8587 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8588 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8589 EXPECT_TRUE(
8590 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8591 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8592 EXPECT_TRUE(
8593 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8594
8595 // Should be able to use keys, since early boot has not ended
8596 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8597 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8598 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8599 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8600
8601 // End early boot
8602 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8603 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8604
8605 // Should not be able to use already-created keys.
8606 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8607 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8608 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8609 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8610
8611 CheckedDeleteKey(&aesKeyData.blob);
8612 CheckedDeleteKey(&hmacKeyData.blob);
8613 CheckedDeleteKey(&rsaKeyData.blob);
8614 CheckedDeleteKey(&ecdsaKeyData.blob);
8615
8616 // Should not be able to create new keys
8617 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
8618 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
8619
8620 CheckedDeleteKey(&aesKeyData.blob);
8621 CheckedDeleteKey(&hmacKeyData.blob);
8622 CheckedDeleteKey(&rsaKeyData.blob);
8623 CheckedDeleteKey(&ecdsaKeyData.blob);
8624 }
8625
8626 INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8627
8628 using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
8629
8630 // This may be a problematic test. It can't be run repeatedly without unlocking the device in
8631 // between runs... and on most test devices there are no enrolled credentials so it can't be
8632 // unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8633 // device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8634 // a manual test process, which includes unlocking between runs, which is why it's included here.
8635 // Well, that and the fact that it's the only test we can do without also making calls into the
8636 // Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8637 // implications might be, so that may or may not be a solution.
TEST_P(UnlockedDeviceRequiredTest,DISABLED_KeysBecomeUnusable)8638 TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8639 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8640 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
8641
8642 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8643 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8644 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8645 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8646
8647 ErrorCode rc = GetReturnErrorCode(
8648 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
8649 ASSERT_EQ(ErrorCode::OK, rc);
8650 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8651 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8652 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8653 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8654
8655 CheckedDeleteKey(&aesKeyData.blob);
8656 CheckedDeleteKey(&hmacKeyData.blob);
8657 CheckedDeleteKey(&rsaKeyData.blob);
8658 CheckedDeleteKey(&ecdsaKeyData.blob);
8659 }
8660
8661 INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8662
8663 using VsrRequirementTest = KeyMintAidlTestBase;
8664
TEST_P(VsrRequirementTest,Vsr13Test)8665 TEST_P(VsrRequirementTest, Vsr13Test) {
8666 int vsr_api_level = get_vsr_api_level();
8667 if (vsr_api_level < __ANDROID_API_T__) {
8668 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8669 }
8670 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8671 }
8672
TEST_P(VsrRequirementTest,Vsr14Test)8673 TEST_P(VsrRequirementTest, Vsr14Test) {
8674 int vsr_api_level = get_vsr_api_level();
8675 if (vsr_api_level < __ANDROID_API_U__) {
8676 GTEST_SKIP() << "Applies only to VSR API level 34, this device is: " << vsr_api_level;
8677 }
8678 EXPECT_GE(AidlVersion(), 3) << "VSR 14+ requires KeyMint version 3";
8679 }
8680
8681 INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8682
8683 } // namespace aidl::android::hardware::security::keymint::test
8684
main(int argc,char ** argv)8685 int main(int argc, char** argv) {
8686 std::cout << "Testing ";
8687 auto halInstances =
8688 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8689 std::cout << "HAL instances:\n";
8690 for (auto& entry : halInstances) {
8691 std::cout << " " << entry << '\n';
8692 }
8693
8694 ::testing::InitGoogleTest(&argc, argv);
8695 for (int i = 1; i < argc; ++i) {
8696 if (argv[i][0] == '-') {
8697 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
8698 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8699 arm_deleteAllKeys = true;
8700 }
8701 if (std::string(argv[i]) == "--dump_attestations") {
8702 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8703 dump_Attestations = true;
8704 } else {
8705 std::cout << "NOT dumping attestations" << std::endl;
8706 }
8707 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8708 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8709 // be run in emulated environments that don't have the normal bootloader
8710 // interactions.
8711 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8712 }
8713 if (std::string(argv[i]) == "--keyblob_dir") {
8714 if (i + 1 >= argc) {
8715 std::cerr << "Missing argument for --keyblob_dir\n";
8716 return 1;
8717 }
8718 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::keyblob_dir =
8719 std::string(argv[i + 1]);
8720 ++i;
8721 }
8722 }
8723 }
8724 return RUN_ALL_TESTS();
8725 }
8726