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