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