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