1 /*
2  * Copyright (C) 2017 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 "keymaster_hidl_hal_test"
18 #include <cutils/log.h>
19 
20 #include <signal.h>
21 
22 #include <functional>
23 #include <iostream>
24 #include <string>
25 
26 #include <openssl/evp.h>
27 #include <openssl/mem.h>
28 #include <openssl/x509.h>
29 
30 #include <cutils/properties.h>
31 
32 #include <keymasterV4_0/attestation_record.h>
33 #include <keymasterV4_0/key_param_output.h>
34 #include <keymasterV4_0/openssl_utils.h>
35 
36 #include "KeymasterHidlTest.h"
37 
38 using namespace std::string_literals;
39 
40 static bool arm_deleteAllKeys = false;
41 static bool dump_Attestations = false;
42 
43 namespace android {
44 namespace hardware {
45 
46 template <typename T>
operator ==(const hidl_vec<T> & a,const hidl_vec<T> & b)47 bool operator==(const hidl_vec<T>& a, const hidl_vec<T>& b) {
48     if (a.size() != b.size()) {
49         return false;
50     }
51     for (size_t i = 0; i < a.size(); ++i) {
52         if (a[i] != b[i]) {
53             return false;
54         }
55     }
56     return true;
57 }
58 
59 namespace keymaster {
60 namespace V4_0 {
61 
operator ==(const AuthorizationSet & a,const AuthorizationSet & b)62 bool operator==(const AuthorizationSet& a, const AuthorizationSet& b) {
63     return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin());
64 }
65 
operator ==(const KeyCharacteristics & a,const KeyCharacteristics & b)66 bool operator==(const KeyCharacteristics& a, const KeyCharacteristics& b) {
67     // This isn't very efficient. Oh, well.
68     AuthorizationSet a_sw(a.softwareEnforced);
69     AuthorizationSet b_sw(b.softwareEnforced);
70     AuthorizationSet a_tee(b.hardwareEnforced);
71     AuthorizationSet b_tee(b.hardwareEnforced);
72 
73     a_sw.Sort();
74     b_sw.Sort();
75     a_tee.Sort();
76     b_tee.Sort();
77 
78     return a_sw == b_sw && a_tee == b_tee;
79 }
80 
81 namespace test {
82 namespace {
83 
84 template <TagType tag_type, Tag tag, typename ValueT>
contains(hidl_vec<KeyParameter> & set,TypedTag<tag_type,tag> ttag,ValueT expected_value)85 bool contains(hidl_vec<KeyParameter>& set, TypedTag<tag_type, tag> ttag, ValueT expected_value) {
86     size_t count = std::count_if(set.begin(), set.end(), [&](const KeyParameter& param) {
87         return param.tag == tag && accessTagValue(ttag, param) == expected_value;
88     });
89     return count == 1;
90 }
91 
92 template <TagType tag_type, Tag tag>
contains(hidl_vec<KeyParameter> & set,TypedTag<tag_type,tag>)93 bool contains(hidl_vec<KeyParameter>& set, TypedTag<tag_type, tag>) {
94     size_t count = std::count_if(set.begin(), set.end(),
95                                  [&](const KeyParameter& param) { return param.tag == tag; });
96     return count > 0;
97 }
98 
99 // If the given property is available, add it to the tag set under the given tag ID.
100 template <Tag tag>
add_tag_from_prop(AuthorizationSetBuilder * tags,TypedTag<TagType::BYTES,tag> ttag,const char * prop)101 void add_tag_from_prop(AuthorizationSetBuilder* tags, TypedTag<TagType::BYTES, tag> ttag,
102                        const char* prop) {
103     char value[PROPERTY_VALUE_MAX];
104     int len = property_get(prop, value, /* default = */ "");
105     if (len > 0) {
106         tags->Authorization(ttag, reinterpret_cast<const uint8_t*>(value),
107                             static_cast<size_t>(len));
108     }
109 }
110 
111 constexpr char hex_value[256] = {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, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
114                                  0, 1,  2,  3,  4,  5,  6,  7, 8, 9, 0, 0, 0, 0, 0, 0,  // '0'..'9'
115                                  0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 'A'..'F'
116                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
117                                  0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 'a'..'f'
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                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0};
127 
hex2str(string a)128 string hex2str(string a) {
129     string b;
130     size_t num = a.size() / 2;
131     b.resize(num);
132     for (size_t i = 0; i < num; i++) {
133         b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
134     }
135     return b;
136 }
137 
138 char nibble2hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
139                        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
140 
bin2hex(const hidl_vec<uint8_t> & data)141 string bin2hex(const hidl_vec<uint8_t>& data) {
142     string retval;
143     retval.reserve(data.size() * 2 + 1);
144     for (uint8_t byte : data) {
145         retval.push_back(nibble2hex[0x0F & (byte >> 4)]);
146         retval.push_back(nibble2hex[0x0F & byte]);
147     }
148     return retval;
149 }
150 
151 /*
152  * DER-encoded PKCS#8 format RSA key. Generated using:
153  *
154  * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1  "%02X" "\n"'
155  */
156 string rsa_2048_key = hex2str(
157     "308204BD020100300D06092A864886F70D0101010500048204A7308204A3"
158     "0201000282010100BEBC342B56D443B1299F9A6A7056E80A897E318476A5"
159     "A18029E63B2ED739A61791D339F58DC763D9D14911F2EDEC383DEE11F631"
160     "9B44510E7A3ECD9B79B97382E49500ACF8117DC89CAF0E621F77756554A2"
161     "FD4664BFE7AB8B59AB48340DBFA27B93B5A81F6ECDEB02D0759307128DF3"
162     "E3BAD4055C8B840216DFAA5700670E6C5126F0962FCB70FF308F25049164"
163     "CCF76CC2DA66A7DD9A81A714C2809D69186133D29D84568E892B6FFBF319"
164     "9BDB14383EE224407F190358F111A949552ABA6714227D1BD7F6B20DD0CB"
165     "88F9467B719339F33BFF35B3870B3F62204E4286B0948EA348B524544B5F"
166     "9838F29EE643B079EEF8A713B220D7806924CDF7295070C5020301000102"
167     "82010069F377F35F2F584EF075353CCD1CA99738DB3DBC7C7FF35F9366CE"
168     "176DFD1B135AB10030344ABF5FBECF1D4659FDEF1C0FC430834BE1BE3911"
169     "951377BB3D563A2EA9CA8F4AD9C48A8CE6FD516A735C662686C7B4B3C09A"
170     "7B8354133E6F93F790D59EAEB92E84C9A4339302CCE28FDF04CCCAFA7DE3"
171     "F3A827D4F6F7D38E68B0EC6AB706645BF074A4E4090D06FB163124365FD5"
172     "EE7A20D350E9958CC30D91326E1B292E9EF5DB408EC42DAF737D20149704"
173     "D0A678A0FB5B5446863B099228A352D604BA8091A164D01D5AB05397C71E"
174     "AD20BE2A08FC528FE442817809C787FEE4AB97F97B9130D022153EDC6EB6"
175     "CBE7B0F8E3473F2E901209B5DB10F93604DB0102818100E83C0998214941"
176     "EA4F9293F1B77E2E99E6CF305FAF358238E126124FEAF2EB9724B2EA7B78"
177     "E6032343821A80E55D1D88FB12D220C3F41A56142FEC85796D1917F1E8C7"
178     "74F142B67D3D6E7B7E6B4383E94DB5929089DBB346D5BDAB40CC2D96EE04"
179     "09475E175C63BF78CFD744136740838127EA723FF3FE7FA368C1311B4A4E"
180     "0502818100D240FCC0F5D7715CDE21CB2DC86EA146132EA3B06F61FF2AF5"
181     "4BF38473F59DADCCE32B5F4CC32DD0BA6F509347B4B5B1B58C39F95E4798"
182     "CCBB43E83D0119ACF532F359CA743C85199F0286610E200997D731291717"
183     "9AC9B67558773212EC961E8BCE7A3CC809BC5486A96E4B0E6AF394D94E06"
184     "6A0900B7B70E82A44FB30053C102818100AD15DA1CBD6A492B66851BA8C3"
185     "16D38AB700E2CFDDD926A658003513C54BAA152B30021D667D20078F500F"
186     "8AD3E7F3945D74A891ED1A28EAD0FEEAEC8C14A8E834CF46A13D1378C99D"
187     "18940823CFDD27EC5810D59339E0C34198AC638E09C87CBB1B634A9864AE"
188     "9F4D5EB2D53514F67B4CAEC048C8AB849A02E397618F3271350281801FA2"
189     "C1A5331880A92D8F3E281C617108BF38244F16E352E69ED417C7153F9EC3"
190     "18F211839C643DCF8B4DD67CE2AC312E95178D5D952F06B1BF779F491692"
191     "4B70F582A23F11304E02A5E7565AE22A35E74FECC8B6FDC93F92A1A37703"
192     "E4CF0E63783BD02EB716A7ECBBFA606B10B74D01579522E7EF84D91FC522"
193     "292108D902C1028180796FE3825F9DCC85DF22D58690065D93898ACD65C0"
194     "87BEA8DA3A63BF4549B795E2CD0E3BE08CDEBD9FCF1720D9CDC5070D74F4"
195     "0DED8E1102C52152A31B6165F83A6722AECFCC35A493D7634664B888A08D"
196     "3EB034F12EA28BFEE346E205D334827F778B16ED40872BD29FCB36536B6E"
197     "93FFB06778696B4A9D81BB0A9423E63DE5");
198 
199 string rsa_key = hex2str(
200     "30820275020100300d06092a864886f70d01010105000482025f3082025b"
201     "02010002818100c6095409047d8634812d5a218176e45c41d60a75b13901"
202     "f234226cffe776521c5a77b9e389417b71c0b6a44d13afe4e4a2805d46c9"
203     "da2935adb1ff0c1f24ea06e62b20d776430a4d435157233c6f916783c30e"
204     "310fcbd89b85c2d56771169785ac12bca244abda72bfb19fc44d27c81e1d"
205     "92de284f4061edfd99280745ea6d2502030100010281801be0f04d9cae37"
206     "18691f035338308e91564b55899ffb5084d2460e6630257e05b3ceab0297"
207     "2dfabcd6ce5f6ee2589eb67911ed0fac16e43a444b8c861e544a05933657"
208     "72f8baf6b22fc9e3c5f1024b063ac080a7b2234cf8aee8f6c47bbf4fd3ac"
209     "e7240290bef16c0b3f7f3cdd64ce3ab5912cf6e32f39ab188358afcccd80"
210     "81024100e4b49ef50f765d3b24dde01aceaaf130f2c76670a91a61ae08af"
211     "497b4a82be6dee8fcdd5e3f7ba1cfb1f0c926b88f88c92bfab137fba2285"
212     "227b83c342ff7c55024100ddabb5839c4c7f6bf3d4183231f005b31aa58a"
213     "ffdda5c79e4cce217f6bc930dbe563d480706c24e9ebfcab28a6cdefd324"
214     "b77e1bf7251b709092c24ff501fd91024023d4340eda3445d8cd26c14411"
215     "da6fdca63c1ccd4b80a98ad52b78cc8ad8beb2842c1d280405bc2f6c1bea"
216     "214a1d742ab996b35b63a82a5e470fa88dbf823cdd02401b7b57449ad30d"
217     "1518249a5f56bb98294d4b6ac12ffc86940497a5a5837a6cf946262b4945"
218     "26d328c11e1126380fde04c24f916dec250892db09a6d77cdba351024077"
219     "62cd8f4d050da56bd591adb515d24d7ccd32cca0d05f866d583514bd7324"
220     "d5f33645e8ed8b4a1cb3cc4a1d67987399f2a09f5b3fb68c88d5e5d90ac3"
221     "3492d6");
222 
223 string ec_256_key = hex2str(
224     "308187020100301306072a8648ce3d020106082a8648ce3d030107046d30"
225     "6b0201010420737c2ecd7b8d1940bf2930aa9b4ed3ff941eed09366bc032"
226     "99986481f3a4d859a14403420004bf85d7720d07c25461683bc648b4778a"
227     "9a14dd8a024e3bdd8c7ddd9ab2b528bbc7aa1b51f14ebbbb0bd0ce21bcc4"
228     "1c6eb00083cf3376d11fd44949e0b2183bfe");
229 
230 string ec_521_key = hex2str(
231     "3081EE020100301006072A8648CE3D020106052B810400230481D63081D3"
232     "02010104420011458C586DB5DAA92AFAB03F4FE46AA9D9C3CE9A9B7A006A"
233     "8384BEC4C78E8E9D18D7D08B5BCFA0E53C75B064AD51C449BAE0258D54B9"
234     "4B1E885DED08ED4FB25CE9A1818903818600040149EC11C6DF0FA122C6A9"
235     "AFD9754A4FA9513A627CA329E349535A5629875A8ADFBE27DCB932C05198"
236     "6377108D054C28C6F39B6F2C9AF81802F9F326B842FF2E5F3C00AB7635CF"
237     "B36157FC0882D574A10D839C1A0C049DC5E0D775E2EE50671A208431BB45"
238     "E78E70BEFE930DB34818EE4D5C26259F5C6B8E28A652950F9F88D7B4B2C9"
239     "D9");
240 
241 string ec_256_key_rfc5915 =
242         hex2str("308193020100301306072a8648ce3d020106082a8648ce3d030107047930"
243                 "770201010420782370a8c8ce5537baadd04dcff079c8158cfa9c67b818b3"
244                 "8e8d21c9fa750c1da00a06082a8648ce3d030107a14403420004e2cc561e"
245                 "e701da0ad0ef0d176bb0c919d42e79c393fdc1bd6c4010d85cf2cf8e68c9"
246                 "05464666f98dad4f01573ba81078b3428570a439ba3229fbc026c550682f");
247 
248 string ec_256_key_sec1 =
249         hex2str("308187020100301306072a8648ce3d020106082a8648ce3d030107046d30"
250                 "6b0201010420782370a8c8ce5537baadd04dcff079c8158cfa9c67b818b3"
251                 "8e8d21c9fa750c1da14403420004e2cc561ee701da0ad0ef0d176bb0c919"
252                 "d42e79c393fdc1bd6c4010d85cf2cf8e68c905464666f98dad4f01573ba8"
253                 "1078b3428570a439ba3229fbc026c550682f");
254 
255 struct RSA_Delete {
operator ()android::hardware::keymaster::V4_0::test::__anon0dcccddb0111::RSA_Delete256     void operator()(RSA* p) { RSA_free(p); }
257 };
258 
parse_cert_blob(const hidl_vec<uint8_t> & blob)259 X509* parse_cert_blob(const hidl_vec<uint8_t>& blob) {
260     const uint8_t* p = blob.data();
261     return d2i_X509(nullptr, &p, blob.size());
262 }
263 
verify_chain(const hidl_vec<hidl_vec<uint8_t>> & chain,const std::string & msg,const std::string & signature)264 bool verify_chain(const hidl_vec<hidl_vec<uint8_t>>& chain, const std::string& msg,
265                   const std::string& signature) {
266     {
267         EVP_MD_CTX md_ctx_verify;
268         X509_Ptr signing_cert(parse_cert_blob(chain[0]));
269         EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
270         EXPECT_TRUE(signing_pubkey);
271         ERR_print_errors_cb(
272             [](const char* str, size_t len, void* ctx) -> int {
273                 (void)ctx;
274                 std::cerr << std::string(str, len) << std::endl;
275                 return 1;
276             },
277             nullptr);
278 
279         EVP_MD_CTX_init(&md_ctx_verify);
280 
281         bool result = false;
282         EXPECT_TRUE((result = EVP_DigestVerifyInit(&md_ctx_verify, NULL, EVP_sha256(), NULL,
283                                                    signing_pubkey.get())));
284         EXPECT_TRUE(
285             (result = result && EVP_DigestVerifyUpdate(&md_ctx_verify, msg.c_str(), msg.size())));
286         EXPECT_TRUE((result = result && EVP_DigestVerifyFinal(
287                                             &md_ctx_verify,
288                                             reinterpret_cast<const uint8_t*>(signature.c_str()),
289                                             signature.size())));
290         EVP_MD_CTX_cleanup(&md_ctx_verify);
291         if (!result) return false;
292     }
293     for (size_t i = 0; i < chain.size(); ++i) {
294         X509_Ptr key_cert(parse_cert_blob(chain[i]));
295         X509_Ptr signing_cert;
296         if (i < chain.size() - 1) {
297             signing_cert.reset(parse_cert_blob(chain[i + 1]));
298         } else {
299             signing_cert.reset(parse_cert_blob(chain[i]));
300         }
301         EXPECT_TRUE(!!key_cert.get() && !!signing_cert.get());
302         if (!key_cert.get() || !signing_cert.get()) return false;
303 
304         EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
305         EXPECT_TRUE(!!signing_pubkey.get());
306         if (!signing_pubkey.get()) return false;
307 
308         EXPECT_EQ(1, X509_verify(key_cert.get(), signing_pubkey.get()))
309             << "Verification of certificate " << i << " failed "
310             << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
311 
312         char* cert_issuer =  //
313             X509_NAME_oneline(X509_get_issuer_name(key_cert.get()), nullptr, 0);
314         char* signer_subj =
315             X509_NAME_oneline(X509_get_subject_name(signing_cert.get()), nullptr, 0);
316         EXPECT_STREQ(cert_issuer, signer_subj) << "Cert " << i << " has wrong issuer.";
317         if (i == 0) {
318             char* cert_sub = X509_NAME_oneline(X509_get_subject_name(key_cert.get()), nullptr, 0);
319             EXPECT_STREQ("/CN=Android Keystore Key", cert_sub)
320                 << "Cert " << i << " has wrong subject.";
321             OPENSSL_free(cert_sub);
322         }
323 
324         OPENSSL_free(cert_issuer);
325         OPENSSL_free(signer_subj);
326 
327         if (dump_Attestations) std::cout << bin2hex(chain[i]) << std::endl;
328     }
329 
330     return true;
331 }
332 
333 // Extract attestation record from cert. Returned object is still part of cert; don't free it
334 // separately.
get_attestation_record(X509 * certificate)335 ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
336     ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
337     EXPECT_TRUE(!!oid.get());
338     if (!oid.get()) return nullptr;
339 
340     int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
341     EXPECT_NE(-1, location) << "Attestation extension not found in certificate";
342     if (location == -1) return nullptr;
343 
344     X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
345     EXPECT_TRUE(!!attest_rec_ext)
346         << "Found attestation extension but couldn't retrieve it?  Probably a BoringSSL bug.";
347     if (!attest_rec_ext) return nullptr;
348 
349     ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
350     EXPECT_TRUE(!!attest_rec) << "Attestation extension contained no data";
351     return attest_rec;
352 }
353 
tag_in_list(const KeyParameter & entry)354 bool tag_in_list(const KeyParameter& entry) {
355     // Attestations don't contain everything in key authorization lists, so we need to filter
356     // the key lists to produce the lists that we expect to match the attestations.
357     auto tag_list = {
358         Tag::INCLUDE_UNIQUE_ID, Tag::BLOB_USAGE_REQUIREMENTS, Tag::EC_CURVE, Tag::HARDWARE_TYPE,
359     };
360     return std::find(tag_list.begin(), tag_list.end(), entry.tag) != tag_list.end();
361 }
362 
filter_tags(const AuthorizationSet & set)363 AuthorizationSet filter_tags(const AuthorizationSet& set) {
364     AuthorizationSet filtered;
365     std::remove_copy_if(set.begin(), set.end(), std::back_inserter(filtered), tag_in_list);
366     return filtered;
367 }
368 
make_string(const uint8_t * data,size_t length)369 std::string make_string(const uint8_t* data, size_t length) {
370     return std::string(reinterpret_cast<const char*>(data), length);
371 }
372 
373 template <size_t N>
make_string(const uint8_t (& a)[N])374 std::string make_string(const uint8_t (&a)[N]) {
375     return make_string(a, N);
376 }
377 
avb_verification_enabled()378 bool avb_verification_enabled() {
379     char value[PROPERTY_VALUE_MAX];
380     return property_get("ro.boot.vbmeta.device_state", value, "") != 0;
381 }
382 
is_gsi()383 bool is_gsi() {
384     char property_value[PROPERTY_VALUE_MAX] = {};
385     EXPECT_NE(property_get("ro.product.system.name", property_value, ""), 0);
386     return "mainline"s == property_value;
387 }
388 
389 }  // namespace
390 
verify_attestation_record(const string & challenge,const string & app_id,AuthorizationSet expected_sw_enforced,AuthorizationSet expected_hw_enforced,SecurityLevel security_level,const hidl_vec<uint8_t> & attestation_cert)391 bool verify_attestation_record(const string& challenge, const string& app_id,
392                                AuthorizationSet expected_sw_enforced,
393                                AuthorizationSet expected_hw_enforced, SecurityLevel security_level,
394                                const hidl_vec<uint8_t>& attestation_cert) {
395     X509_Ptr cert(parse_cert_blob(attestation_cert));
396     EXPECT_TRUE(!!cert.get());
397     if (!cert.get()) return false;
398 
399     ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
400     EXPECT_TRUE(!!attest_rec);
401     if (!attest_rec) return false;
402 
403     AuthorizationSet att_sw_enforced;
404     AuthorizationSet att_hw_enforced;
405     uint32_t att_attestation_version;
406     uint32_t att_keymaster_version;
407     SecurityLevel att_attestation_security_level;
408     SecurityLevel att_keymaster_security_level;
409     HidlBuf att_challenge;
410     HidlBuf att_unique_id;
411     HidlBuf att_app_id;
412 
413     auto error = parse_attestation_record(attest_rec->data,                 //
414                                           attest_rec->length,               //
415                                           &att_attestation_version,         //
416                                           &att_attestation_security_level,  //
417                                           &att_keymaster_version,           //
418                                           &att_keymaster_security_level,    //
419                                           &att_challenge,                   //
420                                           &att_sw_enforced,                 //
421                                           &att_hw_enforced,                 //
422                                           &att_unique_id);
423     EXPECT_EQ(ErrorCode::OK, error);
424     if (error != ErrorCode::OK) return false;
425 
426     EXPECT_GE(att_attestation_version, 3U);
427 
428     expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID, HidlBuf(app_id));
429 
430     EXPECT_GE(att_keymaster_version, 4U);
431     EXPECT_EQ(security_level, att_keymaster_security_level);
432     EXPECT_EQ(security_level, att_attestation_security_level);
433 
434     EXPECT_EQ(challenge.length(), att_challenge.size());
435     EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
436 
437     char property_value[PROPERTY_VALUE_MAX] = {};
438     // TODO(b/136282179): When running under VTS-on-GSI the TEE-backed
439     // keymaster implementation will report YYYYMM dates instead of YYYYMMDD
440     // for the BOOT_PATCH_LEVEL.
441     if (!is_gsi()) {
442         for (int i = 0; i < att_hw_enforced.size(); i++) {
443             if (att_hw_enforced[i].tag == TAG_BOOT_PATCHLEVEL ||
444                 att_hw_enforced[i].tag == TAG_VENDOR_PATCHLEVEL) {
445                 std::string date = std::to_string(att_hw_enforced[i].f.integer);
446                 // strptime seems to require delimiters, but the tag value will
447                 // be YYYYMMDD
448                 date.insert(6, "-");
449                 date.insert(4, "-");
450                 EXPECT_EQ(date.size(), 10);
451                 struct tm time;
452                 strptime(date.c_str(), "%Y-%m-%d", &time);
453 
454                 // Day of the month (0-31)
455                 EXPECT_GE(time.tm_mday, 0);
456                 EXPECT_LT(time.tm_mday, 32);
457                 // Months since Jan (0-11)
458                 EXPECT_GE(time.tm_mon, 0);
459                 EXPECT_LT(time.tm_mon, 12);
460                 // Years since 1900
461                 EXPECT_GT(time.tm_year, 110);
462                 EXPECT_LT(time.tm_year, 200);
463             }
464         }
465     }
466 
467     // Check to make sure boolean values are properly encoded. Presence of a boolean tag indicates
468     // true. A provided boolean tag that can be pulled back out of the certificate indicates correct
469     // encoding. No need to check if it's in both lists, since the AuthorizationSet compare below
470     // will handle mismatches of tags.
471     if (security_level == SecurityLevel::SOFTWARE) {
472         EXPECT_TRUE(expected_sw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
473     } else {
474         EXPECT_TRUE(expected_hw_enforced.Contains(TAG_NO_AUTH_REQUIRED));
475     }
476 
477     // Alternatively this checks the opposite - a false boolean tag (one that isn't provided in
478     // the authorization list during key generation) isn't being attested to in the certificate.
479     EXPECT_FALSE(expected_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
480     EXPECT_FALSE(att_sw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
481     EXPECT_FALSE(expected_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
482     EXPECT_FALSE(att_hw_enforced.Contains(TAG_TRUSTED_USER_PRESENCE_REQUIRED));
483 
484     if (att_hw_enforced.Contains(TAG_ALGORITHM, Algorithm::EC)) {
485         // For ECDSA keys, either an EC_CURVE or a KEY_SIZE can be specified, but one must be.
486         EXPECT_TRUE(att_hw_enforced.Contains(TAG_EC_CURVE) ||
487                     att_hw_enforced.Contains(TAG_KEY_SIZE));
488     }
489 
490     // Test root of trust elements
491     HidlBuf verified_boot_key;
492     keymaster_verified_boot_t verified_boot_state;
493     bool device_locked;
494     HidlBuf verified_boot_hash;
495     error = parse_root_of_trust(attest_rec->data, attest_rec->length, &verified_boot_key,
496                                 &verified_boot_state, &device_locked, &verified_boot_hash);
497     EXPECT_EQ(ErrorCode::OK, error);
498 
499     if (avb_verification_enabled()) {
500         EXPECT_NE(property_get("ro.boot.vbmeta.digest", property_value, ""), 0);
501         string prop_string(property_value);
502         EXPECT_EQ(prop_string.size(), 64);
503         EXPECT_EQ(prop_string, bin2hex(verified_boot_hash));
504 
505         EXPECT_NE(property_get("ro.boot.vbmeta.device_state", property_value, ""), 0);
506         if (!strcmp(property_value, "unlocked")) {
507             EXPECT_FALSE(device_locked);
508         } else {
509             EXPECT_TRUE(device_locked);
510         }
511 
512         // Check that the device is locked if not debuggable, e.g., user build
513         // images in CTS. For VTS, debuggable images are used to allow adb root
514         // and the device is unlocked.
515         if (!property_get_bool("ro.debuggable", false)) {
516             EXPECT_TRUE(device_locked);
517         } else {
518             EXPECT_FALSE(device_locked);
519         }
520     }
521 
522     // Verified boot key should be all 0's if the boot state is not verified or self signed
523     std::string empty_boot_key(32, '\0');
524     std::string verified_boot_key_str((const char*)verified_boot_key.data(),
525                                       verified_boot_key.size());
526     EXPECT_NE(property_get("ro.boot.verifiedbootstate", property_value, ""), 0);
527     if (!strcmp(property_value, "green")) {
528         EXPECT_EQ(verified_boot_state, KM_VERIFIED_BOOT_VERIFIED);
529         EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
530                             verified_boot_key.size()));
531     } else if (!strcmp(property_value, "yellow")) {
532         EXPECT_EQ(verified_boot_state, KM_VERIFIED_BOOT_SELF_SIGNED);
533         EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
534                             verified_boot_key.size()));
535     } else if (!strcmp(property_value, "orange")) {
536         EXPECT_EQ(verified_boot_state, KM_VERIFIED_BOOT_UNVERIFIED);
537         EXPECT_EQ(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
538                             verified_boot_key.size()));
539     } else if (!strcmp(property_value, "red")) {
540         EXPECT_EQ(verified_boot_state, KM_VERIFIED_BOOT_FAILED);
541     } else {
542         EXPECT_EQ(verified_boot_state, KM_VERIFIED_BOOT_UNVERIFIED);
543         EXPECT_NE(0, memcmp(verified_boot_key.data(), empty_boot_key.data(),
544                             verified_boot_key.size()));
545     }
546 
547     att_sw_enforced.Sort();
548     expected_sw_enforced.Sort();
549     EXPECT_EQ(filter_tags(expected_sw_enforced), filter_tags(att_sw_enforced));
550 
551     att_hw_enforced.Sort();
552     expected_hw_enforced.Sort();
553     EXPECT_EQ(filter_tags(expected_hw_enforced), filter_tags(att_hw_enforced));
554 
555     return true;
556 }
557 
558 class NewKeyGenerationTest : public KeymasterHidlTest {
559    protected:
CheckBaseParams(const KeyCharacteristics & keyCharacteristics)560     void CheckBaseParams(const KeyCharacteristics& keyCharacteristics) {
561         // TODO(swillden): Distinguish which params should be in which auth list.
562 
563         AuthorizationSet auths(keyCharacteristics.hardwareEnforced);
564         auths.push_back(AuthorizationSet(keyCharacteristics.softwareEnforced));
565 
566         EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
567         EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
568         EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
569 
570         // Verify that App ID, App data and ROT are NOT included.
571         EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
572         EXPECT_FALSE(auths.Contains(TAG_APPLICATION_ID));
573         EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
574 
575         // Check that some unexpected tags/values are NOT present.
576         EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
577         EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
578         EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
579 
580         // Now check that unspecified, defaulted tags are correct.
581         EXPECT_TRUE(auths.Contains(TAG_CREATION_DATETIME));
582 
583         EXPECT_TRUE(auths.Contains(TAG_OS_VERSION, os_version()))
584             << "OS version is " << os_version() << " key reported "
585             << auths.GetTagValue(TAG_OS_VERSION);
586 
587         if (is_gsi()) {
588             // In general, TAG_OS_PATCHLEVEL should be equal to os_patch_level()
589             // reported from the system.img in use. But it is allowed to boot a
590             // GSI system.img with newer patch level, which means TAG_OS_PATCHLEVEL
591             // might be less than or equal to os_patch_level() in this case.
592             EXPECT_TRUE(auths.Contains(TAG_OS_PATCHLEVEL,  // vbmeta.img patch level
593                                        os_patch_level(),   // system.img patch level
594                                        std::less_equal<>()))
595                     << "OS patch level is " << os_patch_level()
596                     << ", which is less than key reported " << auths.GetTagValue(TAG_OS_PATCHLEVEL);
597         } else {
598             EXPECT_TRUE(auths.Contains(TAG_OS_PATCHLEVEL,  // vbmeta.img patch level
599                                        os_patch_level(),   // system.img patch level
600                                        std::equal_to<>()))
601                     << "OS patch level is " << os_patch_level()
602                     << ", which is not equal to key reported "
603                     << auths.GetTagValue(TAG_OS_PATCHLEVEL);
604         }
605     }
606 
CheckCharacteristics(const HidlBuf & key_blob,const KeyCharacteristics & key_characteristics)607     void CheckCharacteristics(const HidlBuf& key_blob,
608                               const KeyCharacteristics& key_characteristics) {
609         KeyCharacteristics retrieved_chars;
610         ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob, &retrieved_chars));
611         EXPECT_EQ(key_characteristics, retrieved_chars);
612     }
613 };
614 
615 /*
616  * NewKeyGenerationTest.Rsa
617  *
618  * Verifies that keymaster can generate all required RSA key sizes, and that the resulting keys have
619  * correct characteristics.
620  */
TEST_P(NewKeyGenerationTest,Rsa)621 TEST_P(NewKeyGenerationTest, Rsa) {
622     for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
623         HidlBuf key_blob;
624         KeyCharacteristics key_characteristics;
625         ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
626                                                      .RsaSigningKey(key_size, 65537)
627                                                      .Digest(Digest::NONE)
628                                                      .Padding(PaddingMode::NONE),
629                                              &key_blob, &key_characteristics));
630 
631         ASSERT_GT(key_blob.size(), 0U);
632         CheckBaseParams(key_characteristics);
633         CheckCharacteristics(key_blob, key_characteristics);
634 
635         AuthorizationSet crypto_params;
636         if (IsSecure()) {
637             crypto_params = key_characteristics.hardwareEnforced;
638         } else {
639             crypto_params = key_characteristics.softwareEnforced;
640         }
641 
642         EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
643         EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
644             << "Key size " << key_size << "missing";
645         EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
646 
647         CheckedDeleteKey(&key_blob);
648     }
649 }
650 
651 /*
652  * NewKeyGenerationTest.NoInvalidRsaSizes
653  *
654  * Verifies that keymaster cannot generate any RSA key sizes that are designated as invalid.
655  */
TEST_P(NewKeyGenerationTest,NoInvalidRsaSizes)656 TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
657     for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
658         HidlBuf key_blob;
659         KeyCharacteristics key_characteristics;
660         ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
661                   GenerateKey(AuthorizationSetBuilder()
662                                       .RsaSigningKey(key_size, 65537)
663                                       .Digest(Digest::NONE)
664                                       .Padding(PaddingMode::NONE),
665                               &key_blob, &key_characteristics));
666     }
667 }
668 
669 /*
670  * NewKeyGenerationTest.RsaNoDefaultSize
671  *
672  * Verifies that failing to specify a key size for RSA key generation returns UNSUPPORTED_KEY_SIZE.
673  */
TEST_P(NewKeyGenerationTest,RsaNoDefaultSize)674 TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
675     ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
676               GenerateKey(AuthorizationSetBuilder()
677                               .Authorization(TAG_ALGORITHM, Algorithm::RSA)
678                               .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
679                               .SigningKey()));
680 }
681 
682 /*
683  * NewKeyGenerationTest.Ecdsa
684  *
685  * Verifies that keymaster can generate all required EC key sizes, and that the resulting keys have
686  * correct characteristics.
687  */
TEST_P(NewKeyGenerationTest,Ecdsa)688 TEST_P(NewKeyGenerationTest, Ecdsa) {
689     for (auto key_size : ValidKeySizes(Algorithm::EC)) {
690         HidlBuf key_blob;
691         KeyCharacteristics key_characteristics;
692         ASSERT_EQ(
693             ErrorCode::OK,
694             GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(key_size).Digest(Digest::NONE),
695                         &key_blob, &key_characteristics));
696         ASSERT_GT(key_blob.size(), 0U);
697         CheckBaseParams(key_characteristics);
698         CheckCharacteristics(key_blob, key_characteristics);
699 
700         AuthorizationSet crypto_params;
701         if (IsSecure()) {
702             crypto_params = key_characteristics.hardwareEnforced;
703         } else {
704             crypto_params = key_characteristics.softwareEnforced;
705         }
706 
707         EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
708         EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
709             << "Key size " << key_size << "missing";
710 
711         CheckedDeleteKey(&key_blob);
712     }
713 }
714 
715 /*
716  * NewKeyGenerationTest.EcdsaDefaultSize
717  *
718  * Verifies that failing to specify a key size for EC key generation returns UNSUPPORTED_KEY_SIZE.
719  */
TEST_P(NewKeyGenerationTest,EcdsaDefaultSize)720 TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
721     ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
722               GenerateKey(AuthorizationSetBuilder()
723                               .Authorization(TAG_ALGORITHM, Algorithm::EC)
724                               .SigningKey()
725                               .Digest(Digest::NONE)));
726 }
727 
728 /*
729  * NewKeyGenerationTest.EcdsaInvalidSize
730  *
731  * Verifies that specifying an invalid key size for EC key generation returns UNSUPPORTED_KEY_SIZE.
732  */
TEST_P(NewKeyGenerationTest,EcdsaInvalidSize)733 TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
734     for (auto key_size : InvalidKeySizes(Algorithm::EC)) {
735         HidlBuf key_blob;
736         KeyCharacteristics key_characteristics;
737         ASSERT_EQ(
738             ErrorCode::UNSUPPORTED_KEY_SIZE,
739             GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(key_size).Digest(Digest::NONE),
740                         &key_blob, &key_characteristics));
741     }
742 
743     ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
744               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(Digest::NONE)));
745 }
746 
747 /*
748  * NewKeyGenerationTest.EcdsaMismatchKeySize
749  *
750  * Verifies that specifying mismatched key size and curve for EC key generation returns
751  * INVALID_ARGUMENT.
752  */
TEST_P(NewKeyGenerationTest,EcdsaMismatchKeySize)753 TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
754     if (SecLevel() == SecurityLevel::STRONGBOX) return;
755 
756     ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
757               GenerateKey(AuthorizationSetBuilder()
758                               .EcdsaSigningKey(224)
759                               .Authorization(TAG_EC_CURVE, EcCurve::P_256)
760                               .Digest(Digest::NONE)));
761 }
762 
763 /*
764  * NewKeyGenerationTest.EcdsaAllValidSizes
765  *
766  * Verifies that keymaster supports all required EC key sizes.
767  */
TEST_P(NewKeyGenerationTest,EcdsaAllValidSizes)768 TEST_P(NewKeyGenerationTest, EcdsaAllValidSizes) {
769     auto valid_sizes = ValidKeySizes(Algorithm::EC);
770     for (size_t size : valid_sizes) {
771         EXPECT_EQ(ErrorCode::OK,
772                   GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(size).Digest(Digest::NONE)))
773             << "Failed to generate size: " << size;
774         CheckCharacteristics(key_blob_, key_characteristics_);
775         CheckedDeleteKey();
776     }
777 }
778 
779 /*
780  * NewKeyGenerationTest.EcdsaInvalidCurves
781  *
782  * Verifies that keymaster does not support any curve designated as unsupported.
783  */
TEST_P(NewKeyGenerationTest,EcdsaAllValidCurves)784 TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
785     Digest digest;
786     if (SecLevel() == SecurityLevel::STRONGBOX) {
787         digest = Digest::SHA_2_256;
788     } else {
789         digest = Digest::SHA_2_512;
790     }
791     for (auto curve : ValidCurves()) {
792         EXPECT_EQ(
793             ErrorCode::OK,
794             GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(curve).Digest(digest)))
795             << "Failed to generate key on curve: " << curve;
796         CheckCharacteristics(key_blob_, key_characteristics_);
797         CheckedDeleteKey();
798     }
799 }
800 
801 /*
802  * NewKeyGenerationTest.Hmac
803  *
804  * Verifies that keymaster supports all required digests, and that the resulting keys have correct
805  * characteristics.
806  */
TEST_P(NewKeyGenerationTest,Hmac)807 TEST_P(NewKeyGenerationTest, Hmac) {
808     for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
809         HidlBuf key_blob;
810         KeyCharacteristics key_characteristics;
811         constexpr size_t key_size = 128;
812         ASSERT_EQ(
813             ErrorCode::OK,
814             GenerateKey(AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
815                             TAG_MIN_MAC_LENGTH, 128),
816                         &key_blob, &key_characteristics));
817 
818         ASSERT_GT(key_blob.size(), 0U);
819         CheckBaseParams(key_characteristics);
820         CheckCharacteristics(key_blob, key_characteristics);
821 
822         AuthorizationSet hardwareEnforced = key_characteristics.hardwareEnforced;
823         AuthorizationSet softwareEnforced = key_characteristics.softwareEnforced;
824         if (IsSecure()) {
825             EXPECT_TRUE(hardwareEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC));
826             EXPECT_TRUE(hardwareEnforced.Contains(TAG_KEY_SIZE, key_size))
827                 << "Key size " << key_size << "missing";
828         } else {
829             EXPECT_TRUE(softwareEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC));
830             EXPECT_TRUE(softwareEnforced.Contains(TAG_KEY_SIZE, key_size))
831                 << "Key size " << key_size << "missing";
832         }
833 
834         CheckedDeleteKey(&key_blob);
835     }
836 }
837 
838 /*
839  * NewKeyGenerationTest.HmacCheckKeySizes
840  *
841  * Verifies that keymaster supports all key sizes, and rejects all invalid key sizes.
842  */
TEST_P(NewKeyGenerationTest,HmacCheckKeySizes)843 TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
844     for (size_t key_size = 0; key_size <= 512; ++key_size) {
845         if (key_size < 64 || key_size % 8 != 0) {
846             // To keep this test from being very slow, we only test a random fraction of non-byte
847             // key sizes.  We test only ~10% of such cases. Since there are 392 of them, we expect
848             // to run ~40 of them in each run.
849             if (key_size % 8 == 0 || random() % 10 == 0) {
850                 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
851                           GenerateKey(AuthorizationSetBuilder()
852                                           .HmacKey(key_size)
853                                           .Digest(Digest::SHA_2_256)
854                                           .Authorization(TAG_MIN_MAC_LENGTH, 256)))
855                     << "HMAC key size " << key_size << " invalid";
856             }
857         } else {
858             EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
859                                                      .HmacKey(key_size)
860                                                      .Digest(Digest::SHA_2_256)
861                                                      .Authorization(TAG_MIN_MAC_LENGTH, 256)))
862                 << "Failed to generate HMAC key of size " << key_size;
863             CheckCharacteristics(key_blob_, key_characteristics_);
864             CheckedDeleteKey();
865         }
866     }
867 }
868 
869 /*
870  * NewKeyGenerationTest.HmacCheckMinMacLengths
871  *
872  * Verifies that keymaster supports all required MAC lengths and rejects all invalid lengths.  This
873  * test is probabilistic in order to keep the runtime down, but any failure prints out the specific
874  * MAC length that failed, so reproducing a failed run will be easy.
875  */
TEST_P(NewKeyGenerationTest,HmacCheckMinMacLengths)876 TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
877     for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
878         if (min_mac_length < 64 || min_mac_length % 8 != 0) {
879             // To keep this test from being very long, we only test a random fraction of non-byte
880             // lengths.  We test only ~10% of such cases. Since there are 172 of them, we expect to
881             // run ~17 of them in each run.
882             if (min_mac_length % 8 == 0 || random() % 10 == 0) {
883                 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
884                           GenerateKey(AuthorizationSetBuilder()
885                                           .HmacKey(128)
886                                           .Digest(Digest::SHA_2_256)
887                                           .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
888                     << "HMAC min mac length " << min_mac_length << " invalid.";
889             }
890         } else {
891             EXPECT_EQ(ErrorCode::OK,
892                       GenerateKey(AuthorizationSetBuilder()
893                                       .HmacKey(128)
894                                       .Digest(Digest::SHA_2_256)
895                                       .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
896                 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
897             CheckCharacteristics(key_blob_, key_characteristics_);
898             CheckedDeleteKey();
899         }
900     }
901 }
902 
903 /*
904  * NewKeyGenerationTest.HmacMultipleDigests
905  *
906  * Verifies that keymaster rejects HMAC key generation with multiple specified digest algorithms.
907  */
TEST_P(NewKeyGenerationTest,HmacMultipleDigests)908 TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
909     if (SecLevel() == SecurityLevel::STRONGBOX) return;
910 
911     ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
912               GenerateKey(AuthorizationSetBuilder()
913                               .HmacKey(128)
914                               .Digest(Digest::SHA1)
915                               .Digest(Digest::SHA_2_256)
916                               .Authorization(TAG_MIN_MAC_LENGTH, 128)));
917 }
918 
919 /*
920  * NewKeyGenerationTest.HmacDigestNone
921  *
922  * Verifies that keymaster rejects HMAC key generation with no digest or Digest::NONE
923  */
TEST_P(NewKeyGenerationTest,HmacDigestNone)924 TEST_P(NewKeyGenerationTest, HmacDigestNone) {
925     ASSERT_EQ(
926         ErrorCode::UNSUPPORTED_DIGEST,
927         GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH, 128)));
928 
929     ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
930               GenerateKey(AuthorizationSetBuilder()
931                               .HmacKey(128)
932                               .Digest(Digest::NONE)
933                               .Authorization(TAG_MIN_MAC_LENGTH, 128)));
934 }
935 
936 /**
937  * NewKeyGenerationTest.AesInvalidKeySize
938  *
939  * Verifies that specifying an invalid key size for AES key generation returns
940  * UNSUPPORTED_KEY_SIZE.
941  */
TEST_P(NewKeyGenerationTest,AesInvalidKeySize)942 TEST_P(NewKeyGenerationTest, AesInvalidKeySize) {
943     int32_t firstApiLevel = property_get_int32("ro.board.first_api_level", 0);
944     for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
945         if (key_size == 192 && SecLevel() == SecurityLevel::STRONGBOX && firstApiLevel < 31) {
946             continue;
947         }
948         ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
949                   GenerateKey(AuthorizationSetBuilder()
950                                       .Authorization(TAG_NO_AUTH_REQUIRED)
951                                       .AesEncryptionKey(key_size)
952                                       .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
953                                       .Padding(PaddingMode::NONE)));
954     }
955 }
956 
957 INSTANTIATE_KEYMASTER_HIDL_TEST(NewKeyGenerationTest);
958 
959 typedef KeymasterHidlTest SigningOperationsTest;
960 
961 /*
962  * SigningOperationsTest.RsaSuccess
963  *
964  * Verifies that raw RSA signature operations succeed.
965  */
TEST_P(SigningOperationsTest,RsaSuccess)966 TEST_P(SigningOperationsTest, RsaSuccess) {
967     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
968                                              .RsaSigningKey(2048, 65537)
969                                              .Digest(Digest::NONE)
970                                              .Padding(PaddingMode::NONE)
971                                              .Authorization(TAG_NO_AUTH_REQUIRED)));
972     string message = "12345678901234567890123456789012";
973     string signature = SignMessage(
974         message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
975 }
976 
977 /*
978  * SigningOperationsTest.RsaGetKeyCharacteristicsRequiresCorrectAppIdAppData
979  *
980  * Verifies that getting RSA key characteristics requires the correct app ID/data.
981  */
TEST_P(SigningOperationsTest,RsaGetKeyCharacteristicsRequiresCorrectAppIdAppData)982 TEST_P(SigningOperationsTest, RsaGetKeyCharacteristicsRequiresCorrectAppIdAppData) {
983     HidlBuf key_blob;
984     KeyCharacteristics key_characteristics;
985     ASSERT_EQ(ErrorCode::OK,
986               GenerateKey(AuthorizationSetBuilder()
987                                   .Authorization(TAG_NO_AUTH_REQUIRED)
988                                   .RsaSigningKey(2048, 65537)
989                                   .Digest(Digest::NONE)
990                                   .Padding(PaddingMode::NONE)
991                                   .Authorization(TAG_APPLICATION_ID, HidlBuf("clientid"))
992                                   .Authorization(TAG_APPLICATION_DATA, HidlBuf("appdata")),
993                           &key_blob, &key_characteristics));
994     CheckGetCharacteristics(key_blob, HidlBuf("clientid"), HidlBuf("appdata"),
995                             &key_characteristics);
996 }
997 
998 /*
999  * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
1000  *
1001  * Verifies that using an RSA key requires the correct app ID/data.
1002  */
TEST_P(SigningOperationsTest,RsaUseRequiresCorrectAppIdAppData)1003 TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
1004     ASSERT_EQ(ErrorCode::OK,
1005               GenerateKey(AuthorizationSetBuilder()
1006                                   .Authorization(TAG_NO_AUTH_REQUIRED)
1007                                   .RsaSigningKey(2048, 65537)
1008                                   .Digest(Digest::NONE)
1009                                   .Padding(PaddingMode::NONE)
1010                                   .Authorization(TAG_APPLICATION_ID, HidlBuf("clientid"))
1011                                   .Authorization(TAG_APPLICATION_DATA, HidlBuf("appdata"))));
1012     EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1013               Begin(KeyPurpose::SIGN,
1014                     AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1015     AbortIfNeeded();
1016     EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1017               Begin(KeyPurpose::SIGN,
1018                     AuthorizationSetBuilder()
1019                             .Digest(Digest::NONE)
1020                             .Padding(PaddingMode::NONE)
1021                             .Authorization(TAG_APPLICATION_ID, HidlBuf("clientid"))));
1022     AbortIfNeeded();
1023     EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1024               Begin(KeyPurpose::SIGN,
1025                     AuthorizationSetBuilder()
1026                             .Digest(Digest::NONE)
1027                             .Padding(PaddingMode::NONE)
1028                             .Authorization(TAG_APPLICATION_DATA, HidlBuf("appdata"))));
1029     AbortIfNeeded();
1030     EXPECT_EQ(ErrorCode::OK,
1031               Begin(KeyPurpose::SIGN,
1032                     AuthorizationSetBuilder()
1033                             .Digest(Digest::NONE)
1034                             .Padding(PaddingMode::NONE)
1035                             .Authorization(TAG_APPLICATION_DATA, HidlBuf("appdata"))
1036                             .Authorization(TAG_APPLICATION_ID, HidlBuf("clientid"))));
1037     AbortIfNeeded();
1038 }
1039 
1040 /*
1041  * SigningOperationsTest.RsaPssSha256Success
1042  *
1043  * Verifies that RSA-PSS signature operations succeed.
1044  */
TEST_P(SigningOperationsTest,RsaPssSha256Success)1045 TEST_P(SigningOperationsTest, RsaPssSha256Success) {
1046     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1047                                              .RsaSigningKey(2048, 65537)
1048                                              .Digest(Digest::SHA_2_256)
1049                                              .Padding(PaddingMode::RSA_PSS)
1050                                              .Authorization(TAG_NO_AUTH_REQUIRED)));
1051     // Use large message, which won't work without digesting.
1052     string message(1024, 'a');
1053     string signature = SignMessage(
1054         message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
1055 }
1056 
1057 /*
1058  * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
1059  *
1060  * Verifies that keymaster rejects signature operations that specify a padding mode when the key
1061  * supports only unpadded operations.
1062  */
TEST_P(SigningOperationsTest,RsaPaddingNoneDoesNotAllowOther)1063 TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
1064     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1065                                              .RsaSigningKey(2048, 65537)
1066                                              .Digest(Digest::NONE)
1067                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1068                                              .Padding(PaddingMode::NONE)));
1069     string message = "12345678901234567890123456789012";
1070     string signature;
1071 
1072     EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
1073               Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1074                                           .Digest(Digest::NONE)
1075                                           .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1076 }
1077 
1078 /*
1079  * SigningOperationsTest.NoUserConfirmation
1080  *
1081  * Verifies that keymaster rejects signing operations for keys with
1082  * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
1083  * presented.
1084  */
TEST_P(SigningOperationsTest,NoUserConfirmation)1085 TEST_P(SigningOperationsTest, NoUserConfirmation) {
1086     if (SecLevel() == SecurityLevel::STRONGBOX) return;
1087     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1088                                              .RsaSigningKey(1024, 65537)
1089                                              .Digest(Digest::NONE)
1090                                              .Padding(PaddingMode::NONE)
1091                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1092                                              .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)));
1093 
1094     const string message = "12345678901234567890123456789012";
1095     EXPECT_EQ(ErrorCode::OK,
1096               Begin(KeyPurpose::SIGN,
1097                     AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1098     string signature;
1099     EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
1100 }
1101 
1102 /*
1103  * SigningOperationsTest.RsaPkcs1Sha256Success
1104  *
1105  * Verifies that digested RSA-PKCS1 signature operations succeed.
1106  */
TEST_P(SigningOperationsTest,RsaPkcs1Sha256Success)1107 TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
1108     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1109                                              .RsaSigningKey(2048, 65537)
1110                                              .Digest(Digest::SHA_2_256)
1111                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1112                                              .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1113     string message(1024, 'a');
1114     string signature = SignMessage(message, AuthorizationSetBuilder()
1115                                                 .Digest(Digest::SHA_2_256)
1116                                                 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1117 }
1118 
1119 /*
1120  * SigningOperationsTest.RsaPkcs1NoDigestSuccess
1121  *
1122  * Verifies that undigested RSA-PKCS1 signature operations succeed.
1123  */
TEST_P(SigningOperationsTest,RsaPkcs1NoDigestSuccess)1124 TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
1125     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1126                                              .RsaSigningKey(2048, 65537)
1127                                              .Digest(Digest::NONE)
1128                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1129                                              .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1130     string message(53, 'a');
1131     string signature = SignMessage(
1132         message,
1133         AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1134 }
1135 
1136 /*
1137  * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
1138  *
1139  * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
1140  * given a too-long message.
1141  */
TEST_P(SigningOperationsTest,RsaPkcs1NoDigestTooLong)1142 TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
1143     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1144                                              .RsaSigningKey(2048, 65537)
1145                                              .Digest(Digest::NONE)
1146                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1147                                              .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1148     string message(257, 'a');
1149 
1150     EXPECT_EQ(ErrorCode::OK,
1151               Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1152                                           .Digest(Digest::NONE)
1153                                           .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1154     string signature;
1155     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
1156 }
1157 
1158 /*
1159  * SigningOperationsTest.RsaPssSha512TooSmallKey
1160  *
1161  * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
1162  * used with a key that is too small for the message.
1163  *
1164  * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the keymaster
1165  * specification requires that salt_size == digest_size, so the message will be digest_size * 2 +
1166  * 16. Such a message can only be signed by a given key if the key is at least that size. This test
1167  * uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large for a
1168  * 1024-bit key.
1169  */
TEST_P(SigningOperationsTest,RsaPssSha512TooSmallKey)1170 TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
1171     if (SecLevel() == SecurityLevel::STRONGBOX) return;
1172     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1173                                              .RsaSigningKey(1024, 65537)
1174                                              .Digest(Digest::SHA_2_512)
1175                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1176                                              .Padding(PaddingMode::RSA_PSS)));
1177     EXPECT_EQ(
1178         ErrorCode::INCOMPATIBLE_DIGEST,
1179         Begin(KeyPurpose::SIGN,
1180               AuthorizationSetBuilder().Digest(Digest::SHA_2_512).Padding(PaddingMode::RSA_PSS)));
1181 }
1182 
1183 /*
1184  * SigningOperationsTest.RsaNoPaddingTooLong
1185  *
1186  * Verifies that raw RSA signature operations fail with the correct error code when
1187  * given a too-long message.
1188  */
TEST_P(SigningOperationsTest,RsaNoPaddingTooLong)1189 TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
1190     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1191                                              .RsaSigningKey(2048, 65537)
1192                                              .Digest(Digest::NONE)
1193                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1194                                              .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1195     // One byte too long
1196     string message(2048 / 8 + 1, 'a');
1197     ASSERT_EQ(ErrorCode::OK,
1198               Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1199                                           .Digest(Digest::NONE)
1200                                           .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1201     string result;
1202     ErrorCode finish_error_code = Finish(message, &result);
1203     EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1204                 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1205 
1206     // Very large message that should exceed the transfer buffer size of any reasonable TEE.
1207     message = string(128 * 1024, 'a');
1208     ASSERT_EQ(ErrorCode::OK,
1209               Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1210                                           .Digest(Digest::NONE)
1211                                           .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1212     finish_error_code = Finish(message, &result);
1213     EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1214                 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1215 }
1216 
1217 /*
1218  * SigningOperationsTest.RsaAbort
1219  *
1220  * Verifies that operations can be aborted correctly.  Uses an RSA signing operation for the test,
1221  * but the behavior should be algorithm and purpose-independent.
1222  */
TEST_P(SigningOperationsTest,RsaAbort)1223 TEST_P(SigningOperationsTest, RsaAbort) {
1224     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1225                                              .RsaSigningKey(2048, 65537)
1226                                              .Digest(Digest::NONE)
1227                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1228                                              .Padding(PaddingMode::NONE)));
1229 
1230     ASSERT_EQ(ErrorCode::OK,
1231               Begin(KeyPurpose::SIGN,
1232                     AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1233     EXPECT_EQ(ErrorCode::OK, Abort(op_handle_));
1234 
1235     // Another abort should fail
1236     EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort(op_handle_));
1237 
1238     // Set to sentinel, so TearDown() doesn't try to abort again.
1239     op_handle_ = kOpHandleSentinel;
1240 }
1241 
1242 /*
1243  * SigningOperationsTest.RsaUnsupportedPadding
1244  *
1245  * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used with a
1246  * padding mode inappropriate for RSA.
1247  */
TEST_P(SigningOperationsTest,RsaUnsupportedPadding)1248 TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
1249     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1250                                              .RsaSigningKey(2048, 65537)
1251                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1252                                              .Digest(Digest::SHA_2_256 /* supported digest */)
1253                                              .Padding(PaddingMode::PKCS7)));
1254     ASSERT_EQ(
1255         ErrorCode::UNSUPPORTED_PADDING_MODE,
1256         Begin(KeyPurpose::SIGN,
1257               AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
1258 }
1259 
1260 /*
1261  * SigningOperationsTest.RsaPssNoDigest
1262  *
1263  * Verifies that RSA PSS operations fail when no digest is used.  PSS requires a digest.
1264  */
TEST_P(SigningOperationsTest,RsaNoDigest)1265 TEST_P(SigningOperationsTest, RsaNoDigest) {
1266     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1267                                              .RsaSigningKey(2048, 65537)
1268                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1269                                              .Digest(Digest::NONE)
1270                                              .Padding(PaddingMode::RSA_PSS)));
1271     ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
1272               Begin(KeyPurpose::SIGN,
1273                     AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
1274 
1275     ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1276               Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
1277 }
1278 
1279 /*
1280  * SigningOperationsTest.RsaPssNoDigest
1281  *
1282  * Verifies that RSA operations fail when no padding mode is specified.  PaddingMode::NONE is
1283  * supported in some cases (as validated in other tests), but a mode must be specified.
1284  */
TEST_P(SigningOperationsTest,RsaNoPadding)1285 TEST_P(SigningOperationsTest, RsaNoPadding) {
1286     // Padding must be specified
1287     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1288                                              .RsaKey(2048, 65537)
1289                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1290                                              .SigningKey()
1291                                              .Digest(Digest::NONE)));
1292     ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
1293               Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
1294 }
1295 
1296 /*
1297  * SigningOperationsTest.RsaShortMessage
1298  *
1299  * Verifies that raw RSA signatures succeed with a message shorter than the key size.
1300  */
TEST_P(SigningOperationsTest,RsaTooShortMessage)1301 TEST_P(SigningOperationsTest, RsaTooShortMessage) {
1302     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1303                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1304                                              .RsaSigningKey(2048, 65537)
1305                                              .Digest(Digest::NONE)
1306                                              .Padding(PaddingMode::NONE)));
1307 
1308     // Barely shorter
1309     string message(2048 / 8 - 1, 'a');
1310     SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1311 
1312     // Much shorter
1313     message = "a";
1314     SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1315 }
1316 
1317 /*
1318  * SigningOperationsTest.RsaSignWithEncryptionKey
1319  *
1320  * Verifies that RSA encryption keys cannot be used to sign.
1321  */
TEST_P(SigningOperationsTest,RsaSignWithEncryptionKey)1322 TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
1323     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1324                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1325                                              .RsaEncryptionKey(2048, 65537)
1326                                              .Digest(Digest::NONE)
1327                                              .Padding(PaddingMode::NONE)));
1328     ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
1329               Begin(KeyPurpose::SIGN,
1330                     AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1331 }
1332 
1333 /*
1334  * SigningOperationsTest.RsaSignTooLargeMessage
1335  *
1336  * Verifies that attempting a raw signature of a message which is the same length as the key, but
1337  * numerically larger than the public modulus, fails with the correct error.
1338  */
TEST_P(SigningOperationsTest,RsaSignTooLargeMessage)1339 TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
1340     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1341                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1342                                              .RsaSigningKey(2048, 65537)
1343                                              .Digest(Digest::NONE)
1344                                              .Padding(PaddingMode::NONE)));
1345 
1346     // Largest possible message will always be larger than the public modulus.
1347     string message(2048 / 8, static_cast<char>(0xff));
1348     ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1349                                                          .Authorization(TAG_NO_AUTH_REQUIRED)
1350                                                          .Digest(Digest::NONE)
1351                                                          .Padding(PaddingMode::NONE)));
1352     string signature;
1353     ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
1354 }
1355 
1356 /*
1357  * SigningOperationsTest.EcdsaAllSizesAndHashes
1358  *
1359  * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
1360  */
TEST_P(SigningOperationsTest,EcdsaAllSizesAndHashes)1361 TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
1362     for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1363         for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
1364             ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1365                                               .Authorization(TAG_NO_AUTH_REQUIRED)
1366                                               .EcdsaSigningKey(key_size)
1367                                               .Digest(digest));
1368             EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
1369                                             << " and digest " << digest;
1370             if (error != ErrorCode::OK) continue;
1371 
1372             string message(1024, 'a');
1373             if (digest == Digest::NONE) message.resize(key_size / 8);
1374             SignMessage(message, AuthorizationSetBuilder().Digest(digest));
1375             CheckedDeleteKey();
1376         }
1377     }
1378 }
1379 
1380 /*
1381  * SigningOperationsTest.EcdsaAllCurves
1382  *
1383  * Verifies that ECDSA operations succeed with all possible curves.
1384  */
TEST_P(SigningOperationsTest,EcdsaAllCurves)1385 TEST_P(SigningOperationsTest, EcdsaAllCurves) {
1386     for (auto curve : ValidCurves()) {
1387         ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1388                                           .Authorization(TAG_NO_AUTH_REQUIRED)
1389                                           .EcdsaSigningKey(curve)
1390                                           .Digest(Digest::SHA_2_256));
1391         EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
1392         if (error != ErrorCode::OK) continue;
1393 
1394         string message(1024, 'a');
1395         SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1396         CheckedDeleteKey();
1397     }
1398 }
1399 
1400 /*
1401  * SigningOperationsTest.EcdsaNoDigestHugeData
1402  *
1403  * Verifies that ECDSA operations support very large messages, even without digesting.  This should
1404  * work because ECDSA actually only signs the leftmost L_n bits of the message, however large it may
1405  * be.  Not using digesting is a bad idea, but in some cases digesting is done by the framework.
1406  */
TEST_P(SigningOperationsTest,EcdsaNoDigestHugeData)1407 TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
1408     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1409                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1410                                              .EcdsaSigningKey(256)
1411                                              .Digest(Digest::NONE)));
1412     string message(1 * 1024, 'a');
1413     SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
1414 }
1415 
1416 /*
1417  * SigningOperationsTest.EcGetKeyCharacteristicsRequiresCorrectAppIdAppData
1418  *
1419  * Verifies that getting EC key characteristics requires the correct app ID/data.
1420  */
TEST_P(SigningOperationsTest,EcGetKeyCharacteristicsRequiresCorrectAppIdAppData)1421 TEST_P(SigningOperationsTest, EcGetKeyCharacteristicsRequiresCorrectAppIdAppData) {
1422     HidlBuf key_blob;
1423     KeyCharacteristics key_characteristics;
1424     ASSERT_EQ(ErrorCode::OK,
1425               GenerateKey(AuthorizationSetBuilder()
1426                                   .Authorization(TAG_NO_AUTH_REQUIRED)
1427                                   .EcdsaSigningKey(256)
1428                                   .Digest(Digest::NONE)
1429                                   .Authorization(TAG_APPLICATION_ID, HidlBuf("clientid"))
1430                                   .Authorization(TAG_APPLICATION_DATA, HidlBuf("appdata")),
1431                           &key_blob, &key_characteristics));
1432     CheckGetCharacteristics(key_blob, HidlBuf("clientid"), HidlBuf("appdata"),
1433                             &key_characteristics);
1434 }
1435 
1436 /*
1437  * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
1438  *
1439  * Verifies that using an EC key requires the correct app ID/data.
1440  */
TEST_P(SigningOperationsTest,EcUseRequiresCorrectAppIdAppData)1441 TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
1442     ASSERT_EQ(ErrorCode::OK,
1443               GenerateKey(AuthorizationSetBuilder()
1444                                   .Authorization(TAG_NO_AUTH_REQUIRED)
1445                                   .EcdsaSigningKey(256)
1446                                   .Digest(Digest::NONE)
1447                                   .Authorization(TAG_APPLICATION_ID, HidlBuf("clientid"))
1448                                   .Authorization(TAG_APPLICATION_DATA, HidlBuf("appdata"))));
1449     EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1450               Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
1451     AbortIfNeeded();
1452     EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1453               Begin(KeyPurpose::SIGN,
1454                     AuthorizationSetBuilder()
1455                             .Digest(Digest::NONE)
1456                             .Authorization(TAG_APPLICATION_ID, HidlBuf("clientid"))));
1457     AbortIfNeeded();
1458     EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1459               Begin(KeyPurpose::SIGN,
1460                     AuthorizationSetBuilder()
1461                             .Digest(Digest::NONE)
1462                             .Authorization(TAG_APPLICATION_DATA, HidlBuf("appdata"))));
1463     AbortIfNeeded();
1464     EXPECT_EQ(ErrorCode::OK,
1465               Begin(KeyPurpose::SIGN,
1466                     AuthorizationSetBuilder()
1467                             .Digest(Digest::NONE)
1468                             .Authorization(TAG_APPLICATION_DATA, HidlBuf("appdata"))
1469                             .Authorization(TAG_APPLICATION_ID, HidlBuf("clientid"))));
1470     AbortIfNeeded();
1471 }
1472 
1473 /*
1474  * SigningOperationsTest.AesEcbSign
1475  *
1476  * Verifies that attempts to use AES keys to sign fail in the correct way.
1477  */
TEST_P(SigningOperationsTest,AesEcbSign)1478 TEST_P(SigningOperationsTest, AesEcbSign) {
1479     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1480                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1481                                              .SigningKey()
1482                                              .AesEncryptionKey(128)
1483                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
1484 
1485     AuthorizationSet out_params;
1486     EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1487               Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
1488     EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1489               Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
1490 }
1491 
1492 /*
1493  * SigningOperationsTest.HmacAllDigests
1494  *
1495  * Verifies that HMAC works with all digests.
1496  */
TEST_P(SigningOperationsTest,HmacAllDigests)1497 TEST_P(SigningOperationsTest, HmacAllDigests) {
1498     for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
1499         ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1500                                                  .Authorization(TAG_NO_AUTH_REQUIRED)
1501                                                  .HmacKey(128)
1502                                                  .Digest(digest)
1503                                                  .Authorization(TAG_MIN_MAC_LENGTH, 160)))
1504             << "Failed to create HMAC key with digest " << digest;
1505         string message = "12345678901234567890123456789012";
1506         string signature = MacMessage(message, digest, 160);
1507         EXPECT_EQ(160U / 8U, signature.size())
1508             << "Failed to sign with HMAC key with digest " << digest;
1509         CheckedDeleteKey();
1510     }
1511 }
1512 
1513 /*
1514  * SigningOperationsTest.HmacSha256TooLargeMacLength
1515  *
1516  * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the digest
1517  * size.
1518  */
TEST_P(SigningOperationsTest,HmacSha256TooLargeMacLength)1519 TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
1520     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1521                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1522                                              .HmacKey(128)
1523                                              .Digest(Digest::SHA_2_256)
1524                                              .Authorization(TAG_MIN_MAC_LENGTH, 256)));
1525     AuthorizationSet output_params;
1526     EXPECT_EQ(
1527         ErrorCode::UNSUPPORTED_MAC_LENGTH,
1528         Begin(
1529             KeyPurpose::SIGN, key_blob_,
1530             AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 264),
1531             &output_params, &op_handle_));
1532 }
1533 
1534 /*
1535  * SigningOperationsTest.HmacSha256TooSmallMacLength
1536  *
1537  * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
1538  * specified minimum MAC length.
1539  */
TEST_P(SigningOperationsTest,HmacSha256TooSmallMacLength)1540 TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
1541     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1542                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1543                                              .HmacKey(128)
1544                                              .Digest(Digest::SHA_2_256)
1545                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1546     AuthorizationSet output_params;
1547     EXPECT_EQ(
1548         ErrorCode::INVALID_MAC_LENGTH,
1549         Begin(
1550             KeyPurpose::SIGN, key_blob_,
1551             AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 120),
1552             &output_params, &op_handle_));
1553 }
1554 
1555 /*
1556  * SigningOperationsTest.HmacRfc4231TestCase3
1557  *
1558  * Validates against the test vectors from RFC 4231 test case 3.
1559  */
TEST_P(SigningOperationsTest,HmacRfc4231TestCase3)1560 TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
1561     string key(20, 0xaa);
1562     string message(50, 0xdd);
1563     uint8_t sha_224_expected[] = {
1564         0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
1565         0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
1566     };
1567     uint8_t sha_256_expected[] = {
1568         0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
1569         0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
1570         0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
1571     };
1572     uint8_t sha_384_expected[] = {
1573         0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
1574         0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
1575         0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
1576         0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
1577     };
1578     uint8_t sha_512_expected[] = {
1579         0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
1580         0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
1581         0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
1582         0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
1583         0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
1584     };
1585 
1586     CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1587     if (SecLevel() != SecurityLevel::STRONGBOX) {
1588         CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1589         CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1590         CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1591     }
1592 }
1593 
1594 /*
1595  * SigningOperationsTest.HmacRfc4231TestCase5
1596  *
1597  * Validates against the test vectors from RFC 4231 test case 5.
1598  */
TEST_P(SigningOperationsTest,HmacRfc4231TestCase5)1599 TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
1600     string key(20, 0x0c);
1601     string message = "Test With Truncation";
1602 
1603     uint8_t sha_224_expected[] = {
1604         0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
1605         0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
1606     };
1607     uint8_t sha_256_expected[] = {
1608         0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
1609         0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
1610     };
1611     uint8_t sha_384_expected[] = {
1612         0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
1613         0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
1614     };
1615     uint8_t sha_512_expected[] = {
1616         0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
1617         0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
1618     };
1619 
1620     CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1621     if (SecLevel() != SecurityLevel::STRONGBOX) {
1622         CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1623         CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1624         CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1625     }
1626 }
1627 
1628 INSTANTIATE_KEYMASTER_HIDL_TEST(SigningOperationsTest);
1629 
1630 typedef KeymasterHidlTest VerificationOperationsTest;
1631 
1632 /*
1633  * VerificationOperationsTest.RsaSuccess
1634  *
1635  * Verifies that a simple RSA signature/verification sequence succeeds.
1636  */
TEST_P(VerificationOperationsTest,RsaSuccess)1637 TEST_P(VerificationOperationsTest, RsaSuccess) {
1638     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1639                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1640                                              .RsaSigningKey(2048, 65537)
1641                                              .Digest(Digest::NONE)
1642                                              .Padding(PaddingMode::NONE)));
1643     string message = "12345678901234567890123456789012";
1644     string signature = SignMessage(
1645         message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1646     VerifyMessage(message, signature,
1647                   AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1648 }
1649 
1650 /*
1651  * VerificationOperationsTest.RsaSuccess
1652  *
1653  * Verifies RSA signature/verification for all padding modes and digests.
1654  */
TEST_P(VerificationOperationsTest,RsaAllPaddingsAndDigests)1655 TEST_P(VerificationOperationsTest, RsaAllPaddingsAndDigests) {
1656     auto authorizations = AuthorizationSetBuilder()
1657                               .Authorization(TAG_NO_AUTH_REQUIRED)
1658                               .RsaSigningKey(2048, 65537)
1659                               .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
1660                               .Padding(PaddingMode::NONE)
1661                               .Padding(PaddingMode::RSA_PSS)
1662                               .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN);
1663 
1664     ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
1665 
1666     string message(128, 'a');
1667     string corrupt_message(message);
1668     ++corrupt_message[corrupt_message.size() / 2];
1669 
1670     for (auto padding :
1671          {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
1672         for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
1673             if (padding == PaddingMode::NONE && digest != Digest::NONE) {
1674                 // Digesting only makes sense with padding.
1675                 continue;
1676             }
1677 
1678             if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
1679                 // PSS requires digesting.
1680                 continue;
1681             }
1682 
1683             string signature =
1684                 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
1685             VerifyMessage(message, signature,
1686                           AuthorizationSetBuilder().Digest(digest).Padding(padding));
1687 
1688             if (digest != Digest::NONE) {
1689                 // Verify with OpenSSL.
1690                 HidlBuf pubkey;
1691                 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey));
1692 
1693                 const uint8_t* p = pubkey.data();
1694                 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
1695                 ASSERT_TRUE(pkey.get());
1696 
1697                 EVP_MD_CTX digest_ctx;
1698                 EVP_MD_CTX_init(&digest_ctx);
1699                 EVP_PKEY_CTX* pkey_ctx;
1700                 const EVP_MD* md = openssl_digest(digest);
1701                 ASSERT_NE(md, nullptr);
1702                 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr /* engine */,
1703                                                   pkey.get()));
1704 
1705                 switch (padding) {
1706                     case PaddingMode::RSA_PSS:
1707                         EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
1708                         EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
1709                         break;
1710                     case PaddingMode::RSA_PKCS1_1_5_SIGN:
1711                         // PKCS1 is the default; don't need to set anything.
1712                         break;
1713                     default:
1714                         FAIL();
1715                         break;
1716                 }
1717 
1718                 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()));
1719                 EXPECT_EQ(1, EVP_DigestVerifyFinal(
1720                                  &digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
1721                                  signature.size()));
1722                 EVP_MD_CTX_cleanup(&digest_ctx);
1723             }
1724 
1725             // Corrupt signature shouldn't verify.
1726             string corrupt_signature(signature);
1727             ++corrupt_signature[corrupt_signature.size() / 2];
1728 
1729             EXPECT_EQ(ErrorCode::OK,
1730                       Begin(KeyPurpose::VERIFY,
1731                             AuthorizationSetBuilder().Digest(digest).Padding(padding)));
1732             string result;
1733             EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result));
1734 
1735             // Corrupt message shouldn't verify
1736             EXPECT_EQ(ErrorCode::OK,
1737                       Begin(KeyPurpose::VERIFY,
1738                             AuthorizationSetBuilder().Digest(digest).Padding(padding)));
1739             EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result));
1740         }
1741     }
1742 }
1743 
1744 /*
1745  * VerificationOperationsTest.RsaSuccess
1746  *
1747  * Verifies ECDSA signature/verification for all digests and curves.
1748  */
TEST_P(VerificationOperationsTest,EcdsaAllDigestsAndCurves)1749 TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndCurves) {
1750     auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
1751 
1752     string message = "1234567890";
1753     string corrupt_message = "2234567890";
1754     for (auto curve : ValidCurves()) {
1755         ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1756                                           .Authorization(TAG_NO_AUTH_REQUIRED)
1757                                           .EcdsaSigningKey(curve)
1758                                           .Digest(digests));
1759         EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
1760         if (error != ErrorCode::OK) {
1761             continue;
1762         }
1763 
1764         for (auto digest : digests) {
1765             string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
1766             VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
1767 
1768             // Verify with OpenSSL
1769             if (digest != Digest::NONE) {
1770                 HidlBuf pubkey;
1771                 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey))
1772                     << curve << ' ' << digest;
1773 
1774                 const uint8_t* p = pubkey.data();
1775                 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
1776                 ASSERT_TRUE(pkey.get());
1777 
1778                 EVP_MD_CTX digest_ctx;
1779                 EVP_MD_CTX_init(&digest_ctx);
1780                 EVP_PKEY_CTX* pkey_ctx;
1781                 const EVP_MD* md = openssl_digest(digest);
1782 
1783                 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr /* engine */,
1784                                                   pkey.get()))
1785                     << curve << ' ' << digest;
1786 
1787                 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()))
1788                     << curve << ' ' << digest;
1789 
1790                 EXPECT_EQ(1, EVP_DigestVerifyFinal(
1791                                  &digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
1792                                  signature.size()))
1793                     << curve << ' ' << digest;
1794 
1795                 EVP_MD_CTX_cleanup(&digest_ctx);
1796             }
1797 
1798             // Corrupt signature shouldn't verify.
1799             string corrupt_signature(signature);
1800             ++corrupt_signature[corrupt_signature.size() / 2];
1801 
1802             EXPECT_EQ(ErrorCode::OK,
1803                       Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
1804                 << curve << ' ' << digest;
1805 
1806             string result;
1807             EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result))
1808                 << curve << ' ' << digest;
1809 
1810             // Corrupt message shouldn't verify
1811             EXPECT_EQ(ErrorCode::OK,
1812                       Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
1813                 << curve << ' ' << digest;
1814 
1815             EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result))
1816                 << curve << ' ' << digest;
1817         }
1818 
1819         auto rc = DeleteKey();
1820         ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
1821     }
1822 }
1823 
1824 /*
1825  * VerificationOperationsTest.HmacSigningKeyCannotVerify
1826  *
1827  * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
1828  */
TEST_P(VerificationOperationsTest,HmacSigningKeyCannotVerify)1829 TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
1830     string key_material = "HelloThisIsAKey";
1831 
1832     HidlBuf signing_key, verification_key;
1833     KeyCharacteristics signing_key_chars, verification_key_chars;
1834     EXPECT_EQ(ErrorCode::OK,
1835               ImportKey(AuthorizationSetBuilder()
1836                             .Authorization(TAG_NO_AUTH_REQUIRED)
1837                             .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
1838                             .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
1839                             .Digest(Digest::SHA_2_256)
1840                             .Authorization(TAG_MIN_MAC_LENGTH, 160),
1841                         KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
1842     EXPECT_EQ(ErrorCode::OK,
1843               ImportKey(AuthorizationSetBuilder()
1844                             .Authorization(TAG_NO_AUTH_REQUIRED)
1845                             .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
1846                             .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
1847                             .Digest(Digest::SHA_2_256)
1848                             .Authorization(TAG_MIN_MAC_LENGTH, 160),
1849                         KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
1850 
1851     string message = "This is a message.";
1852     string signature = SignMessage(
1853         signing_key, message,
1854         AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
1855 
1856     // Signing key should not work.
1857     AuthorizationSet out_params;
1858     EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
1859               Begin(KeyPurpose::VERIFY, signing_key, AuthorizationSetBuilder().Digest(Digest::SHA_2_256),
1860                     &out_params, &op_handle_));
1861 
1862     // Verification key should work.
1863     VerifyMessage(verification_key, message, signature,
1864                   AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1865 
1866     CheckedDeleteKey(&signing_key);
1867     CheckedDeleteKey(&verification_key);
1868 }
1869 
1870 INSTANTIATE_KEYMASTER_HIDL_TEST(VerificationOperationsTest);
1871 
1872 typedef KeymasterHidlTest ExportKeyTest;
1873 
1874 /*
1875  * ExportKeyTest.RsaUnsupportedKeyFormat
1876  *
1877  * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
1878  */
TEST_P(ExportKeyTest,RsaUnsupportedKeyFormat)1879 TEST_P(ExportKeyTest, RsaUnsupportedKeyFormat) {
1880     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1881                                              .RsaSigningKey(2048, 65537)
1882                                              .Digest(Digest::NONE)
1883                                              .Padding(PaddingMode::NONE)));
1884     HidlBuf export_data;
1885     ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::PKCS8, &export_data));
1886 }
1887 
1888 /*
1889  * ExportKeyTest.RsaCorruptedKeyBlob
1890  *
1891  * Verifies that attempting to export RSA keys from corrupted key blobs fails.  This is essentially
1892  * a poor-man's key blob fuzzer.
1893  */
TEST_P(ExportKeyTest,RsaCorruptedKeyBlob)1894 TEST_P(ExportKeyTest, RsaCorruptedKeyBlob) {
1895     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1896                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1897                                              .RsaSigningKey(2048, 65537)
1898                                              .Digest(Digest::NONE)
1899                                              .Padding(PaddingMode::NONE)));
1900     for (size_t i = 0; i < key_blob_.size(); ++i) {
1901         HidlBuf corrupted(key_blob_);
1902         ++corrupted[i];
1903 
1904         HidlBuf export_data;
1905         EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1906                   ExportKey(KeyFormat::X509, corrupted, HidlBuf(), HidlBuf(), &export_data))
1907             << "Blob corrupted at offset " << i << " erroneously accepted as valid";
1908     }
1909 }
1910 
1911 /*
1912  * ExportKeyTest.RsaCorruptedKeyBlob
1913  *
1914  * Verifies that attempting to export ECDSA keys from corrupted key blobs fails.  This is
1915  * essentially a poor-man's key blob fuzzer.
1916  */
TEST_P(ExportKeyTest,EcCorruptedKeyBlob)1917 TEST_P(ExportKeyTest, EcCorruptedKeyBlob) {
1918     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1919                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1920                                              .EcdsaSigningKey(EcCurve::P_256)
1921                                              .Digest(Digest::NONE)));
1922     for (size_t i = 0; i < key_blob_.size(); ++i) {
1923         HidlBuf corrupted(key_blob_);
1924         ++corrupted[i];
1925 
1926         HidlBuf export_data;
1927         EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1928                   ExportKey(KeyFormat::X509, corrupted, HidlBuf(), HidlBuf(), &export_data))
1929             << "Blob corrupted at offset " << i << " erroneously accepted as valid";
1930     }
1931 }
1932 
1933 /*
1934  * ExportKeyTest.AesKeyUnexportable
1935  *
1936  * Verifies that attempting to export AES keys fails in the expected way.
1937  */
TEST_P(ExportKeyTest,AesKeyUnexportable)1938 TEST_P(ExportKeyTest, AesKeyUnexportable) {
1939     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1940                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1941                                              .AesEncryptionKey(128)
1942                                              .EcbMode()
1943                                              .Padding(PaddingMode::NONE)));
1944 
1945     HidlBuf export_data;
1946     EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::X509, &export_data));
1947     EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::PKCS8, &export_data));
1948     EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::RAW, &export_data));
1949 }
1950 
1951 INSTANTIATE_KEYMASTER_HIDL_TEST(ExportKeyTest);
1952 
1953 class ImportKeyTest : public KeymasterHidlTest {
1954    public:
1955     template <TagType tag_type, Tag tag, typename ValueT>
CheckCryptoParam(TypedTag<tag_type,tag> ttag,ValueT expected)1956     void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
1957         SCOPED_TRACE("CheckCryptoParam");
1958         if (IsSecure()) {
1959             EXPECT_TRUE(contains(key_characteristics_.hardwareEnforced, ttag, expected))
1960                 << "Tag " << tag << " with value " << expected << " not found";
1961             EXPECT_FALSE(contains(key_characteristics_.softwareEnforced, ttag))
1962                 << "Tag " << tag << " found";
1963         } else {
1964             EXPECT_TRUE(contains(key_characteristics_.softwareEnforced, ttag, expected))
1965                 << "Tag " << tag << " with value " << expected << " not found";
1966             EXPECT_FALSE(contains(key_characteristics_.hardwareEnforced, ttag))
1967                 << "Tag " << tag << " found";
1968         }
1969     }
1970 
CheckOrigin()1971     void CheckOrigin() {
1972         SCOPED_TRACE("CheckOrigin");
1973         if (IsSecure()) {
1974             EXPECT_TRUE(
1975                 contains(key_characteristics_.hardwareEnforced, TAG_ORIGIN, KeyOrigin::IMPORTED));
1976         } else {
1977             EXPECT_TRUE(
1978                 contains(key_characteristics_.softwareEnforced, TAG_ORIGIN, KeyOrigin::IMPORTED));
1979         }
1980     }
1981 };
1982 
1983 /*
1984  * ImportKeyTest.RsaSuccess
1985  *
1986  * Verifies that importing and using an RSA key pair works correctly.
1987  */
TEST_P(ImportKeyTest,RsaSuccess)1988 TEST_P(ImportKeyTest, RsaSuccess) {
1989     uint32_t keysize;
1990     string key;
1991     if (SecLevel() == SecurityLevel::STRONGBOX) {
1992         keysize = 2048;
1993         key = rsa_2048_key;
1994     } else {
1995         keysize = 1024;
1996         key = rsa_key;
1997     }
1998 
1999     ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2000                                                .Authorization(TAG_NO_AUTH_REQUIRED)
2001                                                .RsaSigningKey(keysize, 65537)
2002                                                .Digest(Digest::SHA_2_256)
2003                                                .Padding(PaddingMode::RSA_PSS),
2004                                        KeyFormat::PKCS8, key));
2005 
2006     CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
2007     CheckCryptoParam(TAG_KEY_SIZE, keysize);
2008     CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
2009     CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2010     CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
2011     CheckOrigin();
2012 
2013     string message(keysize / 8, 'a');
2014     auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
2015     string signature = SignMessage(message, params);
2016     VerifyMessage(message, signature, params);
2017 }
2018 
2019 /*
2020  * ImportKeyTest.RsaKeySizeMismatch
2021  *
2022  * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
2023  * correct way.
2024  */
TEST_P(ImportKeyTest,RsaKeySizeMismatch)2025 TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
2026     ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2027               ImportKey(AuthorizationSetBuilder()
2028                             .RsaSigningKey(2048 /* Doesn't match key */, 65537)
2029                             .Digest(Digest::NONE)
2030                             .Padding(PaddingMode::NONE),
2031                         KeyFormat::PKCS8, rsa_key));
2032 }
2033 
2034 /*
2035  * ImportKeyTest.RsaPublicExponentMismatch
2036  *
2037  * Verifies that importing an RSA key pair with a public exponent that doesn't match the key fails
2038  * in the correct way.
2039  */
TEST_P(ImportKeyTest,RsaPublicExponentMismatch)2040 TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
2041     ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2042               ImportKey(AuthorizationSetBuilder()
2043                             .RsaSigningKey(1024, 3 /* Doesn't match key */)
2044                             .Digest(Digest::NONE)
2045                             .Padding(PaddingMode::NONE),
2046                         KeyFormat::PKCS8, rsa_key));
2047 }
2048 
2049 /*
2050  * ImportKeyTest.EcdsaSuccess
2051  *
2052  * Verifies that importing and using an ECDSA P-256 key pair works correctly.
2053  */
TEST_P(ImportKeyTest,EcdsaSuccess)2054 TEST_P(ImportKeyTest, EcdsaSuccess) {
2055     ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2056                                            .Authorization(TAG_NO_AUTH_REQUIRED)
2057                                            .EcdsaSigningKey(256)
2058                                            .Digest(Digest::SHA_2_256),
2059                                        KeyFormat::PKCS8, ec_256_key));
2060 
2061     CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2062     CheckCryptoParam(TAG_KEY_SIZE, 256U);
2063     CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2064     CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2065 
2066     CheckOrigin();
2067 
2068     string message(32, 'a');
2069     auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2070     string signature = SignMessage(message, params);
2071     VerifyMessage(message, signature, params);
2072 }
2073 
2074 /*
2075  * ImportKeyTest.EcdsaP256RFC5915Success
2076  *
2077  * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works correctly.
2078  */
TEST_P(ImportKeyTest,EcdsaP256RFC5915Success)2079 TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
2080     ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2081                                                .Authorization(TAG_NO_AUTH_REQUIRED)
2082                                                .EcdsaSigningKey(256)
2083                                                .Digest(Digest::SHA_2_256),
2084                                        KeyFormat::PKCS8, ec_256_key_rfc5915));
2085 
2086     CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2087     CheckCryptoParam(TAG_KEY_SIZE, 256U);
2088     CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2089     CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2090 
2091     CheckOrigin();
2092 
2093     string message(32, 'a');
2094     auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2095     string signature = SignMessage(message, params);
2096     VerifyMessage(message, signature, params);
2097 }
2098 
2099 /*
2100  * ImportKeyTest.EcdsaP256SEC1Success
2101  *
2102  * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
2103  */
TEST_P(ImportKeyTest,EcdsaP256SEC1Success)2104 TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
2105     ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2106                                                .Authorization(TAG_NO_AUTH_REQUIRED)
2107                                                .EcdsaSigningKey(256)
2108                                                .Digest(Digest::SHA_2_256),
2109                                        KeyFormat::PKCS8, ec_256_key_sec1));
2110 
2111     CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2112     CheckCryptoParam(TAG_KEY_SIZE, 256U);
2113     CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2114     CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2115 
2116     CheckOrigin();
2117 
2118     string message(32, 'a');
2119     auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2120     string signature = SignMessage(message, params);
2121     VerifyMessage(message, signature, params);
2122 }
2123 
2124 /*
2125  * ImportKeyTest.Ecdsa521Success
2126  *
2127  * Verifies that importing and using an ECDSA P-521 key pair works correctly.
2128  */
TEST_P(ImportKeyTest,Ecdsa521Success)2129 TEST_P(ImportKeyTest, Ecdsa521Success) {
2130     if (SecLevel() == SecurityLevel::STRONGBOX) return;
2131     ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2132                                            .Authorization(TAG_NO_AUTH_REQUIRED)
2133                                            .EcdsaSigningKey(521)
2134                                            .Digest(Digest::SHA_2_256),
2135                                        KeyFormat::PKCS8, ec_521_key));
2136 
2137     CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2138     CheckCryptoParam(TAG_KEY_SIZE, 521U);
2139     CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2140     CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
2141     CheckOrigin();
2142 
2143     string message(32, 'a');
2144     auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2145     string signature = SignMessage(message, params);
2146     VerifyMessage(message, signature, params);
2147 }
2148 
2149 /*
2150  * ImportKeyTest.EcdsaSizeMismatch
2151  *
2152  * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
2153  * correct way.
2154  */
TEST_P(ImportKeyTest,EcdsaSizeMismatch)2155 TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
2156     ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2157               ImportKey(AuthorizationSetBuilder()
2158                             .EcdsaSigningKey(224 /* Doesn't match key */)
2159                             .Digest(Digest::NONE),
2160                         KeyFormat::PKCS8, ec_256_key));
2161 }
2162 
2163 /*
2164  * ImportKeyTest.EcdsaCurveMismatch
2165  *
2166  * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in the
2167  * correct way.
2168  */
TEST_P(ImportKeyTest,EcdsaCurveMismatch)2169 TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
2170     ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2171               ImportKey(AuthorizationSetBuilder()
2172                             .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
2173                             .Digest(Digest::NONE),
2174                         KeyFormat::PKCS8, ec_256_key));
2175 }
2176 
2177 /*
2178  * ImportKeyTest.AesSuccess
2179  *
2180  * Verifies that importing and using an AES key works.
2181  */
TEST_P(ImportKeyTest,AesSuccess)2182 TEST_P(ImportKeyTest, AesSuccess) {
2183     string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2184     ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2185                                            .Authorization(TAG_NO_AUTH_REQUIRED)
2186                                            .AesEncryptionKey(key.size() * 8)
2187                                            .EcbMode()
2188                                            .Padding(PaddingMode::PKCS7),
2189                                        KeyFormat::RAW, key));
2190 
2191     CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
2192     CheckCryptoParam(TAG_KEY_SIZE, 128U);
2193     CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
2194     CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
2195     CheckOrigin();
2196 
2197     string message = "Hello World!";
2198     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2199     string ciphertext = EncryptMessage(message, params);
2200     string plaintext = DecryptMessage(ciphertext, params);
2201     EXPECT_EQ(message, plaintext);
2202 }
2203 
2204 /*
2205  * ImportKeyTest.AesSuccess
2206  *
2207  * Verifies that importing and using an HMAC key works.
2208  */
TEST_P(ImportKeyTest,HmacKeySuccess)2209 TEST_P(ImportKeyTest, HmacKeySuccess) {
2210     string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2211     ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2212                                            .Authorization(TAG_NO_AUTH_REQUIRED)
2213                                            .HmacKey(key.size() * 8)
2214                                            .Digest(Digest::SHA_2_256)
2215                                            .Authorization(TAG_MIN_MAC_LENGTH, 256),
2216                                        KeyFormat::RAW, key));
2217 
2218     CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
2219     CheckCryptoParam(TAG_KEY_SIZE, 128U);
2220     CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2221     CheckOrigin();
2222 
2223     string message = "Hello World!";
2224     string signature = MacMessage(message, Digest::SHA_2_256, 256);
2225     VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2226 }
2227 
2228 INSTANTIATE_KEYMASTER_HIDL_TEST(ImportKeyTest);
2229 
2230 auto wrapped_key = hex2str(
2231     "3082017902010004820100934bf94e2aa28a3f83c9f79297250262fbe3276b5a1c91159bbfa3ef8957aac84b59b30b"
2232     "455a79c2973480823d8b3863c3deef4a8e243590268d80e18751a0e130f67ce6a1ace9f79b95e097474febc981195b"
2233     "1d13a69086c0863f66a7b7fdb48792227b1ac5e2489febdf087ab5486483033a6f001ca5d1ec1e27f5c30f4cec2642"
2234     "074a39ae68aee552e196627a8e3d867e67a8c01b11e75f13cca0a97ab668b50cda07a8ecb7cd8e3dd7009c9636534f"
2235     "6f239cffe1fc8daa466f78b676c7119efb96bce4e69ca2a25d0b34ed9c3ff999b801597d5220e307eaa5bee507fb94"
2236     "d1fa69f9e519b2de315bac92c36f2ea1fa1df4478c0ddedeae8c70e0233cd098040cd796b02c370f1fa4cc0124f130"
2237     "2e0201033029a1083106020100020101a203020120a30402020100a4053103020101a6053103020140bf8377020500"
2238     "0420ccd540855f833a5e1480bfd2d36faf3aeee15df5beabe2691bc82dde2a7aa910041064c9f689c60ff6223ab6e6"
2239     "999e0eb6e5");
2240 
2241 auto wrapped_key_masked = hex2str(
2242     "3082017902010004820100aad93ed5924f283b4bb5526fbe7a1412f9d9749ec30db9062b29e574a8546f33c8873245"
2243     "2f5b8e6a391ee76c39ed1712c61d8df6213dec1cffbc17a8c6d04c7b30893d8daa9b2015213e21946821553207f8f9"
2244     "931c4caba23ed3bee28b36947e47f10e0a5c3dc51c988a628daad3e5e1f4005e79c2d5a96c284b4b8d7e4948f331e5"
2245     "b85dd5a236f85579f3ea1d1b848487470bdb0ab4f81a12bee42c99fe0df4bee3759453e69ad1d68a809ce06b949f76"
2246     "94a990429b2fe81e066ff43e56a21602db70757922a4bcc23ab89f1e35da77586775f423e519c2ea394caf48a28d0c"
2247     "8020f1dcf6b3a68ec246f615ae96dae9a079b1f6eb959033c1af5c125fd94168040c6d9721d08589581ab49204a330"
2248     "2e0201033029a1083106020100020101a203020120a30402020100a4053103020101a6053103020140bf8377020500"
2249     "0420a61c6e247e25b3e6e69aa78eb03c2d4ac20d1f99a9a024a76f35c8e2cab9b68d04102560c70109ae67c030f00b"
2250     "98b512a670");
2251 
2252 auto wrapping_key = hex2str(
2253     "308204be020100300d06092a864886f70d0101010500048204a8308204a40201000282010100aec367931d8900ce56"
2254     "b0067f7d70e1fc653f3f34d194c1fed50018fb43db937b06e673a837313d56b1c725150a3fef86acbddc41bb759c28"
2255     "54eae32d35841efb5c18d82bc90a1cb5c1d55adf245b02911f0b7cda88c421ff0ebafe7c0d23be312d7bd5921ffaea"
2256     "1347c157406fef718f682643e4e5d33c6703d61c0cf7ac0bf4645c11f5c1374c3886427411c449796792e0bef75dec"
2257     "858a2123c36753e02a95a96d7c454b504de385a642e0dfc3e60ac3a7ee4991d0d48b0172a95f9536f02ba13cecccb9"
2258     "2b727db5c27e5b2f5cec09600b286af5cf14c42024c61ddfe71c2a8d7458f185234cb00e01d282f10f8fc6721d2aed"
2259     "3f4833cca2bd8fa62821dd55020301000102820100431447b6251908112b1ee76f99f3711a52b6630960046c2de70d"
2260     "e188d833f8b8b91e4d785caeeeaf4f0f74414e2cda40641f7fe24f14c67a88959bdb27766df9e710b630a03adc683b"
2261     "5d2c43080e52bee71e9eaeb6de297a5fea1072070d181c822bccff087d63c940ba8a45f670feb29fb4484d1c95e6d2"
2262     "579ba02aae0a00900c3ebf490e3d2cd7ee8d0e20c536e4dc5a5097272888cddd7e91f228b1c4d7474c55b8fcd618c4"
2263     "a957bbddd5ad7407cc312d8d98a5caf7e08f4a0d6b45bb41c652659d5a5ba05b663737a8696281865ba20fbdd7f851"
2264     "e6c56e8cbe0ddbbf24dc03b2d2cb4c3d540fb0af52e034a2d06698b128e5f101e3b51a34f8d8b4f8618102818100de"
2265     "392e18d682c829266cc3454e1d6166242f32d9a1d10577753e904ea7d08bff841be5bac82a164c5970007047b8c517"
2266     "db8f8f84e37bd5988561bdf503d4dc2bdb38f885434ae42c355f725c9a60f91f0788e1f1a97223b524b5357fdf72e2"
2267     "f696bab7d78e32bf92ba8e1864eab1229e91346130748a6e3c124f9149d71c743502818100c95387c0f9d35f137b57"
2268     "d0d65c397c5e21cc251e47008ed62a542409c8b6b6ac7f8967b3863ca645fcce49582a9aa17349db6c4a95affdae0d"
2269     "ae612e1afac99ed39a2d934c880440aed8832f9843163a47f27f392199dc1202f9a0f9bd08308007cb1e4e7f583093"
2270     "66a7de25f7c3c9b880677c068e1be936e81288815252a8a102818057ff8ca1895080b2cae486ef0adfd791fb0235c0"
2271     "b8b36cd6c136e52e4085f4ea5a063212a4f105a3764743e53281988aba073f6e0027298e1c4378556e0efca0e14ece"
2272     "1af76ad0b030f27af6f0ab35fb73a060d8b1a0e142fa2647e93b32e36d8282ae0a4de50ab7afe85500a16f43a64719"
2273     "d6e2b9439823719cd08bcd03178102818100ba73b0bb28e3f81e9bd1c568713b101241acc607976c4ddccc90e65b65"
2274     "56ca31516058f92b6e09f3b160ff0e374ec40d78ae4d4979fde6ac06a1a400c61dd31254186af30b22c10582a8a43e"
2275     "34fe949c5f3b9755bae7baa7b7b7a6bd03b38cef55c86885fc6c1978b9cee7ef33da507c9df6b9277cff1e6aaa5d57"
2276     "aca528466102818100c931617c77829dfb1270502be9195c8f2830885f57dba869536811e6864236d0c4736a0008a1"
2277     "45af36b8357a7c3d139966d04c4e00934ea1aede3bb6b8ec841dc95e3f579751e2bfdfe27ae778983f959356210723"
2278     "287b0affcc9f727044d48c373f1babde0724fa17a4fd4da0902c7c9b9bf27ba61be6ad02dfddda8f4e6822");
2279 
2280 string zero_masking_key =
2281     hex2str("0000000000000000000000000000000000000000000000000000000000000000");
2282 string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
2283 
2284 class ImportWrappedKeyTest : public KeymasterHidlTest {};
2285 
TEST_P(ImportWrappedKeyTest,Success)2286 TEST_P(ImportWrappedKeyTest, Success) {
2287     auto wrapping_key_desc = AuthorizationSetBuilder()
2288                                  .RsaEncryptionKey(2048, 65537)
2289                                  .Digest(Digest::SHA_2_256)
2290                                  .Padding(PaddingMode::RSA_OAEP)
2291                                  .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY);
2292 
2293     ASSERT_EQ(ErrorCode::OK,
2294               ImportWrappedKey(
2295                   wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
2296                   AuthorizationSetBuilder()
2297                       .Digest(Digest::SHA_2_256)
2298                       .Padding(PaddingMode::RSA_OAEP)));
2299 
2300     string message = "Hello World!";
2301     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2302     string ciphertext = EncryptMessage(message, params);
2303     string plaintext = DecryptMessage(ciphertext, params);
2304     EXPECT_EQ(message, plaintext);
2305 }
2306 
TEST_P(ImportWrappedKeyTest,SuccessMasked)2307 TEST_P(ImportWrappedKeyTest, SuccessMasked) {
2308     auto wrapping_key_desc = AuthorizationSetBuilder()
2309                                  .RsaEncryptionKey(2048, 65537)
2310                                  .Digest(Digest::SHA_2_256)
2311                                  .Padding(PaddingMode::RSA_OAEP)
2312                                  .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY);
2313 
2314     ASSERT_EQ(ErrorCode::OK,
2315               ImportWrappedKey(
2316                   wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
2317                   AuthorizationSetBuilder()
2318                       .Digest(Digest::SHA_2_256)
2319                       .Padding(PaddingMode::RSA_OAEP)));
2320 }
2321 
TEST_P(ImportWrappedKeyTest,WrongMask)2322 TEST_P(ImportWrappedKeyTest, WrongMask) {
2323     auto wrapping_key_desc = AuthorizationSetBuilder()
2324                                  .RsaEncryptionKey(2048, 65537)
2325                                  .Digest(Digest::SHA_2_256)
2326                                  .Padding(PaddingMode::RSA_OAEP)
2327                                  .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY);
2328 
2329     ASSERT_EQ(ErrorCode::VERIFICATION_FAILED,
2330               ImportWrappedKey(
2331                   wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
2332                   AuthorizationSetBuilder()
2333                       .Digest(Digest::SHA_2_256)
2334                       .Padding(PaddingMode::RSA_OAEP)));
2335 }
2336 
TEST_P(ImportWrappedKeyTest,WrongPurpose)2337 TEST_P(ImportWrappedKeyTest, WrongPurpose) {
2338     auto wrapping_key_desc = AuthorizationSetBuilder()
2339                                  .RsaEncryptionKey(2048, 65537)
2340                                  .Digest(Digest::SHA_2_256)
2341                                  .Padding(PaddingMode::RSA_OAEP);
2342 
2343     ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2344               ImportWrappedKey(
2345                   wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
2346                   AuthorizationSetBuilder()
2347                       .Digest(Digest::SHA_2_256)
2348                       .Padding(PaddingMode::RSA_OAEP)));
2349 }
2350 
2351 INSTANTIATE_KEYMASTER_HIDL_TEST(ImportWrappedKeyTest);
2352 
2353 typedef KeymasterHidlTest EncryptionOperationsTest;
2354 
2355 /*
2356  * EncryptionOperationsTest.RsaNoPaddingSuccess
2357  *
2358  * Verifies that raw RSA encryption works.
2359  */
TEST_P(EncryptionOperationsTest,RsaNoPaddingSuccess)2360 TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
2361     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2362                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2363                                              .RsaEncryptionKey(2048, 65537)
2364                                              .Padding(PaddingMode::NONE)));
2365 
2366     string message = string(2048 / 8, 'a');
2367     auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2368     string ciphertext1 = EncryptMessage(message, params);
2369     EXPECT_EQ(2048U / 8, ciphertext1.size());
2370 
2371     string ciphertext2 = EncryptMessage(message, params);
2372     EXPECT_EQ(2048U / 8, ciphertext2.size());
2373 
2374     // Unpadded RSA is deterministic
2375     EXPECT_EQ(ciphertext1, ciphertext2);
2376 }
2377 
2378 /*
2379  * EncryptionOperationsTest.RsaNoPaddingShortMessage
2380  *
2381  * Verifies that raw RSA encryption of short messages works.
2382  */
TEST_P(EncryptionOperationsTest,RsaNoPaddingShortMessage)2383 TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
2384     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2385                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2386                                              .RsaEncryptionKey(2048, 65537)
2387                                              .Padding(PaddingMode::NONE)));
2388 
2389     string message = "1";
2390     auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2391 
2392     string ciphertext = EncryptMessage(message, params);
2393     EXPECT_EQ(2048U / 8, ciphertext.size());
2394 
2395     string expected_plaintext = string(2048U / 8 - 1, 0) + message;
2396     string plaintext = DecryptMessage(ciphertext, params);
2397 
2398     EXPECT_EQ(expected_plaintext, plaintext);
2399 
2400     // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
2401     message = static_cast<char>(1);
2402     ciphertext = EncryptMessage(message, params);
2403     EXPECT_EQ(2048U / 8, ciphertext.size());
2404     EXPECT_EQ(ciphertext, string(2048U / 8 - 1, 0) + message);
2405 }
2406 
2407 /*
2408  * EncryptionOperationsTest.RsaNoPaddingTooLong
2409  *
2410  * Verifies that raw RSA encryption of too-long messages fails in the expected way.
2411  */
TEST_P(EncryptionOperationsTest,RsaNoPaddingTooLong)2412 TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
2413     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2414                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2415                                              .RsaEncryptionKey(2048, 65537)
2416                                              .Padding(PaddingMode::NONE)));
2417 
2418     string message(2048 / 8 + 1, 'a');
2419 
2420     auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2421     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2422 
2423     string result;
2424     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
2425 }
2426 
2427 /*
2428  * EncryptionOperationsTest.RsaNoPaddingTooLarge
2429  *
2430  * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected way.
2431  */
TEST_P(EncryptionOperationsTest,RsaNoPaddingTooLarge)2432 TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLarge) {
2433     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2434                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2435                                              .RsaEncryptionKey(2048, 65537)
2436                                              .Padding(PaddingMode::NONE)));
2437 
2438     HidlBuf exported;
2439     ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &exported));
2440 
2441     const uint8_t* p = exported.data();
2442     EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr /* alloc new */, &p, exported.size()));
2443     RSA_Ptr rsa(EVP_PKEY_get1_RSA(pkey.get()));
2444 
2445     size_t modulus_len = BN_num_bytes(rsa->n);
2446     ASSERT_EQ(2048U / 8, modulus_len);
2447     std::unique_ptr<uint8_t[]> modulus_buf(new uint8_t[modulus_len]);
2448     BN_bn2bin(rsa->n, modulus_buf.get());
2449 
2450     // The modulus is too big to encrypt.
2451     string message(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
2452 
2453     auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2454     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2455 
2456     string result;
2457     EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &result));
2458 
2459     // One smaller than the modulus is okay.
2460     BN_sub(rsa->n, rsa->n, BN_value_one());
2461     modulus_len = BN_num_bytes(rsa->n);
2462     ASSERT_EQ(2048U / 8, modulus_len);
2463     BN_bn2bin(rsa->n, modulus_buf.get());
2464     message = string(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
2465     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2466     EXPECT_EQ(ErrorCode::OK, Finish(message, &result));
2467 }
2468 
2469 /*
2470  * EncryptionOperationsTest.RsaOaepSuccess
2471  *
2472  * Verifies that RSA-OAEP encryption operations work, with all digests.
2473  */
TEST_P(EncryptionOperationsTest,RsaOaepSuccess)2474 TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
2475     auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
2476 
2477     size_t key_size = 2048;  // Need largish key for SHA-512 test.
2478     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2479                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2480                                              .RsaEncryptionKey(key_size, 65537)
2481                                              .Padding(PaddingMode::RSA_OAEP)
2482                                              .Digest(digests)));
2483 
2484     string message = "Hello";
2485 
2486     for (auto digest : digests) {
2487         auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
2488         string ciphertext1 = EncryptMessage(message, params);
2489         if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
2490         EXPECT_EQ(key_size / 8, ciphertext1.size());
2491 
2492         string ciphertext2 = EncryptMessage(message, params);
2493         EXPECT_EQ(key_size / 8, ciphertext2.size());
2494 
2495         // OAEP randomizes padding so every result should be different (with astronomically high
2496         // probability).
2497         EXPECT_NE(ciphertext1, ciphertext2);
2498 
2499         string plaintext1 = DecryptMessage(ciphertext1, params);
2500         EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
2501         string plaintext2 = DecryptMessage(ciphertext2, params);
2502         EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
2503 
2504         // Decrypting corrupted ciphertext should fail.
2505         size_t offset_to_corrupt = random() % ciphertext1.size();
2506         char corrupt_byte;
2507         do {
2508             corrupt_byte = static_cast<char>(random() % 256);
2509         } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2510         ciphertext1[offset_to_corrupt] = corrupt_byte;
2511 
2512         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2513         string result;
2514         EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2515         EXPECT_EQ(0U, result.size());
2516     }
2517 }
2518 
2519 /*
2520  * EncryptionOperationsTest.RsaOaepInvalidDigest
2521  *
2522  * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2523  * without a digest.
2524  */
TEST_P(EncryptionOperationsTest,RsaOaepInvalidDigest)2525 TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
2526     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2527                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2528                                              .RsaEncryptionKey(2048, 65537)
2529                                              .Padding(PaddingMode::RSA_OAEP)
2530                                              .Digest(Digest::NONE)));
2531     string message = "Hello World!";
2532 
2533     auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
2534     EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2535 }
2536 
2537 /*
2538  * EncryptionOperationsTest.RsaOaepInvalidDigest
2539  *
2540  * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt with a
2541  * different digest than was used to encrypt.
2542  */
TEST_P(EncryptionOperationsTest,RsaOaepDecryptWithWrongDigest)2543 TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
2544     if (SecLevel() == SecurityLevel::STRONGBOX) return;
2545 
2546     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2547                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2548                                              .RsaEncryptionKey(1024, 65537)
2549                                              .Padding(PaddingMode::RSA_OAEP)
2550                                              .Digest(Digest::SHA_2_224, Digest::SHA_2_256)));
2551     string message = "Hello World!";
2552     string ciphertext = EncryptMessage(
2553         message,
2554         AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
2555 
2556     EXPECT_EQ(
2557         ErrorCode::OK,
2558         Begin(KeyPurpose::DECRYPT,
2559               AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP)));
2560     string result;
2561     EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
2562     EXPECT_EQ(0U, result.size());
2563 }
2564 
2565 /*
2566  * EncryptionOperationsTest.RsaOaepTooLarge
2567  *
2568  * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
2569  * too-large message.
2570  */
TEST_P(EncryptionOperationsTest,RsaOaepTooLarge)2571 TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
2572     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2573                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2574                                              .RsaEncryptionKey(2048, 65537)
2575                                              .Padding(PaddingMode::RSA_OAEP)
2576                                              .Digest(Digest::SHA_2_256)));
2577     constexpr size_t digest_size = 256 /* SHA_2_256 */ / 8;
2578     constexpr size_t oaep_overhead = 2 * digest_size + 2;
2579     string message(2048 / 8 - oaep_overhead + 1, 'a');
2580     EXPECT_EQ(ErrorCode::OK,
2581               Begin(KeyPurpose::ENCRYPT,
2582                     AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::SHA_2_256)));
2583     string result;
2584     auto error = Finish(message, &result);
2585     EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2586     EXPECT_EQ(0U, result.size());
2587 }
2588 
2589 /*
2590  * EncryptionOperationsTest.RsaPkcs1Success
2591  *
2592  * Verifies that RSA PKCS encryption/decrypts works.
2593  */
TEST_P(EncryptionOperationsTest,RsaPkcs1Success)2594 TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
2595     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2596                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2597                                              .RsaEncryptionKey(2048, 65537)
2598                                              .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)));
2599 
2600     string message = "Hello World!";
2601     auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2602     string ciphertext1 = EncryptMessage(message, params);
2603     // Die here on failure because we try to modify ciphertext1 below
2604     ASSERT_EQ(2048U / 8, ciphertext1.size()) << "Failed to encrypt the message";
2605 
2606     string ciphertext2 = EncryptMessage(message, params);
2607     EXPECT_EQ(2048U / 8, ciphertext2.size());
2608 
2609     // PKCS1 v1.5 randomizes padding so every result should be different.
2610     EXPECT_NE(ciphertext1, ciphertext2);
2611 
2612     string plaintext = DecryptMessage(ciphertext1, params);
2613     EXPECT_EQ(message, plaintext);
2614 
2615     // Decrypting corrupted ciphertext should fail.
2616     size_t offset_to_corrupt = random() % ciphertext1.size();
2617     char corrupt_byte;
2618     do {
2619         corrupt_byte = static_cast<char>(random() % 256);
2620     } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2621     ciphertext1[offset_to_corrupt] = corrupt_byte;
2622 
2623     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2624     string result;
2625     EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2626     EXPECT_EQ(0U, result.size());
2627 }
2628 
2629 /*
2630  * EncryptionOperationsTest.RsaPkcs1TooLarge
2631  *
2632  * Verifies that RSA PKCS encryption fails in the correct way when the mssage is too large.
2633  */
TEST_P(EncryptionOperationsTest,RsaPkcs1TooLarge)2634 TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
2635     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2636                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2637                                              .RsaEncryptionKey(2048, 65537)
2638                                              .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)));
2639     string message(2048 / 8 - 10, 'a');
2640 
2641     auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2642     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2643     string result;
2644     auto error = Finish(message, &result);
2645     EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2646     EXPECT_EQ(0U, result.size());
2647 }
2648 
2649 /*
2650  * EncryptionOperationsTest.EcdsaEncrypt
2651  *
2652  * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
2653  */
TEST_P(EncryptionOperationsTest,EcdsaEncrypt)2654 TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
2655     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2656                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2657                                              .EcdsaSigningKey(256)
2658                                              .Digest(Digest::NONE)));
2659     auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
2660     ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
2661     ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
2662 }
2663 
2664 /*
2665  * EncryptionOperationsTest.HmacEncrypt
2666  *
2667  * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
2668  */
TEST_P(EncryptionOperationsTest,HmacEncrypt)2669 TEST_P(EncryptionOperationsTest, HmacEncrypt) {
2670     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2671                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2672                                              .HmacKey(128)
2673                                              .Digest(Digest::SHA_2_256)
2674                                              .Padding(PaddingMode::NONE)
2675                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2676     auto params = AuthorizationSetBuilder()
2677                       .Digest(Digest::SHA_2_256)
2678                       .Padding(PaddingMode::NONE)
2679                       .Authorization(TAG_MAC_LENGTH, 128);
2680     ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
2681     ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
2682 }
2683 
2684 /*
2685  * EncryptionOperationsTest.AesEcbRoundTripSuccess
2686  *
2687  * Verifies that AES ECB mode works.
2688  */
TEST_P(EncryptionOperationsTest,AesEcbRoundTripSuccess)2689 TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
2690     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2691                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2692                                              .AesEncryptionKey(128)
2693                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2694                                              .Padding(PaddingMode::NONE)));
2695 
2696     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2697 
2698     // Two-block message.
2699     string message = "12345678901234567890123456789012";
2700     string ciphertext1 = EncryptMessage(message, params);
2701     EXPECT_EQ(message.size(), ciphertext1.size());
2702 
2703     string ciphertext2 = EncryptMessage(string(message), params);
2704     EXPECT_EQ(message.size(), ciphertext2.size());
2705 
2706     // ECB is deterministic.
2707     EXPECT_EQ(ciphertext1, ciphertext2);
2708 
2709     string plaintext = DecryptMessage(ciphertext1, params);
2710     EXPECT_EQ(message, plaintext);
2711 }
2712 
2713 /*
2714  * EncryptionOperationsTest.AesEcbRoundTripSuccess
2715  *
2716  * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
2717  */
TEST_P(EncryptionOperationsTest,AesWrongMode)2718 TEST_P(EncryptionOperationsTest, AesWrongMode) {
2719     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2720                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2721                                              .AesEncryptionKey(128)
2722                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
2723                                              .Padding(PaddingMode::NONE)));
2724     // Two-block message.
2725     string message = "12345678901234567890123456789012";
2726     EXPECT_EQ(
2727         ErrorCode::INCOMPATIBLE_BLOCK_MODE,
2728         Begin(KeyPurpose::ENCRYPT,
2729               AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
2730 }
2731 
2732 /*
2733  * EncryptionOperationsTest.AesWrongPurpose
2734  *
2735  * Verifies that AES encryption fails in the correct way when an unauthorized purpose is specified.
2736  */
TEST_P(EncryptionOperationsTest,AesWrongPurpose)2737 TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
2738     auto err = GenerateKey(AuthorizationSetBuilder()
2739                                    .Authorization(TAG_NO_AUTH_REQUIRED)
2740                                    .AesKey(128)
2741                                    .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
2742                                    .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
2743                                    .Authorization(TAG_MIN_MAC_LENGTH, 128)
2744                                    .Padding(PaddingMode::NONE));
2745     ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
2746 
2747     err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
2748                                              .BlockMode(BlockMode::GCM)
2749                                              .Padding(PaddingMode::NONE)
2750                                              .Authorization(TAG_MAC_LENGTH, 128));
2751     EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
2752 
2753     CheckedDeleteKey();
2754 
2755     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2756                                                  .Authorization(TAG_NO_AUTH_REQUIRED)
2757                                                  .AesKey(128)
2758                                                  .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
2759                                                  .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
2760                                                  .Authorization(TAG_MIN_MAC_LENGTH, 128)
2761                                                  .Padding(PaddingMode::NONE)));
2762 
2763     err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
2764                                              .BlockMode(BlockMode::GCM)
2765                                              .Padding(PaddingMode::NONE)
2766                                              .Authorization(TAG_MAC_LENGTH, 128));
2767     EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
2768 }
2769 
2770 /*
2771  * EncryptionOperationsTest.AesEcbNoPaddingWrongInputSize
2772  *
2773  * Verifies that AES encryption fails in the correct way when provided an input that is not a
2774  * multiple of the block size and no padding is specified.
2775  */
TEST_P(EncryptionOperationsTest,AesEcbNoPaddingWrongInputSize)2776 TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
2777     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2778                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2779                                              .AesEncryptionKey(128)
2780                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2781                                              .Padding(PaddingMode::NONE)));
2782     // Message is slightly shorter than two blocks.
2783     string message(16 * 2 - 1, 'a');
2784 
2785     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2786     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2787     string ciphertext;
2788     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
2789     EXPECT_EQ(0U, ciphertext.size());
2790 }
2791 
2792 /*
2793  * EncryptionOperationsTest.AesEcbPkcs7Padding
2794  *
2795  * Verifies that AES PKCS7 padding works for any message length.
2796  */
TEST_P(EncryptionOperationsTest,AesEcbPkcs7Padding)2797 TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
2798     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2799                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2800                                              .AesEncryptionKey(128)
2801                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2802                                              .Padding(PaddingMode::PKCS7)));
2803 
2804     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2805 
2806     // Try various message lengths; all should work.
2807     for (size_t i = 0; i < 32; ++i) {
2808         string message(i, 'a');
2809         string ciphertext = EncryptMessage(message, params);
2810         EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2811         string plaintext = DecryptMessage(ciphertext, params);
2812         EXPECT_EQ(message, plaintext);
2813     }
2814 }
2815 
2816 /*
2817  * EncryptionOperationsTest.AesEcbWrongPadding
2818  *
2819  * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
2820  * specified.
2821  */
TEST_P(EncryptionOperationsTest,AesEcbWrongPadding)2822 TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
2823     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2824                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2825                                              .AesEncryptionKey(128)
2826                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2827                                              .Padding(PaddingMode::NONE)));
2828 
2829     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2830 
2831     // Try various message lengths; all should fail
2832     for (size_t i = 0; i < 32; ++i) {
2833         string message(i, 'a');
2834         EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
2835     }
2836 }
2837 
2838 /*
2839  * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
2840  *
2841  * Verifies that AES decryption fails in the correct way when the padding is corrupted.
2842  */
TEST_P(EncryptionOperationsTest,AesEcbPkcs7PaddingCorrupted)2843 TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
2844     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2845                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2846                                              .AesEncryptionKey(128)
2847                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2848                                              .Padding(PaddingMode::PKCS7)));
2849 
2850     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2851 
2852     string message = "a";
2853     string ciphertext = EncryptMessage(message, params);
2854     EXPECT_EQ(16U, ciphertext.size());
2855     EXPECT_NE(ciphertext, message);
2856     ++ciphertext[ciphertext.size() / 2];
2857 
2858     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2859     string plaintext;
2860     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
2861 }
2862 
CopyIv(const AuthorizationSet & set)2863 HidlBuf CopyIv(const AuthorizationSet& set) {
2864     auto iv = set.GetTagValue(TAG_NONCE);
2865     EXPECT_TRUE(iv.isOk());
2866     return iv.value();
2867 }
2868 
2869 /*
2870  * EncryptionOperationsTest.AesCtrRoundTripSuccess
2871  *
2872  * Verifies that AES CTR mode works.
2873  */
TEST_P(EncryptionOperationsTest,AesCtrRoundTripSuccess)2874 TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
2875     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2876                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2877                                              .AesEncryptionKey(128)
2878                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
2879                                              .Padding(PaddingMode::NONE)));
2880 
2881     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
2882 
2883     string message = "123";
2884     AuthorizationSet out_params;
2885     string ciphertext1 = EncryptMessage(message, params, &out_params);
2886     HidlBuf iv1 = CopyIv(out_params);
2887     EXPECT_EQ(16U, iv1.size());
2888 
2889     EXPECT_EQ(message.size(), ciphertext1.size());
2890 
2891     out_params.Clear();
2892     string ciphertext2 = EncryptMessage(message, params, &out_params);
2893     HidlBuf iv2 = CopyIv(out_params);
2894     EXPECT_EQ(16U, iv2.size());
2895 
2896     // IVs should be random, so ciphertexts should differ.
2897     EXPECT_NE(ciphertext1, ciphertext2);
2898 
2899     auto params_iv1 =
2900         AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
2901     auto params_iv2 =
2902         AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
2903 
2904     string plaintext = DecryptMessage(ciphertext1, params_iv1);
2905     EXPECT_EQ(message, plaintext);
2906     plaintext = DecryptMessage(ciphertext2, params_iv2);
2907     EXPECT_EQ(message, plaintext);
2908 
2909     // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
2910     plaintext = DecryptMessage(ciphertext1, params_iv2);
2911     EXPECT_NE(message, plaintext);
2912     plaintext = DecryptMessage(ciphertext2, params_iv1);
2913     EXPECT_NE(message, plaintext);
2914 }
2915 
2916 /*
2917  * EncryptionOperationsTest.AesIncremental
2918  *
2919  * Verifies that AES works, all modes, when provided data in various size increments.
2920  */
TEST_P(EncryptionOperationsTest,AesIncremental)2921 TEST_P(EncryptionOperationsTest, AesIncremental) {
2922     auto block_modes = {
2923         BlockMode::ECB, BlockMode::CBC, BlockMode::CTR, BlockMode::GCM,
2924     };
2925 
2926     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2927                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2928                                              .AesEncryptionKey(128)
2929                                              .BlockMode(block_modes)
2930                                              .Padding(PaddingMode::NONE)
2931                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2932 
2933     for (int increment = 1; increment <= 240; ++increment) {
2934         for (auto block_mode : block_modes) {
2935             string message(240, 'a');
2936             auto params = AuthorizationSetBuilder()
2937                               .BlockMode(block_mode)
2938                               .Padding(PaddingMode::NONE)
2939                               .Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
2940 
2941             AuthorizationSet output_params;
2942             EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
2943 
2944             string ciphertext;
2945             size_t input_consumed;
2946             string to_send;
2947             for (size_t i = 0; i < message.size(); i += increment) {
2948                 to_send.append(message.substr(i, increment));
2949                 EXPECT_EQ(ErrorCode::OK, Update(to_send, &ciphertext, &input_consumed));
2950                 EXPECT_EQ(to_send.length(), input_consumed);
2951                 to_send = to_send.substr(input_consumed);
2952                 EXPECT_EQ(0U, to_send.length());
2953 
2954                 switch (block_mode) {
2955                     case BlockMode::ECB:
2956                     case BlockMode::CBC:
2957                         // Implementations must take as many blocks as possible, leaving less than
2958                         // a block.
2959                         EXPECT_LE(to_send.length(), 16U);
2960                         break;
2961                     case BlockMode::GCM:
2962                     case BlockMode::CTR:
2963                         // Implementations must always take all the data.
2964                         EXPECT_EQ(0U, to_send.length());
2965                         break;
2966                 }
2967             }
2968             EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext)) << "Error sending " << to_send;
2969 
2970             switch (block_mode) {
2971                 case BlockMode::GCM:
2972                     EXPECT_EQ(message.size() + 16, ciphertext.size());
2973                     break;
2974                 case BlockMode::CTR:
2975                     EXPECT_EQ(message.size(), ciphertext.size());
2976                     break;
2977                 case BlockMode::CBC:
2978                 case BlockMode::ECB:
2979                     EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
2980                     break;
2981             }
2982 
2983             auto iv = output_params.GetTagValue(TAG_NONCE);
2984             switch (block_mode) {
2985                 case BlockMode::CBC:
2986                 case BlockMode::GCM:
2987                 case BlockMode::CTR:
2988                     ASSERT_TRUE(iv.isOk()) << "No IV for block mode " << block_mode;
2989                     EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv.value().size());
2990                     params.push_back(TAG_NONCE, iv.value());
2991                     break;
2992 
2993                 case BlockMode::ECB:
2994                     EXPECT_FALSE(iv.isOk()) << "ECB mode should not generate IV";
2995                     break;
2996             }
2997 
2998             EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
2999                 << "Decrypt begin() failed for block mode " << block_mode;
3000 
3001             string plaintext;
3002             for (size_t i = 0; i < ciphertext.size(); i += increment) {
3003                 to_send.append(ciphertext.substr(i, increment));
3004                 EXPECT_EQ(ErrorCode::OK, Update(to_send, &plaintext, &input_consumed));
3005                 to_send = to_send.substr(input_consumed);
3006             }
3007             ErrorCode error = Finish(to_send, &plaintext);
3008             ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
3009                                             << " and increment " << increment;
3010             if (error == ErrorCode::OK) {
3011                 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
3012                                               << block_mode << " and increment " << increment;
3013             }
3014         }
3015     }
3016 }
3017 
3018 struct AesCtrSp80038aTestVector {
3019     const char* key;
3020     const char* nonce;
3021     const char* plaintext;
3022     const char* ciphertext;
3023 };
3024 
3025 // These test vectors are taken from
3026 // http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
3027 static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
3028     // AES-128
3029     {
3030         "2b7e151628aed2a6abf7158809cf4f3c", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3031         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3032         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3033         "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
3034         "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
3035     },
3036     // AES-192
3037     {
3038         "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3039         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3040         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3041         "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
3042         "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
3043     },
3044     // AES-256
3045     {
3046         "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
3047         "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3048         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3049         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3050         "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
3051         "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
3052     },
3053 };
3054 
3055 /*
3056  * EncryptionOperationsTest.AesCtrSp80038aTestVector
3057  *
3058  * Verifies AES CTR implementation against SP800-38A test vectors.
3059  */
TEST_P(EncryptionOperationsTest,AesCtrSp80038aTestVector)3060 TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
3061     std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
3062     for (size_t i = 0; i < 3; i++) {
3063         const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
3064         const string key = hex2str(test.key);
3065         if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
3066             InvalidSizes.end())
3067             continue;
3068         const string nonce = hex2str(test.nonce);
3069         const string plaintext = hex2str(test.plaintext);
3070         const string ciphertext = hex2str(test.ciphertext);
3071         CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
3072     }
3073 }
3074 
3075 /*
3076  * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
3077  *
3078  * Verifies that keymaster rejects use of CTR mode with PKCS7 padding in the correct way.
3079  */
TEST_P(EncryptionOperationsTest,AesCtrIncompatiblePaddingMode)3080 TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
3081     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3082                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3083                                              .AesEncryptionKey(128)
3084                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3085                                              .Padding(PaddingMode::PKCS7)));
3086     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3087     EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3088 }
3089 
3090 /*
3091  * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3092  *
3093  * Verifies that keymaster fails correctly when the user supplies an incorrect-size nonce.
3094  */
TEST_P(EncryptionOperationsTest,AesCtrInvalidCallerNonce)3095 TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
3096     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3097                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3098                                              .AesEncryptionKey(128)
3099                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3100                                              .Authorization(TAG_CALLER_NONCE)
3101                                              .Padding(PaddingMode::NONE)));
3102 
3103     auto params = AuthorizationSetBuilder()
3104                       .BlockMode(BlockMode::CTR)
3105                       .Padding(PaddingMode::NONE)
3106                       .Authorization(TAG_NONCE, HidlBuf(string(1, 'a')));
3107     EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3108 
3109     params = AuthorizationSetBuilder()
3110                  .BlockMode(BlockMode::CTR)
3111                  .Padding(PaddingMode::NONE)
3112                  .Authorization(TAG_NONCE, HidlBuf(string(15, 'a')));
3113     EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3114 
3115     params = AuthorizationSetBuilder()
3116                  .BlockMode(BlockMode::CTR)
3117                  .Padding(PaddingMode::NONE)
3118                  .Authorization(TAG_NONCE, HidlBuf(string(17, 'a')));
3119     EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3120 }
3121 
3122 /*
3123  * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3124  *
3125  * Verifies that keymaster fails correctly when the user supplies an incorrect-size nonce.
3126  */
TEST_P(EncryptionOperationsTest,AesCbcRoundTripSuccess)3127 TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
3128     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3129                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3130                                              .AesEncryptionKey(128)
3131                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3132                                              .Padding(PaddingMode::NONE)));
3133     // Two-block message.
3134     string message = "12345678901234567890123456789012";
3135     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3136     AuthorizationSet out_params;
3137     string ciphertext1 = EncryptMessage(message, params, &out_params);
3138     HidlBuf iv1 = CopyIv(out_params);
3139     EXPECT_EQ(message.size(), ciphertext1.size());
3140 
3141     out_params.Clear();
3142 
3143     string ciphertext2 = EncryptMessage(message, params, &out_params);
3144     HidlBuf iv2 = CopyIv(out_params);
3145     EXPECT_EQ(message.size(), ciphertext2.size());
3146 
3147     // IVs should be random, so ciphertexts should differ.
3148     EXPECT_NE(ciphertext1, ciphertext2);
3149 
3150     params.push_back(TAG_NONCE, iv1);
3151     string plaintext = DecryptMessage(ciphertext1, params);
3152     EXPECT_EQ(message, plaintext);
3153 }
3154 
3155 /*
3156  * EncryptionOperationsTest.AesCallerNonce
3157  *
3158  * Verifies that AES caller-provided nonces work correctly.
3159  */
TEST_P(EncryptionOperationsTest,AesCallerNonce)3160 TEST_P(EncryptionOperationsTest, AesCallerNonce) {
3161     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3162                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3163                                              .AesEncryptionKey(128)
3164                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3165                                              .Authorization(TAG_CALLER_NONCE)
3166                                              .Padding(PaddingMode::NONE)));
3167 
3168     string message = "12345678901234567890123456789012";
3169 
3170     // Don't specify nonce, should get a random one.
3171     AuthorizationSetBuilder params =
3172         AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3173     AuthorizationSet out_params;
3174     string ciphertext = EncryptMessage(message, params, &out_params);
3175     EXPECT_EQ(message.size(), ciphertext.size());
3176     EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE).value().size());
3177 
3178     params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE).value());
3179     string plaintext = DecryptMessage(ciphertext, params);
3180     EXPECT_EQ(message, plaintext);
3181 
3182     // Now specify a nonce, should also work.
3183     params = AuthorizationSetBuilder()
3184                  .BlockMode(BlockMode::CBC)
3185                  .Padding(PaddingMode::NONE)
3186                  .Authorization(TAG_NONCE, HidlBuf("abcdefghijklmnop"));
3187     out_params.Clear();
3188     ciphertext = EncryptMessage(message, params, &out_params);
3189 
3190     // Decrypt with correct nonce.
3191     plaintext = DecryptMessage(ciphertext, params);
3192     EXPECT_EQ(message, plaintext);
3193 
3194     // Try with wrong nonce.
3195     params = AuthorizationSetBuilder()
3196                  .BlockMode(BlockMode::CBC)
3197                  .Padding(PaddingMode::NONE)
3198                  .Authorization(TAG_NONCE, HidlBuf("aaaaaaaaaaaaaaaa"));
3199     plaintext = DecryptMessage(ciphertext, params);
3200     EXPECT_NE(message, plaintext);
3201 }
3202 
3203 /*
3204  * EncryptionOperationsTest.AesCallerNonceProhibited
3205  *
3206  * Verifies that caller-provided nonces are not permitted when not specified in the key
3207  * authorizations.
3208  */
TEST_P(EncryptionOperationsTest,AesCallerNonceProhibited)3209 TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
3210     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3211                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3212                                              .AesEncryptionKey(128)
3213                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3214                                              .Padding(PaddingMode::NONE)));
3215 
3216     string message = "12345678901234567890123456789012";
3217 
3218     // Don't specify nonce, should get a random one.
3219     AuthorizationSetBuilder params =
3220         AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3221     AuthorizationSet out_params;
3222     string ciphertext = EncryptMessage(message, params, &out_params);
3223     EXPECT_EQ(message.size(), ciphertext.size());
3224     EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE).value().size());
3225 
3226     params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE).value());
3227     string plaintext = DecryptMessage(ciphertext, params);
3228     EXPECT_EQ(message, plaintext);
3229 
3230     // Now specify a nonce, should fail
3231     params = AuthorizationSetBuilder()
3232                  .BlockMode(BlockMode::CBC)
3233                  .Padding(PaddingMode::NONE)
3234                  .Authorization(TAG_NONCE, HidlBuf("abcdefghijklmnop"));
3235     out_params.Clear();
3236     EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
3237 }
3238 
3239 /*
3240  * EncryptionOperationsTest.AesGcmRoundTripSuccess
3241  *
3242  * Verifies that AES GCM mode works.
3243  */
TEST_P(EncryptionOperationsTest,AesGcmRoundTripSuccess)3244 TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
3245     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3246                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3247                                              .AesEncryptionKey(128)
3248                                              .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3249                                              .Padding(PaddingMode::NONE)
3250                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3251 
3252     string aad = "foobar";
3253     string message = "123456789012345678901234567890123456";
3254 
3255     auto begin_params = AuthorizationSetBuilder()
3256                             .BlockMode(BlockMode::GCM)
3257                             .Padding(PaddingMode::NONE)
3258                             .Authorization(TAG_MAC_LENGTH, 128);
3259 
3260     auto update_params =
3261         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3262 
3263     // Encrypt
3264     AuthorizationSet begin_out_params;
3265     ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
3266         << "Begin encrypt";
3267     string ciphertext;
3268     AuthorizationSet update_out_params;
3269     ASSERT_EQ(ErrorCode::OK,
3270               Finish(op_handle_, update_params, message, "", &update_out_params, &ciphertext));
3271 
3272     ASSERT_EQ(ciphertext.length(), message.length() + 16);
3273 
3274     // Grab nonce
3275     begin_params.push_back(begin_out_params);
3276 
3277     // Decrypt.
3278     ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
3279     string plaintext;
3280     size_t input_consumed;
3281     ASSERT_EQ(ErrorCode::OK, Update(op_handle_, update_params, ciphertext, &update_out_params,
3282                                     &plaintext, &input_consumed));
3283     EXPECT_EQ(ciphertext.size(), input_consumed);
3284     EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
3285     EXPECT_EQ(message.length(), plaintext.length());
3286     EXPECT_EQ(message, plaintext);
3287 }
3288 
3289 /*
3290  * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
3291  *
3292  * Verifies that AES GCM mode works, even when there's a long delay
3293  * between operations.
3294  */
TEST_P(EncryptionOperationsTest,AesGcmRoundTripWithDelaySuccess)3295 TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
3296     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3297                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3298                                              .AesEncryptionKey(128)
3299                                              .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3300                                              .Padding(PaddingMode::NONE)
3301                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3302 
3303     string aad = "foobar";
3304     string message = "123456789012345678901234567890123456";
3305 
3306     auto begin_params = AuthorizationSetBuilder()
3307                             .BlockMode(BlockMode::GCM)
3308                             .Padding(PaddingMode::NONE)
3309                             .Authorization(TAG_MAC_LENGTH, 128);
3310 
3311     auto update_params =
3312         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3313 
3314     // Encrypt
3315     AuthorizationSet begin_out_params;
3316     ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
3317         << "Begin encrypt";
3318     string ciphertext;
3319     AuthorizationSet update_out_params;
3320     sleep(5);
3321     ASSERT_EQ(ErrorCode::OK,
3322               Finish(op_handle_, update_params, message, "", &update_out_params, &ciphertext));
3323 
3324     ASSERT_EQ(ciphertext.length(), message.length() + 16);
3325 
3326     // Grab nonce
3327     begin_params.push_back(begin_out_params);
3328 
3329     // Decrypt.
3330     ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
3331     string plaintext;
3332     size_t input_consumed;
3333     sleep(5);
3334     ASSERT_EQ(ErrorCode::OK, Update(op_handle_, update_params, ciphertext, &update_out_params,
3335                                     &plaintext, &input_consumed));
3336     EXPECT_EQ(ciphertext.size(), input_consumed);
3337     sleep(5);
3338     EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
3339     EXPECT_EQ(message.length(), plaintext.length());
3340     EXPECT_EQ(message, plaintext);
3341 }
3342 
3343 /*
3344  * EncryptionOperationsTest.AesGcmDifferentNonces
3345  *
3346  * Verifies that encrypting the same data with different nonces produces different outputs.
3347  */
TEST_P(EncryptionOperationsTest,AesGcmDifferentNonces)3348 TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
3349     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3350                                                  .Authorization(TAG_NO_AUTH_REQUIRED)
3351                                                  .AesEncryptionKey(128)
3352                                                  .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3353                                                  .Padding(PaddingMode::NONE)
3354                                                  .Authorization(TAG_MIN_MAC_LENGTH, 128)
3355                                                  .Authorization(TAG_CALLER_NONCE)));
3356 
3357     string aad = "foobar";
3358     string message = "123456789012345678901234567890123456";
3359     string nonce1 = "000000000000";
3360     string nonce2 = "111111111111";
3361     string nonce3 = "222222222222";
3362 
3363     string ciphertext1 =
3364             EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, HidlBuf(nonce1));
3365     string ciphertext2 =
3366             EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, HidlBuf(nonce2));
3367     string ciphertext3 =
3368             EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, HidlBuf(nonce3));
3369 
3370     ASSERT_NE(ciphertext1, ciphertext2);
3371     ASSERT_NE(ciphertext1, ciphertext3);
3372     ASSERT_NE(ciphertext2, ciphertext3);
3373 }
3374 
3375 /*
3376  * EncryptionOperationsTest.AesGcmTooShortTag
3377  *
3378  * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
3379  */
TEST_P(EncryptionOperationsTest,AesGcmTooShortTag)3380 TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
3381     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3382                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3383                                              .AesEncryptionKey(128)
3384                                              .BlockMode(BlockMode::GCM)
3385                                              .Padding(PaddingMode::NONE)
3386                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3387     string message = "123456789012345678901234567890123456";
3388     auto params = AuthorizationSetBuilder()
3389                       .BlockMode(BlockMode::GCM)
3390                       .Padding(PaddingMode::NONE)
3391                       .Authorization(TAG_MAC_LENGTH, 96);
3392 
3393     EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
3394 }
3395 
3396 /*
3397  * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
3398  *
3399  * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
3400  */
TEST_P(EncryptionOperationsTest,AesGcmTooShortTagOnDecrypt)3401 TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
3402     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3403                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3404                                              .AesEncryptionKey(128)
3405                                              .BlockMode(BlockMode::GCM)
3406                                              .Padding(PaddingMode::NONE)
3407                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3408     string aad = "foobar";
3409     string message = "123456789012345678901234567890123456";
3410     auto params = AuthorizationSetBuilder()
3411                       .BlockMode(BlockMode::GCM)
3412                       .Padding(PaddingMode::NONE)
3413                       .Authorization(TAG_MAC_LENGTH, 128);
3414 
3415     auto finish_params =
3416         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3417 
3418     // Encrypt
3419     AuthorizationSet begin_out_params;
3420     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3421     EXPECT_EQ(1U, begin_out_params.size());
3422     ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE).isOk());
3423 
3424     AuthorizationSet finish_out_params;
3425     string ciphertext;
3426     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3427                                     &finish_out_params, &ciphertext));
3428 
3429     params = AuthorizationSetBuilder()
3430                  .Authorizations(begin_out_params)
3431                  .BlockMode(BlockMode::GCM)
3432                  .Padding(PaddingMode::NONE)
3433                  .Authorization(TAG_MAC_LENGTH, 96);
3434 
3435     // Decrypt.
3436     EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
3437 }
3438 
3439 /*
3440  * EncryptionOperationsTest.AesGcmCorruptKey
3441  *
3442  * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
3443  */
TEST_P(EncryptionOperationsTest,AesGcmCorruptKey)3444 TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
3445     const uint8_t nonce_bytes[] = {
3446         0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
3447     };
3448     string nonce = make_string(nonce_bytes);
3449     const uint8_t ciphertext_bytes[] = {
3450         0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc, 0xd2, 0xcb, 0x16,
3451         0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78, 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a,
3452         0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d, 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76,
3453         0x76, 0x5e, 0xfb, 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
3454         0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
3455     };
3456     string ciphertext = make_string(ciphertext_bytes);
3457 
3458     auto params = AuthorizationSetBuilder()
3459                       .BlockMode(BlockMode::GCM)
3460                       .Padding(PaddingMode::NONE)
3461                       .Authorization(TAG_MAC_LENGTH, 128)
3462                       .Authorization(TAG_NONCE, nonce.data(), nonce.size());
3463 
3464     auto import_params = AuthorizationSetBuilder()
3465                              .Authorization(TAG_NO_AUTH_REQUIRED)
3466                              .AesEncryptionKey(128)
3467                              .BlockMode(BlockMode::GCM)
3468                              .Padding(PaddingMode::NONE)
3469                              .Authorization(TAG_CALLER_NONCE)
3470                              .Authorization(TAG_MIN_MAC_LENGTH, 128);
3471 
3472     // Import correct key and decrypt
3473     const uint8_t key_bytes[] = {
3474         0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
3475         0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
3476     };
3477     string key = make_string(key_bytes);
3478     ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3479     string plaintext = DecryptMessage(ciphertext, params);
3480     CheckedDeleteKey();
3481 
3482     // Corrupt key and attempt to decrypt
3483     key[0] = 0;
3484     ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3485     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3486     EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
3487     CheckedDeleteKey();
3488 }
3489 
3490 /*
3491  * EncryptionOperationsTest.AesGcmAadNoData
3492  *
3493  * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
3494  * encrypt.
3495  */
TEST_P(EncryptionOperationsTest,AesGcmAadNoData)3496 TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
3497     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3498                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3499                                              .AesEncryptionKey(128)
3500                                              .BlockMode(BlockMode::GCM)
3501                                              .Padding(PaddingMode::NONE)
3502                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3503 
3504     string aad = "1234567890123456";
3505     auto params = AuthorizationSetBuilder()
3506                       .BlockMode(BlockMode::GCM)
3507                       .Padding(PaddingMode::NONE)
3508                       .Authorization(TAG_MAC_LENGTH, 128);
3509 
3510     auto finish_params =
3511         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3512 
3513     // Encrypt
3514     AuthorizationSet begin_out_params;
3515     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3516     string ciphertext;
3517     AuthorizationSet finish_out_params;
3518     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, "" /* input */, "" /* signature */,
3519                                     &finish_out_params, &ciphertext));
3520     EXPECT_TRUE(finish_out_params.empty());
3521 
3522     // Grab nonce
3523     params.push_back(begin_out_params);
3524 
3525     // Decrypt.
3526     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3527     string plaintext;
3528     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, ciphertext, "" /* signature */,
3529                                     &finish_out_params, &plaintext));
3530 
3531     EXPECT_TRUE(finish_out_params.empty());
3532 
3533     EXPECT_EQ("", plaintext);
3534 }
3535 
3536 /*
3537  * EncryptionOperationsTest.AesGcmMultiPartAad
3538  *
3539  * Verifies that AES GCM mode works when provided additional authenticated data in multiple chunks.
3540  */
TEST_P(EncryptionOperationsTest,AesGcmMultiPartAad)3541 TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
3542     const size_t tag_bits = 128;
3543     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3544                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3545                                              .AesEncryptionKey(128)
3546                                              .BlockMode(BlockMode::GCM)
3547                                              .Padding(PaddingMode::NONE)
3548                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3549 
3550     string message = "123456789012345678901234567890123456";
3551     auto begin_params = AuthorizationSetBuilder()
3552                             .BlockMode(BlockMode::GCM)
3553                             .Padding(PaddingMode::NONE)
3554                             .Authorization(TAG_MAC_LENGTH, tag_bits);
3555     AuthorizationSet begin_out_params;
3556 
3557     auto update_params =
3558         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3);
3559 
3560     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3561 
3562     // No data, AAD only.
3563     string ciphertext;
3564     size_t input_consumed;
3565     AuthorizationSet update_out_params;
3566     EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, "" /* input */, &update_out_params,
3567                                     &ciphertext, &input_consumed));
3568     EXPECT_EQ(0U, input_consumed);
3569     EXPECT_EQ(0U, ciphertext.size());
3570     EXPECT_TRUE(update_out_params.empty());
3571 
3572     // AAD and data.
3573     EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, message, &update_out_params,
3574                                     &ciphertext, &input_consumed));
3575     EXPECT_EQ(message.size(), input_consumed);
3576     EXPECT_TRUE(update_out_params.empty());
3577 
3578     EXPECT_EQ(ErrorCode::OK, Finish("" /* input */, &ciphertext));
3579     // Expect 128-bit (16-byte) tag appended to ciphertext.
3580     EXPECT_EQ(message.size() + (tag_bits >> 3), ciphertext.size());
3581 
3582     // Grab nonce.
3583     begin_params.push_back(begin_out_params);
3584 
3585     // Decrypt
3586     update_params =
3587         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foofoo", (size_t)6);
3588 
3589     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
3590     string plaintext;
3591     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, update_params, ciphertext, "" /* signature */,
3592                                     &update_out_params, &plaintext));
3593     EXPECT_TRUE(update_out_params.empty());
3594     EXPECT_EQ(message, plaintext);
3595 }
3596 
3597 /*
3598  * EncryptionOperationsTest.AesGcmAadOutOfOrder
3599  *
3600  * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
3601  */
TEST_P(EncryptionOperationsTest,AesGcmAadOutOfOrder)3602 TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
3603     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3604                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3605                                              .AesEncryptionKey(128)
3606                                              .BlockMode(BlockMode::GCM)
3607                                              .Padding(PaddingMode::NONE)
3608                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3609 
3610     string message = "123456789012345678901234567890123456";
3611     auto begin_params = AuthorizationSetBuilder()
3612                             .BlockMode(BlockMode::GCM)
3613                             .Padding(PaddingMode::NONE)
3614                             .Authorization(TAG_MAC_LENGTH, 128);
3615     AuthorizationSet begin_out_params;
3616 
3617     auto update_params =
3618         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3);
3619 
3620     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3621 
3622     // No data, AAD only.
3623     string ciphertext;
3624     size_t input_consumed;
3625     AuthorizationSet update_out_params;
3626     EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, "" /* input */, &update_out_params,
3627                                     &ciphertext, &input_consumed));
3628     EXPECT_EQ(0U, input_consumed);
3629     EXPECT_EQ(0U, ciphertext.size());
3630     EXPECT_TRUE(update_out_params.empty());
3631 
3632     // AAD and data.
3633     EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, message, &update_out_params,
3634                                     &ciphertext, &input_consumed));
3635     EXPECT_EQ(message.size(), input_consumed);
3636     EXPECT_TRUE(update_out_params.empty());
3637 
3638     // More AAD
3639     EXPECT_EQ(ErrorCode::INVALID_TAG, Update(op_handle_, update_params, "", &update_out_params,
3640                                              &ciphertext, &input_consumed));
3641 
3642     op_handle_ = kOpHandleSentinel;
3643 }
3644 
3645 /*
3646  * EncryptionOperationsTest.AesGcmBadAad
3647  *
3648  * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
3649  */
TEST_P(EncryptionOperationsTest,AesGcmBadAad)3650 TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
3651     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3652                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3653                                              .AesEncryptionKey(128)
3654                                              .BlockMode(BlockMode::GCM)
3655                                              .Padding(PaddingMode::NONE)
3656                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3657 
3658     string message = "12345678901234567890123456789012";
3659     auto begin_params = AuthorizationSetBuilder()
3660                             .BlockMode(BlockMode::GCM)
3661                             .Padding(PaddingMode::NONE)
3662                             .Authorization(TAG_MAC_LENGTH, 128);
3663 
3664     auto finish_params =
3665         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6);
3666 
3667     // Encrypt
3668     AuthorizationSet begin_out_params;
3669     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3670     string ciphertext;
3671     AuthorizationSet finish_out_params;
3672     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3673                                     &finish_out_params, &ciphertext));
3674 
3675     // Grab nonce
3676     begin_params.push_back(begin_out_params);
3677 
3678     finish_params = AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA,
3679                                                             "barfoo" /* Wrong AAD */, (size_t)6);
3680 
3681     // Decrypt.
3682     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
3683     string plaintext;
3684     EXPECT_EQ(ErrorCode::VERIFICATION_FAILED,
3685               Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params,
3686                      &plaintext));
3687 }
3688 
3689 /*
3690  * EncryptionOperationsTest.AesGcmWrongNonce
3691  *
3692  * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
3693  */
TEST_P(EncryptionOperationsTest,AesGcmWrongNonce)3694 TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
3695     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3696                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3697                                              .AesEncryptionKey(128)
3698                                              .BlockMode(BlockMode::GCM)
3699                                              .Padding(PaddingMode::NONE)
3700                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3701 
3702     string message = "12345678901234567890123456789012";
3703     auto begin_params = AuthorizationSetBuilder()
3704                             .BlockMode(BlockMode::GCM)
3705                             .Padding(PaddingMode::NONE)
3706                             .Authorization(TAG_MAC_LENGTH, 128);
3707 
3708     auto finish_params =
3709         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6);
3710 
3711     // Encrypt
3712     AuthorizationSet begin_out_params;
3713     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3714     string ciphertext;
3715     AuthorizationSet finish_out_params;
3716     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3717                                     &finish_out_params, &ciphertext));
3718 
3719     // Wrong nonce
3720     begin_params.push_back(TAG_NONCE, HidlBuf("123456789012"));
3721 
3722     // Decrypt.
3723     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
3724     string plaintext;
3725     EXPECT_EQ(ErrorCode::VERIFICATION_FAILED,
3726               Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params,
3727                      &plaintext));
3728 
3729     // With wrong nonce, should have gotten garbage plaintext (or none).
3730     EXPECT_NE(message, plaintext);
3731 }
3732 
3733 /*
3734  * EncryptionOperationsTest.AesGcmCorruptTag
3735  *
3736  * Verifies that AES GCM decryption fails correctly when the tag is wrong.
3737  */
TEST_P(EncryptionOperationsTest,AesGcmCorruptTag)3738 TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
3739     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3740                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3741                                              .AesEncryptionKey(128)
3742                                              .BlockMode(BlockMode::GCM)
3743                                              .Padding(PaddingMode::NONE)
3744                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3745 
3746     string aad = "1234567890123456";
3747     string message = "123456789012345678901234567890123456";
3748 
3749     auto params = AuthorizationSetBuilder()
3750                       .BlockMode(BlockMode::GCM)
3751                       .Padding(PaddingMode::NONE)
3752                       .Authorization(TAG_MAC_LENGTH, 128);
3753 
3754     auto finish_params =
3755         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3756 
3757     // Encrypt
3758     AuthorizationSet begin_out_params;
3759     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3760     string ciphertext;
3761     AuthorizationSet finish_out_params;
3762     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3763                                     &finish_out_params, &ciphertext));
3764     EXPECT_TRUE(finish_out_params.empty());
3765 
3766     // Corrupt tag
3767     ++(*ciphertext.rbegin());
3768 
3769     // Grab nonce
3770     params.push_back(begin_out_params);
3771 
3772     // Decrypt.
3773     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3774     string plaintext;
3775     EXPECT_EQ(ErrorCode::VERIFICATION_FAILED,
3776               Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params,
3777                      &plaintext));
3778     EXPECT_TRUE(finish_out_params.empty());
3779 }
3780 
3781 /*
3782  * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
3783  *
3784  * Verifies that 3DES is basically functional.
3785  */
TEST_P(EncryptionOperationsTest,TripleDesEcbRoundTripSuccess)3786 TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
3787     auto auths = AuthorizationSetBuilder()
3788                      .TripleDesEncryptionKey(168)
3789                      .BlockMode(BlockMode::ECB)
3790                      .Authorization(TAG_NO_AUTH_REQUIRED)
3791                      .Padding(PaddingMode::NONE);
3792 
3793     ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
3794     // Two-block message.
3795     string message = "1234567890123456";
3796     auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3797     string ciphertext1 = EncryptMessage(message, inParams);
3798     EXPECT_EQ(message.size(), ciphertext1.size());
3799 
3800     string ciphertext2 = EncryptMessage(string(message), inParams);
3801     EXPECT_EQ(message.size(), ciphertext2.size());
3802 
3803     // ECB is deterministic.
3804     EXPECT_EQ(ciphertext1, ciphertext2);
3805 
3806     string plaintext = DecryptMessage(ciphertext1, inParams);
3807     EXPECT_EQ(message, plaintext);
3808 }
3809 
3810 /*
3811  * EncryptionOperationsTest.TripleDesEcbNotAuthorized
3812  *
3813  * Verifies that CBC keys reject ECB usage.
3814  */
TEST_P(EncryptionOperationsTest,TripleDesEcbNotAuthorized)3815 TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
3816     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3817                                              .TripleDesEncryptionKey(168)
3818                                              .BlockMode(BlockMode::CBC)
3819                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3820                                              .Padding(PaddingMode::NONE)));
3821 
3822     auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3823     EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
3824 }
3825 
3826 /*
3827  * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
3828  *
3829  * Tests ECB mode with PKCS#7 padding, various message sizes.
3830  */
TEST_P(EncryptionOperationsTest,TripleDesEcbPkcs7Padding)3831 TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
3832     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3833                                              .TripleDesEncryptionKey(168)
3834                                              .BlockMode(BlockMode::ECB)
3835                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3836                                              .Padding(PaddingMode::PKCS7)));
3837 
3838     for (size_t i = 0; i < 32; ++i) {
3839         string message(i, 'a');
3840         auto inParams =
3841             AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3842         string ciphertext = EncryptMessage(message, inParams);
3843         EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
3844         string plaintext = DecryptMessage(ciphertext, inParams);
3845         EXPECT_EQ(message, plaintext);
3846     }
3847 }
3848 
3849 /*
3850  * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
3851  *
3852  * Verifies that keys configured for no padding reject PKCS7 padding
3853  */
TEST_P(EncryptionOperationsTest,TripleDesEcbNoPaddingKeyWithPkcs7Padding)3854 TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
3855     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3856                                              .TripleDesEncryptionKey(168)
3857                                              .BlockMode(BlockMode::ECB)
3858                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3859                                              .Padding(PaddingMode::NONE)));
3860     for (size_t i = 0; i < 32; ++i) {
3861         auto inParams =
3862             AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3863         EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
3864     }
3865 }
3866 
3867 /*
3868  * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
3869  *
3870  * Verifies that corrupted padding is detected.
3871  */
TEST_P(EncryptionOperationsTest,TripleDesEcbPkcs7PaddingCorrupted)3872 TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
3873     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3874                                              .TripleDesEncryptionKey(168)
3875                                              .BlockMode(BlockMode::ECB)
3876                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3877                                              .Padding(PaddingMode::PKCS7)));
3878 
3879     string message = "a";
3880     string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
3881     EXPECT_EQ(8U, ciphertext.size());
3882     EXPECT_NE(ciphertext, message);
3883     ++ciphertext[ciphertext.size() / 2];
3884 
3885     AuthorizationSetBuilder begin_params;
3886     begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
3887     begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
3888     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
3889     string plaintext;
3890     size_t input_consumed;
3891     EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext, &input_consumed));
3892     EXPECT_EQ(ciphertext.size(), input_consumed);
3893     EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
3894 }
3895 
3896 struct TripleDesTestVector {
3897     const char* name;
3898     const KeyPurpose purpose;
3899     const BlockMode block_mode;
3900     const PaddingMode padding_mode;
3901     const char* key;
3902     const char* iv;
3903     const char* input;
3904     const char* output;
3905 };
3906 
3907 // These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all of
3908 // the NIST vectors are multiples of the block size.
3909 static const TripleDesTestVector kTripleDesTestVectors[] = {
3910     {
3911         "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
3912         "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd",  // key
3913         "",                                                  // IV
3914         "329d86bdf1bc5af4",                                  // input
3915         "d946c2756d78633f",                                  // output
3916     },
3917     {
3918         "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
3919         "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49",  // key
3920         "",                                                  // IV
3921         "6b1540781b01ce1997adae102dbf3c5b",                  // input
3922         "4d0dc182d6e481ac4a3dc6ab6976ccae",                  // output
3923     },
3924     {
3925         "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
3926         "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9",  // key
3927         "",                                                  // IV
3928         "6daad94ce08acfe7",                                  // input
3929         "660e7d32dcc90e79",                                  // output
3930     },
3931     {
3932         "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
3933         "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce",  // key
3934         "",                                                  // IV
3935         "e9653a0a1f05d31b9acd12d73aa9879d",                  // input
3936         "9b2ae9d998efe62f1b592e7e1df8ff38",                  // output
3937     },
3938     {
3939         "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
3940         "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37",  // key
3941         "43f791134c5647ba",                                  // IV
3942         "dcc153cef81d6f24",                                  // input
3943         "92538bd8af18d3ba",                                  // output
3944     },
3945     {
3946         "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
3947         "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358",  // key
3948         "c2e999cb6249023c",                                  // IV
3949         "c689aee38a301bb316da75db36f110b5",                  // input
3950         "e9afaba5ec75ea1bbe65506655bb4ecb",                  // output
3951     },
3952     {
3953         "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::PKCS7,
3954         "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358",  // key
3955         "c2e999cb6249023c",                                  // IV
3956         "c689aee38a301bb316da75db36f110b500",                // input
3957         "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156",  // output
3958     },
3959     {
3960         "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
3961         PaddingMode::PKCS7,
3962         "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358",  // key
3963         "c2e999cb6249023c",                                  // IV
3964         "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156",  // input
3965         "c689aee38a301bb316da75db36f110b500",                // output
3966     },
3967     {
3968         "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
3969         "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1",  // key
3970         "41746c7e442d3681",                                  // IV
3971         "c53a7b0ec40600fe",                                  // input
3972         "d4f00eb455de1034",                                  // output
3973     },
3974     {
3975         "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
3976         "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549",  // key
3977         "3982bc02c3727d45",                                  // IV
3978         "6006f10adef52991fcc777a1238bbb65",                  // input
3979         "edae09288e9e3bc05746d872b48e3b29",                  // output
3980     },
3981 };
3982 
3983 /*
3984  * EncryptionOperationsTest.TripleDesTestVector
3985  *
3986  * Verifies that NIST (plus a few extra) test vectors produce the correct results.
3987  */
TEST_P(EncryptionOperationsTest,TripleDesTestVector)3988 TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
3989     constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
3990     for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
3991         SCOPED_TRACE(test->name);
3992         CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
3993                                  hex2str(test->key), hex2str(test->iv), hex2str(test->input),
3994                                  hex2str(test->output));
3995     }
3996 }
3997 
3998 /*
3999  * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
4000  *
4001  * Validates CBC mode functionality.
4002  */
TEST_P(EncryptionOperationsTest,TripleDesCbcRoundTripSuccess)4003 TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
4004     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4005                                              .TripleDesEncryptionKey(168)
4006                                              .BlockMode(BlockMode::CBC)
4007                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4008                                              .Padding(PaddingMode::NONE)));
4009     // Two-block message.
4010     string message = "1234567890123456";
4011     HidlBuf iv1;
4012     string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
4013     EXPECT_EQ(message.size(), ciphertext1.size());
4014 
4015     HidlBuf iv2;
4016     string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
4017     EXPECT_EQ(message.size(), ciphertext2.size());
4018 
4019     // IVs should be random, so ciphertexts should differ.
4020     EXPECT_NE(iv1, iv2);
4021     EXPECT_NE(ciphertext1, ciphertext2);
4022 
4023     string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
4024     EXPECT_EQ(message, plaintext);
4025 }
4026 
4027 /*
4028  * EncryptionOperationsTest.TripleDesCallerIv
4029  *
4030  * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
4031  */
TEST_P(EncryptionOperationsTest,TripleDesCallerIv)4032 TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
4033     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4034                                              .TripleDesEncryptionKey(168)
4035                                              .BlockMode(BlockMode::CBC)
4036                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4037                                              .Authorization(TAG_CALLER_NONCE)
4038                                              .Padding(PaddingMode::NONE)));
4039     string message = "1234567890123456";
4040     HidlBuf iv;
4041     // Don't specify IV, should get a random one.
4042     string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
4043     EXPECT_EQ(message.size(), ciphertext1.size());
4044     EXPECT_EQ(8U, iv.size());
4045 
4046     string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
4047     EXPECT_EQ(message, plaintext);
4048 
4049     // Now specify an IV, should also work.
4050     iv = HidlBuf("abcdefgh");
4051     string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
4052 
4053     // Decrypt with correct IV.
4054     plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
4055     EXPECT_EQ(message, plaintext);
4056 
4057     // Now try with wrong IV.
4058     plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, HidlBuf("aaaaaaaa"));
4059     EXPECT_NE(message, plaintext);
4060 }
4061 
4062 /*
4063  * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
4064  *
4065  * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVS.
4066  */
TEST_P(EncryptionOperationsTest,TripleDesCallerNonceProhibited)4067 TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
4068     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4069                                              .TripleDesEncryptionKey(168)
4070                                              .BlockMode(BlockMode::CBC)
4071                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4072                                              .Padding(PaddingMode::NONE)));
4073 
4074     string message = "12345678901234567890123456789012";
4075     HidlBuf iv;
4076     // Don't specify nonce, should get a random one.
4077     string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
4078     EXPECT_EQ(message.size(), ciphertext1.size());
4079     EXPECT_EQ(8U, iv.size());
4080 
4081     string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
4082     EXPECT_EQ(message, plaintext);
4083 
4084     // Now specify a nonce, should fail.
4085     auto input_params = AuthorizationSetBuilder()
4086                             .Authorization(TAG_NONCE, HidlBuf("abcdefgh"))
4087                             .BlockMode(BlockMode::CBC)
4088                             .Padding(PaddingMode::NONE);
4089     AuthorizationSet output_params;
4090     EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
4091               Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4092 }
4093 
4094 /*
4095  * EncryptionOperationsTest.TripleDesCbcNotAuthorized
4096  *
4097  * Verifies that 3DES ECB-only keys do not allow CBC usage.
4098  */
TEST_P(EncryptionOperationsTest,TripleDesCbcNotAuthorized)4099 TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
4100     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4101                                              .TripleDesEncryptionKey(168)
4102                                              .BlockMode(BlockMode::ECB)
4103                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4104                                              .Padding(PaddingMode::NONE)));
4105     // Two-block message.
4106     string message = "1234567890123456";
4107     auto begin_params =
4108         AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4109     EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4110 }
4111 
4112 /*
4113  * EncryptionOperationsTest.TripleDesCbcNoPaddingWrongInputSize
4114  *
4115  * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
4116  */
TEST_P(EncryptionOperationsTest,TripleDesCbcNoPaddingWrongInputSize)4117 TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingWrongInputSize) {
4118     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4119                                              .TripleDesEncryptionKey(168)
4120                                              .BlockMode(BlockMode::CBC)
4121                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4122                                              .Padding(PaddingMode::NONE)));
4123     // Message is slightly shorter than two blocks.
4124     string message = "123456789012345";
4125 
4126     auto begin_params =
4127         AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4128     AuthorizationSet output_params;
4129     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
4130     string ciphertext;
4131     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
4132 }
4133 
4134 /*
4135  * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
4136  *
4137  * Verifies that PKCS7 padding works correctly in CBC mode.
4138  */
TEST_P(EncryptionOperationsTest,TripleDesCbcPkcs7Padding)4139 TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
4140     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4141                                              .TripleDesEncryptionKey(168)
4142                                              .BlockMode(BlockMode::CBC)
4143                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4144                                              .Padding(PaddingMode::PKCS7)));
4145 
4146     // Try various message lengths; all should work.
4147     for (size_t i = 0; i < 32; ++i) {
4148         string message(i, 'a');
4149         HidlBuf iv;
4150         string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4151         EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
4152         string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
4153         EXPECT_EQ(message, plaintext);
4154     }
4155 }
4156 
4157 /*
4158  * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
4159  *
4160  * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
4161  */
TEST_P(EncryptionOperationsTest,TripleDesCbcNoPaddingKeyWithPkcs7Padding)4162 TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
4163     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4164                                              .TripleDesEncryptionKey(168)
4165                                              .BlockMode(BlockMode::CBC)
4166                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4167                                              .Padding(PaddingMode::NONE)));
4168 
4169     // Try various message lengths; all should fail.
4170     for (size_t i = 0; i < 32; ++i) {
4171         auto begin_params =
4172             AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
4173         EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4174     }
4175 }
4176 
4177 /*
4178  * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
4179  *
4180  * Verifies that corrupted PKCS7 padding is rejected during decryption.
4181  */
TEST_P(EncryptionOperationsTest,TripleDesCbcPkcs7PaddingCorrupted)4182 TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
4183     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4184                                              .TripleDesEncryptionKey(168)
4185                                              .BlockMode(BlockMode::CBC)
4186                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4187                                              .Padding(PaddingMode::PKCS7)));
4188 
4189     string message = "a";
4190     HidlBuf iv;
4191     string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4192     EXPECT_EQ(8U, ciphertext.size());
4193     EXPECT_NE(ciphertext, message);
4194     ++ciphertext[ciphertext.size() / 2];
4195 
4196     auto begin_params = AuthorizationSetBuilder()
4197                             .BlockMode(BlockMode::CBC)
4198                             .Padding(PaddingMode::PKCS7)
4199                             .Authorization(TAG_NONCE, iv);
4200     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
4201     string plaintext;
4202     size_t input_consumed;
4203     EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext, &input_consumed));
4204     EXPECT_EQ(ciphertext.size(), input_consumed);
4205     EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
4206 }
4207 
4208 /*
4209  * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
4210  *
4211  * Verifies that 3DES CBC works with many different input sizes.
4212  */
TEST_P(EncryptionOperationsTest,TripleDesCbcIncrementalNoPadding)4213 TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
4214     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4215                                              .TripleDesEncryptionKey(168)
4216                                              .BlockMode(BlockMode::CBC)
4217                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4218                                              .Padding(PaddingMode::NONE)));
4219 
4220     int increment = 7;
4221     string message(240, 'a');
4222     AuthorizationSet input_params =
4223         AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4224     AuthorizationSet output_params;
4225     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4226 
4227     string ciphertext;
4228     size_t input_consumed;
4229     for (size_t i = 0; i < message.size(); i += increment)
4230         EXPECT_EQ(ErrorCode::OK,
4231                   Update(message.substr(i, increment), &ciphertext, &input_consumed));
4232     EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
4233     EXPECT_EQ(message.size(), ciphertext.size());
4234 
4235     // Move TAG_NONCE into input_params
4236     input_params = output_params;
4237     input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
4238     input_params.push_back(TAG_PADDING, PaddingMode::NONE);
4239     output_params.Clear();
4240 
4241     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
4242     string plaintext;
4243     for (size_t i = 0; i < ciphertext.size(); i += increment)
4244         EXPECT_EQ(ErrorCode::OK,
4245                   Update(ciphertext.substr(i, increment), &plaintext, &input_consumed));
4246     EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
4247     EXPECT_EQ(ciphertext.size(), plaintext.size());
4248     EXPECT_EQ(message, plaintext);
4249 }
4250 
4251 INSTANTIATE_KEYMASTER_HIDL_TEST(EncryptionOperationsTest);
4252 
4253 typedef KeymasterHidlTest MaxOperationsTest;
4254 
4255 /*
4256  * MaxOperationsTest.TestLimitAes
4257  *
4258  * Verifies that the max uses per boot tag works correctly with AES keys.
4259  */
TEST_P(MaxOperationsTest,TestLimitAes)4260 TEST_P(MaxOperationsTest, TestLimitAes) {
4261     if (SecLevel() == SecurityLevel::STRONGBOX) return;
4262 
4263     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4264                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4265                                              .AesEncryptionKey(128)
4266                                              .EcbMode()
4267                                              .Padding(PaddingMode::NONE)
4268                                              .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
4269 
4270     string message = "1234567890123456";
4271 
4272     auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
4273 
4274     EncryptMessage(message, params);
4275     EncryptMessage(message, params);
4276     EncryptMessage(message, params);
4277 
4278     // Fourth time should fail.
4279     EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
4280 }
4281 
4282 /*
4283  * MaxOperationsTest.TestLimitAes
4284  *
4285  * Verifies that the max uses per boot tag works correctly with RSA keys.
4286  */
TEST_P(MaxOperationsTest,TestLimitRsa)4287 TEST_P(MaxOperationsTest, TestLimitRsa) {
4288     if (SecLevel() == SecurityLevel::STRONGBOX) return;
4289 
4290     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4291                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4292                                              .RsaSigningKey(1024, 65537)
4293                                              .NoDigestOrPadding()
4294                                              .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
4295 
4296     string message = "1234567890123456";
4297 
4298     auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4299 
4300     SignMessage(message, params);
4301     SignMessage(message, params);
4302     SignMessage(message, params);
4303 
4304     // Fourth time should fail.
4305     EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
4306 }
4307 
4308 INSTANTIATE_KEYMASTER_HIDL_TEST(MaxOperationsTest);
4309 
4310 typedef KeymasterHidlTest AddEntropyTest;
4311 
4312 /*
4313  * AddEntropyTest.AddEntropy
4314  *
4315  * Verifies that the addRngEntropy method doesn't blow up.  There's no way to test that entropy is
4316  * actually added.
4317  */
TEST_P(AddEntropyTest,AddEntropy)4318 TEST_P(AddEntropyTest, AddEntropy) {
4319     EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf("foo")));
4320 }
4321 
4322 /*
4323  * AddEntropyTest.AddEmptyEntropy
4324  *
4325  * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
4326  */
TEST_P(AddEntropyTest,AddEmptyEntropy)4327 TEST_P(AddEntropyTest, AddEmptyEntropy) {
4328     EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf()));
4329 }
4330 
4331 /*
4332  * AddEntropyTest.AddLargeEntropy
4333  *
4334  * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
4335  */
TEST_P(AddEntropyTest,AddLargeEntropy)4336 TEST_P(AddEntropyTest, AddLargeEntropy) {
4337     EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf(string(2 * 1024, 'a'))));
4338 }
4339 
4340 INSTANTIATE_KEYMASTER_HIDL_TEST(AddEntropyTest);
4341 
4342 typedef KeymasterHidlTest AttestationTest;
4343 
4344 /*
4345  * AttestationTest.RsaAttestation
4346  *
4347  * Verifies that attesting to RSA keys works and generates the expected output.
4348  */
TEST_P(AttestationTest,RsaAttestation)4349 TEST_P(AttestationTest, RsaAttestation) {
4350     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4351                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4352                                              .RsaSigningKey(2048, 65537)
4353                                              .Digest(Digest::SHA_2_256)
4354                                              .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
4355                                              .Authorization(TAG_INCLUDE_UNIQUE_ID)));
4356 
4357     hidl_vec<hidl_vec<uint8_t>> cert_chain;
4358     ASSERT_EQ(ErrorCode::OK,
4359               AttestKey(AuthorizationSetBuilder()
4360                             .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
4361                             .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
4362                         &cert_chain));
4363     EXPECT_GE(cert_chain.size(), 2U);
4364 
4365     string message = "12345678901234567890123456789012";
4366     string signature = SignMessage(message, AuthorizationSetBuilder()
4367                                                 .Digest(Digest::SHA_2_256)
4368                                                 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
4369 
4370     EXPECT_TRUE(verify_chain(cert_chain, message, signature));
4371     EXPECT_TRUE(verify_attestation_record("challenge", "foo",                     //
4372                                           key_characteristics_.softwareEnforced,  //
4373                                           key_characteristics_.hardwareEnforced,  //
4374                                           SecLevel(), cert_chain[0]));
4375 }
4376 
4377 /*
4378  * AttestationTest.RsaAttestationRequiresAppId
4379  *
4380  * Verifies that attesting to RSA requires app ID.
4381  */
TEST_P(AttestationTest,RsaAttestationRequiresAppId)4382 TEST_P(AttestationTest, RsaAttestationRequiresAppId) {
4383     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4384                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4385                                              .RsaSigningKey(2048, 65537)
4386                                              .Digest(Digest::NONE)
4387                                              .Padding(PaddingMode::NONE)
4388                                              .Authorization(TAG_INCLUDE_UNIQUE_ID)));
4389 
4390     hidl_vec<hidl_vec<uint8_t>> cert_chain;
4391     EXPECT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
4392               AttestKey(AuthorizationSetBuilder().Authorization(TAG_ATTESTATION_CHALLENGE,
4393                                                                 HidlBuf("challenge")),
4394                         &cert_chain));
4395 }
4396 
4397 /*
4398  * AttestationTest.EcAttestation
4399  *
4400  * Verifies that attesting to EC keys works and generates the expected output.
4401  */
TEST_P(AttestationTest,EcAttestation)4402 TEST_P(AttestationTest, EcAttestation) {
4403     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4404                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4405                                              .EcdsaSigningKey(EcCurve::P_256)
4406                                              .Digest(Digest::SHA_2_256)
4407                                              .Authorization(TAG_INCLUDE_UNIQUE_ID)));
4408 
4409     hidl_vec<hidl_vec<uint8_t>> cert_chain;
4410     ASSERT_EQ(ErrorCode::OK,
4411               AttestKey(AuthorizationSetBuilder()
4412                             .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
4413                             .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
4414                         &cert_chain));
4415     EXPECT_GE(cert_chain.size(), 2U);
4416 
4417     string message(1024, 'a');
4418     string signature = SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4419 
4420     EXPECT_TRUE(verify_chain(cert_chain, message, signature));
4421     EXPECT_TRUE(verify_attestation_record("challenge", "foo",                     //
4422                                           key_characteristics_.softwareEnforced,  //
4423                                           key_characteristics_.hardwareEnforced,  //
4424                                           SecLevel(), cert_chain[0]));
4425 }
4426 
4427 /*
4428  * AttestationTest.EcAttestationID
4429  *
4430  * Verifies that attesting to EC keys with correct attestation ID fields works and generates the
4431  * expected output.
4432  */
TEST_P(AttestationTest,EcAttestationID)4433 TEST_P(AttestationTest, EcAttestationID) {
4434     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4435                                                  .Authorization(TAG_NO_AUTH_REQUIRED)
4436                                                  .EcdsaSigningKey(EcCurve::P_256)
4437                                                  .Digest(Digest::SHA_2_256)
4438                                                  .Authorization(TAG_INCLUDE_UNIQUE_ID)));
4439 
4440     // Collection of valid attestation ID tags.
4441     auto attestation_id_tags = AuthorizationSetBuilder();
4442     add_tag_from_prop(&attestation_id_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
4443     add_tag_from_prop(&attestation_id_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
4444     add_tag_from_prop(&attestation_id_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
4445     add_tag_from_prop(&attestation_id_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
4446     add_tag_from_prop(&attestation_id_tags, TAG_ATTESTATION_ID_MANUFACTURER,
4447                       "ro.product.manufacturer");
4448     add_tag_from_prop(&attestation_id_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
4449 
4450     for (const KeyParameter& tag : attestation_id_tags) {
4451         AuthorizationSetBuilder builder =
4452                 AuthorizationSetBuilder()
4453                         .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
4454                         .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo"));
4455         // Include one of the (valid) attestation ID tags.
4456         builder.push_back(tag);
4457         hidl_vec<hidl_vec<uint8_t>> cert_chain;
4458         auto result = AttestKey(builder, &cert_chain);
4459         if (result == ErrorCode::CANNOT_ATTEST_IDS) {
4460             continue;
4461         }
4462 
4463         ASSERT_EQ(ErrorCode::OK, result);
4464         EXPECT_GE(cert_chain.size(), 2U);
4465 
4466         std::vector<KeyParameter> expected_hw_enforced = key_characteristics_.hardwareEnforced;
4467         expected_hw_enforced.push_back(tag);
4468 
4469         EXPECT_TRUE(verify_attestation_record(
4470                 "challenge", "foo", key_characteristics_.softwareEnforced,
4471                 hidl_vec<KeyParameter>(expected_hw_enforced), SecLevel(), cert_chain[0]));
4472     }
4473 }
4474 
4475 /*
4476  * AttestationTest.EcAttestationMismatchID
4477  *
4478  * Verifies that attesting to EC keys with incorrect attestation ID fields fails.
4479  */
TEST_P(AttestationTest,EcAttestationMismatchID)4480 TEST_P(AttestationTest, EcAttestationMismatchID) {
4481     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4482                                                  .Authorization(TAG_NO_AUTH_REQUIRED)
4483                                                  .EcdsaSigningKey(EcCurve::P_256)
4484                                                  .Digest(Digest::SHA_2_256)
4485                                                  .Authorization(TAG_INCLUDE_UNIQUE_ID)));
4486 
4487     // Collection of invalid attestation ID tags.
4488     std::string invalid = "completely-invalid";
4489     auto invalid_tags =
4490             AuthorizationSetBuilder()
4491                     .Authorization(V4_0::TAG_ATTESTATION_ID_BRAND, invalid.data(), invalid.size())
4492                     .Authorization(V4_0::TAG_ATTESTATION_ID_DEVICE, invalid.data(), invalid.size())
4493                     .Authorization(V4_0::TAG_ATTESTATION_ID_PRODUCT, invalid.data(), invalid.size())
4494                     .Authorization(V4_0::TAG_ATTESTATION_ID_SERIAL, invalid.data(), invalid.size())
4495                     .Authorization(V4_0::TAG_ATTESTATION_ID_IMEI, invalid.data(), invalid.size())
4496                     .Authorization(V4_0::TAG_ATTESTATION_ID_MEID, invalid.data(), invalid.size())
4497                     .Authorization(V4_0::TAG_ATTESTATION_ID_MANUFACTURER, invalid.data(),
4498                                    invalid.size())
4499                     .Authorization(V4_0::TAG_ATTESTATION_ID_MODEL, invalid.data(), invalid.size());
4500 
4501     for (const KeyParameter& invalid_tag : invalid_tags) {
4502         AuthorizationSetBuilder builder =
4503                 AuthorizationSetBuilder()
4504                         .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
4505                         .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo"));
4506         // Include one of the invalid attestation ID tags.
4507         builder.push_back(invalid_tag);
4508         hidl_vec<hidl_vec<uint8_t>> cert_chain;
4509         auto result = AttestKey(builder, &cert_chain);
4510 
4511         EXPECT_TRUE(result == ErrorCode::CANNOT_ATTEST_IDS || result == ErrorCode::INVALID_TAG)
4512                 << "result: " << static_cast<int32_t>(result);
4513     }
4514 }
4515 
4516 /*
4517  * AttestationTest.EcAttestationRequiresAttestationAppId
4518  *
4519  * Verifies that attesting to EC keys requires app ID
4520  */
TEST_P(AttestationTest,EcAttestationRequiresAttestationAppId)4521 TEST_P(AttestationTest, EcAttestationRequiresAttestationAppId) {
4522     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4523                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4524                                              .EcdsaSigningKey(EcCurve::P_256)
4525                                              .Digest(Digest::SHA_2_256)
4526                                              .Authorization(TAG_INCLUDE_UNIQUE_ID)));
4527 
4528     hidl_vec<hidl_vec<uint8_t>> cert_chain;
4529     EXPECT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
4530               AttestKey(AuthorizationSetBuilder().Authorization(TAG_ATTESTATION_CHALLENGE,
4531                                                                 HidlBuf("challenge")),
4532                         &cert_chain));
4533 }
4534 
4535 /*
4536  * AttestationTest.AttestationApplicationIDLengthProperlyEncoded
4537  *
4538  * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
4539  * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
4540  * byte. Proper DER encoding specifies that for lengths greather than 127, one byte should be used
4541  * to specify how many following bytes will be used to encode the length.
4542  */
TEST_P(AttestationTest,AttestationApplicationIDLengthProperlyEncoded)4543 TEST_P(AttestationTest, AttestationApplicationIDLengthProperlyEncoded) {
4544     std::vector<uint32_t> app_id_lengths{143, 258};
4545     for (uint32_t length : app_id_lengths) {
4546         ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4547                                                      .Authorization(TAG_NO_AUTH_REQUIRED)
4548                                                      .EcdsaSigningKey(EcCurve::P_256)
4549                                                      .Digest(Digest::SHA_2_256)));
4550 
4551         hidl_vec<hidl_vec<uint8_t>> cert_chain;
4552         const string app_id(length, 'a');
4553         ASSERT_EQ(ErrorCode::OK,
4554                   AttestKey(AuthorizationSetBuilder()
4555                                     .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
4556                                     .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf(app_id)),
4557                             &cert_chain));
4558         EXPECT_GE(cert_chain.size(), 2U);
4559 
4560         EXPECT_TRUE(verify_attestation_record("challenge", app_id,                    //
4561                                               key_characteristics_.softwareEnforced,  //
4562                                               key_characteristics_.hardwareEnforced,  //
4563                                               SecLevel(), cert_chain[0]));
4564         CheckedDeleteKey();
4565     }
4566 }
4567 /*
4568  * AttestationTest.AesAttestation
4569  *
4570  * Verifies that attesting to AES keys fails in the expected way.
4571  */
TEST_P(AttestationTest,AesAttestation)4572 TEST_P(AttestationTest, AesAttestation) {
4573     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4574                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4575                                              .AesEncryptionKey(128)
4576                                              .EcbMode()
4577                                              .Padding(PaddingMode::PKCS7)));
4578 
4579     hidl_vec<hidl_vec<uint8_t>> cert_chain;
4580     EXPECT_EQ(ErrorCode::INCOMPATIBLE_ALGORITHM,
4581               AttestKey(AuthorizationSetBuilder()
4582                             .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
4583                             .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
4584                         &cert_chain));
4585 }
4586 
4587 /*
4588  * AttestationTest.HmacAttestation
4589  *
4590  * Verifies that attesting to HMAC keys fails in the expected way.
4591  */
TEST_P(AttestationTest,HmacAttestation)4592 TEST_P(AttestationTest, HmacAttestation) {
4593     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4594                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4595                                              .HmacKey(128)
4596                                              .EcbMode()
4597                                              .Digest(Digest::SHA_2_256)
4598                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4599 
4600     hidl_vec<hidl_vec<uint8_t>> cert_chain;
4601     EXPECT_EQ(ErrorCode::INCOMPATIBLE_ALGORITHM,
4602               AttestKey(AuthorizationSetBuilder()
4603                             .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
4604                             .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
4605                         &cert_chain));
4606 }
4607 
4608 INSTANTIATE_KEYMASTER_HIDL_TEST(AttestationTest);
4609 
4610 typedef KeymasterHidlTest KeyDeletionTest;
4611 
4612 /**
4613  * KeyDeletionTest.DeleteKey
4614  *
4615  * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
4616  * valid key blob.
4617  */
TEST_P(KeyDeletionTest,DeleteKey)4618 TEST_P(KeyDeletionTest, DeleteKey) {
4619     auto error = GenerateKey(AuthorizationSetBuilder()
4620                                      .RsaSigningKey(2048, 65537)
4621                                      .Digest(Digest::NONE)
4622                                      .Padding(PaddingMode::NONE)
4623                                      .Authorization(TAG_NO_AUTH_REQUIRED)
4624                                      .Authorization(TAG_ROLLBACK_RESISTANCE));
4625     ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4626 
4627     // Delete must work if rollback protection is implemented
4628     if (error == ErrorCode::OK) {
4629         AuthorizationSet hardwareEnforced(key_characteristics_.hardwareEnforced);
4630         ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4631 
4632         ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
4633 
4634         string message = "12345678901234567890123456789012";
4635         AuthorizationSet begin_out_params;
4636         EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
4637                   Begin(KeyPurpose::SIGN, key_blob_,
4638                         AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
4639                         &begin_out_params, &op_handle_));
4640         AbortIfNeeded();
4641         key_blob_ = HidlBuf();
4642     }
4643 }
4644 
4645 /**
4646  * KeyDeletionTest.DeleteInvalidKey
4647  *
4648  * This test checks that the HAL excepts invalid key blobs..
4649  */
TEST_P(KeyDeletionTest,DeleteInvalidKey)4650 TEST_P(KeyDeletionTest, DeleteInvalidKey) {
4651     // Generate key just to check if rollback protection is implemented
4652     auto error = GenerateKey(AuthorizationSetBuilder()
4653                                      .RsaSigningKey(2048, 65537)
4654                                      .Digest(Digest::NONE)
4655                                      .Padding(PaddingMode::NONE)
4656                                      .Authorization(TAG_NO_AUTH_REQUIRED)
4657                                      .Authorization(TAG_ROLLBACK_RESISTANCE));
4658     ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4659 
4660     // Delete must work if rollback protection is implemented
4661     if (error == ErrorCode::OK) {
4662         AuthorizationSet hardwareEnforced(key_characteristics_.hardwareEnforced);
4663         ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4664 
4665         // Delete the key we don't care about the result at this point.
4666         DeleteKey();
4667 
4668         // Now create an invalid key blob and delete it.
4669         key_blob_ = HidlBuf("just some garbage data which is not a valid key blob");
4670 
4671         ASSERT_EQ(ErrorCode::OK, DeleteKey());
4672     }
4673 }
4674 
4675 /**
4676  * KeyDeletionTest.DeleteAllKeys
4677  *
4678  * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
4679  *
4680  * BEWARE: This test has serious side effects. All user keys will be lost! This includes
4681  * FBE/FDE encryption keys, which means that the device will not even boot until after the
4682  * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
4683  * been provisioned. Use this test only on dedicated testing devices that have no valuable
4684  * credentials stored in Keystore/Keymaster.
4685  */
TEST_P(KeyDeletionTest,DeleteAllKeys)4686 TEST_P(KeyDeletionTest, DeleteAllKeys) {
4687     if (!arm_deleteAllKeys) return;
4688     auto error = GenerateKey(AuthorizationSetBuilder()
4689                                      .RsaSigningKey(2048, 65537)
4690                                      .Digest(Digest::NONE)
4691                                      .Padding(PaddingMode::NONE)
4692                                      .Authorization(TAG_NO_AUTH_REQUIRED)
4693                                      .Authorization(TAG_ROLLBACK_RESISTANCE));
4694     ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4695 
4696     // Delete must work if rollback protection is implemented
4697     if (error == ErrorCode::OK) {
4698         AuthorizationSet hardwareEnforced(key_characteristics_.hardwareEnforced);
4699         ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4700 
4701         ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
4702 
4703         string message = "12345678901234567890123456789012";
4704         AuthorizationSet begin_out_params;
4705 
4706         EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
4707                   Begin(KeyPurpose::SIGN, key_blob_,
4708                         AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
4709                         &begin_out_params, &op_handle_));
4710         AbortIfNeeded();
4711         key_blob_ = HidlBuf();
4712     }
4713 }
4714 
4715 INSTANTIATE_KEYMASTER_HIDL_TEST(KeyDeletionTest);
4716 
4717 using UpgradeKeyTest = KeymasterHidlTest;
4718 
4719 /*
4720  * UpgradeKeyTest.UpgradeKey
4721  *
4722  * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
4723  */
TEST_P(UpgradeKeyTest,UpgradeKey)4724 TEST_P(UpgradeKeyTest, UpgradeKey) {
4725     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4726                                              .AesEncryptionKey(128)
4727                                              .Padding(PaddingMode::NONE)
4728                                              .Authorization(TAG_NO_AUTH_REQUIRED)));
4729 
4730     auto result = UpgradeKey(key_blob_);
4731 
4732     // Key doesn't need upgrading.  Should get okay, but no new key blob.
4733     EXPECT_EQ(result, std::make_pair(ErrorCode::OK, HidlBuf()));
4734 }
4735 
4736 INSTANTIATE_KEYMASTER_HIDL_TEST(UpgradeKeyTest);
4737 
4738 using ClearOperationsTest = KeymasterHidlTest;
4739 
4740 /*
4741  * ClearSlotsTest.TooManyOperations
4742  *
4743  * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
4744  * operations are started without being finished or aborted. Also verifies
4745  * that aborting the operations clears the operations.
4746  *
4747  */
TEST_P(ClearOperationsTest,DISABLED_TooManyOperations)4748 TEST_P(ClearOperationsTest, DISABLED_TooManyOperations) {
4749     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4750                                              .Authorization(TAG_NO_AUTH_REQUIRED)
4751                                              .RsaEncryptionKey(2048, 65537)
4752                                              .Padding(PaddingMode::NONE)));
4753 
4754     auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4755     int max_operations = SecLevel() == SecurityLevel::STRONGBOX ? 4 : 16;
4756     OperationHandle op_handles[max_operations];
4757     AuthorizationSet out_params;
4758     for(int i=0; i<max_operations; i++) {
4759         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, &(op_handles[i])));
4760     }
4761     EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
4762          Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, &op_handle_));
4763     // Try again just in case there's a weird overflow bug
4764     EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
4765          Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, &op_handle_));
4766     for(int i=0; i<max_operations; i++) {
4767         EXPECT_EQ(ErrorCode::OK, Abort(op_handles[i]));
4768     }
4769     EXPECT_EQ(ErrorCode::OK,
4770          Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, &op_handle_));
4771     AbortIfNeeded();
4772 }
4773 
4774 INSTANTIATE_KEYMASTER_HIDL_TEST(ClearOperationsTest);
4775 
4776 typedef KeymasterHidlTest TransportLimitTest;
4777 
4778 /*
4779  * TransportLimitTest.FinishInput
4780  *
4781  * Verifies that passing input data to finish succeeds as expected.
4782  */
TEST_P(TransportLimitTest,LargeFinishInput)4783 TEST_P(TransportLimitTest, LargeFinishInput) {
4784     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4785                                                  .Authorization(TAG_NO_AUTH_REQUIRED)
4786                                                  .AesEncryptionKey(128)
4787                                                  .BlockMode(BlockMode::ECB)
4788                                                  .Padding(PaddingMode::NONE)));
4789 
4790     for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
4791         auto cipher_params =
4792                 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4793 
4794         AuthorizationSet out_params;
4795         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
4796 
4797         string plain_message = std::string(1 << msg_size, 'x');
4798         string encrypted_message;
4799         auto rc = Finish(plain_message, &encrypted_message);
4800 
4801         EXPECT_EQ(ErrorCode::OK, rc);
4802         EXPECT_EQ(plain_message.size(), encrypted_message.size())
4803                 << "Encrypt finish returned OK, but did not consume all of the given input";
4804         cipher_params.push_back(out_params);
4805 
4806         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
4807 
4808         string decrypted_message;
4809         rc = Finish(encrypted_message, &decrypted_message);
4810         EXPECT_EQ(ErrorCode::OK, rc);
4811         EXPECT_EQ(plain_message.size(), decrypted_message.size())
4812                 << "Decrypt finish returned OK, did not consume all of the given input";
4813     }
4814 }
4815 
4816 INSTANTIATE_KEYMASTER_HIDL_TEST(TransportLimitTest);
4817 
4818 }  // namespace test
4819 }  // namespace V4_0
4820 }  // namespace keymaster
4821 }  // namespace hardware
4822 }  // namespace android
4823 
main(int argc,char ** argv)4824 int main(int argc, char** argv) {
4825     ::testing::InitGoogleTest(&argc, argv);
4826     for (int i = 1; i < argc; ++i) {
4827         if (argv[i][0] == '-') {
4828             if (std::string(argv[i]) == "--arm_deleteAllKeys") {
4829                 arm_deleteAllKeys = true;
4830             }
4831             if (std::string(argv[i]) == "--dump_attestations") {
4832                 dump_Attestations = true;
4833             }
4834         }
4835     }
4836     int status = RUN_ALL_TESTS();
4837     ALOGI("Test result = %d", status);
4838     return status;
4839 }
4840