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