1 /*
2  * Copyright (C) 2016 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 <iostream>
21 
22 #include <openssl/evp.h>
23 #include <openssl/x509.h>
24 
25 #include <android/hardware/keymaster/3.0/IKeymasterDevice.h>
26 #include <android/hardware/keymaster/3.0/types.h>
27 
28 #include <cutils/properties.h>
29 
30 #include <keymaster/keymaster_configuration.h>
31 
32 #include "authorization_set.h"
33 #include "key_param_output.h"
34 
35 #include <VtsHalHidlTargetTestBase.h>
36 
37 #include "attestation_record.h"
38 #include "openssl_utils.h"
39 
40 using ::android::sp;
41 
42 using ::std::string;
43 
44 // This service_name will be passed to getService when retrieving the keymaster service to test.  To
45 // change it from "default" specify the selected service name on the command line.  The first
46 // non-gtest argument will be used as the service name.
47 string service_name = "default";
48 
49 static bool arm_deleteAllKeys = false;
50 
51 namespace android {
52 namespace hardware {
53 
operator ==(const hidl_vec<T> & a,const hidl_vec<T> & b)54 template <typename T> bool operator==(const hidl_vec<T>& a, const hidl_vec<T>& b) {
55     if (a.size() != b.size()) {
56         return false;
57     }
58     for (size_t i = 0; i < a.size(); ++i) {
59         if (a[i] != b[i]) {
60             return false;
61         }
62     }
63     return true;
64 }
65 
66 namespace keymaster {
67 namespace V3_0 {
68 
operator ==(const KeyParameter & a,const KeyParameter & b)69 bool operator==(const KeyParameter& a, const KeyParameter& b) {
70     if (a.tag != b.tag) {
71         return false;
72     }
73 
74     switch (a.tag) {
75 
76     /* Boolean tags */
77     case Tag::INVALID:
78     case Tag::CALLER_NONCE:
79     case Tag::INCLUDE_UNIQUE_ID:
80     case Tag::ECIES_SINGLE_HASH_MODE:
81     case Tag::BOOTLOADER_ONLY:
82     case Tag::NO_AUTH_REQUIRED:
83     case Tag::ALLOW_WHILE_ON_BODY:
84     case Tag::EXPORTABLE:
85     case Tag::ALL_APPLICATIONS:
86     case Tag::ROLLBACK_RESISTANT:
87     case Tag::RESET_SINCE_ID_ROTATION:
88         return true;
89 
90     /* Integer tags */
91     case Tag::KEY_SIZE:
92     case Tag::MIN_MAC_LENGTH:
93     case Tag::MIN_SECONDS_BETWEEN_OPS:
94     case Tag::MAX_USES_PER_BOOT:
95     case Tag::ALL_USERS:
96     case Tag::USER_ID:
97     case Tag::OS_VERSION:
98     case Tag::OS_PATCHLEVEL:
99     case Tag::MAC_LENGTH:
100     case Tag::AUTH_TIMEOUT:
101         return a.f.integer == b.f.integer;
102 
103     /* Long integer tags */
104     case Tag::RSA_PUBLIC_EXPONENT:
105     case Tag::USER_SECURE_ID:
106         return a.f.longInteger == b.f.longInteger;
107 
108     /* Date-time tags */
109     case Tag::ACTIVE_DATETIME:
110     case Tag::ORIGINATION_EXPIRE_DATETIME:
111     case Tag::USAGE_EXPIRE_DATETIME:
112     case Tag::CREATION_DATETIME:
113         return a.f.dateTime == b.f.dateTime;
114 
115     /* Bytes tags */
116     case Tag::APPLICATION_ID:
117     case Tag::APPLICATION_DATA:
118     case Tag::ROOT_OF_TRUST:
119     case Tag::UNIQUE_ID:
120     case Tag::ATTESTATION_CHALLENGE:
121     case Tag::ATTESTATION_APPLICATION_ID:
122     case Tag::ATTESTATION_ID_BRAND:
123     case Tag::ATTESTATION_ID_DEVICE:
124     case Tag::ATTESTATION_ID_PRODUCT:
125     case Tag::ATTESTATION_ID_SERIAL:
126     case Tag::ATTESTATION_ID_IMEI:
127     case Tag::ATTESTATION_ID_MEID:
128     case Tag::ATTESTATION_ID_MANUFACTURER:
129     case Tag::ATTESTATION_ID_MODEL:
130     case Tag::ASSOCIATED_DATA:
131     case Tag::NONCE:
132     case Tag::AUTH_TOKEN:
133         return a.blob == b.blob;
134 
135     /* Enum tags */
136     case Tag::PURPOSE:
137         return a.f.purpose == b.f.purpose;
138     case Tag::ALGORITHM:
139         return a.f.algorithm == b.f.algorithm;
140     case Tag::BLOCK_MODE:
141         return a.f.blockMode == b.f.blockMode;
142     case Tag::DIGEST:
143         return a.f.digest == b.f.digest;
144     case Tag::PADDING:
145         return a.f.paddingMode == b.f.paddingMode;
146     case Tag::EC_CURVE:
147         return a.f.ecCurve == b.f.ecCurve;
148     case Tag::BLOB_USAGE_REQUIREMENTS:
149         return a.f.keyBlobUsageRequirements == b.f.keyBlobUsageRequirements;
150     case Tag::USER_AUTH_TYPE:
151         return a.f.integer == b.f.integer;
152     case Tag::ORIGIN:
153         return a.f.origin == b.f.origin;
154 
155     /* Unsupported tags */
156     case Tag::KDF:
157         return false;
158     }
159 }
160 
operator ==(const AuthorizationSet & a,const AuthorizationSet & b)161 bool operator==(const AuthorizationSet& a, const AuthorizationSet& b) {
162     return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin());
163 }
164 
operator ==(const KeyCharacteristics & a,const KeyCharacteristics & b)165 bool operator==(const KeyCharacteristics& a, const KeyCharacteristics& b) {
166     // This isn't very efficient. Oh, well.
167     AuthorizationSet a_sw(a.softwareEnforced);
168     AuthorizationSet b_sw(b.softwareEnforced);
169     AuthorizationSet a_tee(b.teeEnforced);
170     AuthorizationSet b_tee(b.teeEnforced);
171 
172     a_sw.Sort();
173     b_sw.Sort();
174     a_tee.Sort();
175     b_tee.Sort();
176 
177     return a_sw == b_sw && a_tee == b_sw;
178 }
179 
operator <<(::std::ostream & os,const AuthorizationSet & set)180 ::std::ostream& operator<<(::std::ostream& os, const AuthorizationSet& set) {
181     if (set.size() == 0)
182         os << "(Empty)" << ::std::endl;
183     else {
184         os << "\n";
185         for (size_t i = 0; i < set.size(); ++i)
186             os << set[i] << ::std::endl;
187     }
188     return os;
189 }
190 
191 namespace test {
192 namespace {
193 
194 template <TagType tag_type, Tag tag, typename ValueT>
contains(hidl_vec<KeyParameter> & set,TypedTag<tag_type,tag> ttag,ValueT expected_value)195 bool contains(hidl_vec<KeyParameter>& set, TypedTag<tag_type, tag> ttag, ValueT expected_value) {
196     size_t count = std::count_if(set.begin(), set.end(), [&](const KeyParameter& param) {
197         return param.tag == tag && accessTagValue(ttag, param) == expected_value;
198     });
199     return count == 1;
200 }
201 
202 template <TagType tag_type, Tag tag>
contains(hidl_vec<KeyParameter> & set,TypedTag<tag_type,tag>)203 bool contains(hidl_vec<KeyParameter>& set, TypedTag<tag_type, tag>) {
204     size_t count = std::count_if(set.begin(), set.end(),
205                                  [&](const KeyParameter& param) { return param.tag == tag; });
206     return count > 0;
207 }
208 
209 constexpr char hex_value[256] = {0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
210                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
211                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
212                                  0, 1,  2,  3,  4,  5,  6,  7, 8, 9, 0, 0, 0, 0, 0, 0,  // '0'..'9'
213                                  0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 'A'..'F'
214                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
215                                  0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 'a'..'f'
216                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
217                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
218                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
219                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
220                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
221                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
222                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
223                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0,  //
224                                  0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0};
225 
hex2str(string a)226 string hex2str(string a) {
227     string b;
228     size_t num = a.size() / 2;
229     b.resize(num);
230     for (size_t i = 0; i < num; i++) {
231         b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
232     }
233     return b;
234 }
235 
236 string rsa_key = hex2str(
237     "30820275020100300d06092a864886f70d01010105000482025f3082025b"
238     "02010002818100c6095409047d8634812d5a218176e45c41d60a75b13901"
239     "f234226cffe776521c5a77b9e389417b71c0b6a44d13afe4e4a2805d46c9"
240     "da2935adb1ff0c1f24ea06e62b20d776430a4d435157233c6f916783c30e"
241     "310fcbd89b85c2d56771169785ac12bca244abda72bfb19fc44d27c81e1d"
242     "92de284f4061edfd99280745ea6d2502030100010281801be0f04d9cae37"
243     "18691f035338308e91564b55899ffb5084d2460e6630257e05b3ceab0297"
244     "2dfabcd6ce5f6ee2589eb67911ed0fac16e43a444b8c861e544a05933657"
245     "72f8baf6b22fc9e3c5f1024b063ac080a7b2234cf8aee8f6c47bbf4fd3ac"
246     "e7240290bef16c0b3f7f3cdd64ce3ab5912cf6e32f39ab188358afcccd80"
247     "81024100e4b49ef50f765d3b24dde01aceaaf130f2c76670a91a61ae08af"
248     "497b4a82be6dee8fcdd5e3f7ba1cfb1f0c926b88f88c92bfab137fba2285"
249     "227b83c342ff7c55024100ddabb5839c4c7f6bf3d4183231f005b31aa58a"
250     "ffdda5c79e4cce217f6bc930dbe563d480706c24e9ebfcab28a6cdefd324"
251     "b77e1bf7251b709092c24ff501fd91024023d4340eda3445d8cd26c14411"
252     "da6fdca63c1ccd4b80a98ad52b78cc8ad8beb2842c1d280405bc2f6c1bea"
253     "214a1d742ab996b35b63a82a5e470fa88dbf823cdd02401b7b57449ad30d"
254     "1518249a5f56bb98294d4b6ac12ffc86940497a5a5837a6cf946262b4945"
255     "26d328c11e1126380fde04c24f916dec250892db09a6d77cdba351024077"
256     "62cd8f4d050da56bd591adb515d24d7ccd32cca0d05f866d583514bd7324"
257     "d5f33645e8ed8b4a1cb3cc4a1d67987399f2a09f5b3fb68c88d5e5d90ac3"
258     "3492d6");
259 
260 string ec_256_key = hex2str(
261     "308187020100301306072a8648ce3d020106082a8648ce3d030107046d30"
262     "6b0201010420737c2ecd7b8d1940bf2930aa9b4ed3ff941eed09366bc032"
263     "99986481f3a4d859a14403420004bf85d7720d07c25461683bc648b4778a"
264     "9a14dd8a024e3bdd8c7ddd9ab2b528bbc7aa1b51f14ebbbb0bd0ce21bcc4"
265     "1c6eb00083cf3376d11fd44949e0b2183bfe");
266 
267 string ec_521_key = hex2str(
268     "3081EE020100301006072A8648CE3D020106052B810400230481D63081D3"
269     "02010104420011458C586DB5DAA92AFAB03F4FE46AA9D9C3CE9A9B7A006A"
270     "8384BEC4C78E8E9D18D7D08B5BCFA0E53C75B064AD51C449BAE0258D54B9"
271     "4B1E885DED08ED4FB25CE9A1818903818600040149EC11C6DF0FA122C6A9"
272     "AFD9754A4FA9513A627CA329E349535A5629875A8ADFBE27DCB932C05198"
273     "6377108D054C28C6F39B6F2C9AF81802F9F326B842FF2E5F3C00AB7635CF"
274     "B36157FC0882D574A10D839C1A0C049DC5E0D775E2EE50671A208431BB45"
275     "E78E70BEFE930DB34818EE4D5C26259F5C6B8E28A652950F9F88D7B4B2C9"
276     "D9");
277 
278 struct RSA_Delete {
operator ()android::hardware::keymaster::V3_0::test::__anon93d6503a0111::RSA_Delete279     void operator()(RSA* p) { RSA_free(p); }
280 };
281 
parse_cert_blob(const hidl_vec<uint8_t> & blob)282 X509* parse_cert_blob(const hidl_vec<uint8_t>& blob) {
283     const uint8_t* p = blob.data();
284     return d2i_X509(nullptr, &p, blob.size());
285 }
286 
verify_chain(const hidl_vec<hidl_vec<uint8_t>> & chain)287 bool verify_chain(const hidl_vec<hidl_vec<uint8_t>>& chain) {
288     for (size_t i = 0; i < chain.size() - 1; ++i) {
289         auto& key_cert_blob = chain[i];
290         auto& signing_cert_blob = chain[i + 1];
291 
292         X509_Ptr key_cert(parse_cert_blob(key_cert_blob));
293         X509_Ptr signing_cert(parse_cert_blob(signing_cert_blob));
294         EXPECT_TRUE(!!key_cert.get() && !!signing_cert.get());
295         if (!key_cert.get() || !signing_cert.get()) return false;
296 
297         EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
298         EXPECT_TRUE(!!signing_pubkey.get());
299         if (!signing_pubkey.get()) return false;
300 
301         EXPECT_EQ(1, X509_verify(key_cert.get(), signing_pubkey.get()))
302             << "Verification of certificate " << i << " failed";
303     }
304 
305     return true;
306 }
307 
308 // Extract attestation record from cert. Returned object is still part of cert; don't free it
309 // separately.
get_attestation_record(X509 * certificate)310 ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
311     ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
312     EXPECT_TRUE(!!oid.get());
313     if (!oid.get()) return nullptr;
314 
315     int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
316     EXPECT_NE(-1, location);
317     if (location == -1) return nullptr;
318 
319     X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
320     EXPECT_TRUE(!!attest_rec_ext);
321     if (!attest_rec_ext) return nullptr;
322 
323     ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
324     EXPECT_TRUE(!!attest_rec);
325     return attest_rec;
326 }
327 
tag_in_list(const KeyParameter & entry)328 bool tag_in_list(const KeyParameter& entry) {
329     // Attestations don't contain everything in key authorization lists, so we need to filter
330     // the key lists to produce the lists that we expect to match the attestations.
331     auto tag_list = {
332         Tag::USER_ID, Tag::INCLUDE_UNIQUE_ID, Tag::BLOB_USAGE_REQUIREMENTS,
333         Tag::EC_CURVE /* Tag::EC_CURVE will be included by KM2 implementations */,
334     };
335     return std::find(tag_list.begin(), tag_list.end(), entry.tag) != tag_list.end();
336 }
337 
filter_tags(const AuthorizationSet & set)338 AuthorizationSet filter_tags(const AuthorizationSet& set) {
339     AuthorizationSet filtered;
340     std::remove_copy_if(set.begin(), set.end(), std::back_inserter(filtered), tag_in_list);
341     return filtered;
342 }
343 
make_string(const uint8_t * data,size_t length)344 std::string make_string(const uint8_t* data, size_t length) {
345     return std::string(reinterpret_cast<const char*>(data), length);
346 }
347 
make_string(const uint8_t (& a)[N])348 template <size_t N> std::string make_string(const uint8_t (&a)[N]) {
349     return make_string(a, N);
350 }
351 
352 class HidlBuf : public hidl_vec<uint8_t> {
353     typedef hidl_vec<uint8_t> super;
354 
355   public:
HidlBuf()356     HidlBuf() {}
HidlBuf(const super & other)357     HidlBuf(const super& other) : super(other) {}
HidlBuf(super && other)358     HidlBuf(super&& other) : super(std::move(other)) {}
HidlBuf(const std::string & other)359     explicit HidlBuf(const std::string& other) : HidlBuf() { *this = other; }
360 
operator =(const super & other)361     HidlBuf& operator=(const super& other) {
362         super::operator=(other);
363         return *this;
364     }
365 
operator =(super && other)366     HidlBuf& operator=(super&& other) {
367         super::operator=(std::move(other));
368         return *this;
369     }
370 
operator =(const string & other)371     HidlBuf& operator=(const string& other) {
372         resize(other.size());
373         for (size_t i = 0; i < other.size(); ++i) {
374             (*this)[i] = static_cast<uint8_t>(other[i]);
375         }
376         return *this;
377     }
378 
to_string() const379     string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
380 };
381 
382 constexpr uint64_t kOpHandleSentinel = 0xFFFFFFFFFFFFFFFF;
383 
384 }  // namespace
385 
386 class KeymasterHidlTest : public ::testing::VtsHalHidlTargetTestBase {
387   public:
TearDown()388     void TearDown() override {
389         if (key_blob_.size()) {
390             CheckedDeleteKey();
391         }
392         AbortIfNeeded();
393     }
394 
395     // SetUpTestCase runs only once per test case, not once per test.
SetUpTestCase()396     static void SetUpTestCase() {
397         keymaster_ = IKeymasterDevice::getService(service_name);
398         ASSERT_NE(keymaster_, nullptr);
399 
400         ASSERT_TRUE(
401             keymaster_
402                 ->getHardwareFeatures([&](bool isSecure, bool supportsEc, bool supportsSymmetric,
403                                           bool supportsAttestation, bool supportsAllDigests,
404                                           const hidl_string& name, const hidl_string& author) {
405                     is_secure_ = isSecure;
406                     supports_ec_ = supportsEc;
407                     supports_symmetric_ = supportsSymmetric;
408                     supports_attestation_ = supportsAttestation;
409                     supports_all_digests_ = supportsAllDigests;
410                     name_ = name;
411                     author_ = author;
412                 })
413                 .isOk());
414 
415         os_version_ = ::keymaster::GetOsVersion();
416         os_patch_level_ = ::keymaster::GetOsPatchlevel();
417     }
418 
TearDownTestCase()419     static void TearDownTestCase() { keymaster_.clear(); }
420 
keymaster()421     static IKeymasterDevice& keymaster() { return *keymaster_; }
os_version()422     static uint32_t os_version() { return os_version_; }
os_patch_level()423     static uint32_t os_patch_level() { return os_patch_level_; }
424 
UserAuths()425     AuthorizationSet UserAuths() { return AuthorizationSetBuilder().Authorization(TAG_USER_ID, 7); }
426 
GenerateKey(const AuthorizationSet & key_desc,HidlBuf * key_blob,KeyCharacteristics * key_characteristics)427     ErrorCode GenerateKey(const AuthorizationSet& key_desc, HidlBuf* key_blob,
428                           KeyCharacteristics* key_characteristics) {
429         EXPECT_NE(key_blob, nullptr);
430         EXPECT_NE(key_characteristics, nullptr);
431         EXPECT_EQ(0U, key_blob->size());
432 
433         ErrorCode error;
434         EXPECT_TRUE(keymaster_
435                         ->generateKey(key_desc.hidl_data(),
436                                       [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
437                                           const KeyCharacteristics& hidl_key_characteristics) {
438                                           error = hidl_error;
439                                           *key_blob = hidl_key_blob;
440                                           *key_characteristics = hidl_key_characteristics;
441                                       })
442                         .isOk());
443         // On error, blob & characteristics should be empty.
444         if (error != ErrorCode::OK) {
445             EXPECT_EQ(0U, key_blob->size());
446             EXPECT_EQ(0U, (key_characteristics->softwareEnforced.size() +
447                            key_characteristics->teeEnforced.size()));
448         }
449         return error;
450     }
451 
GenerateKey(const AuthorizationSet & key_desc)452     ErrorCode GenerateKey(const AuthorizationSet& key_desc) {
453         return GenerateKey(key_desc, &key_blob_, &key_characteristics_);
454     }
455 
ImportKey(const AuthorizationSet & key_desc,KeyFormat format,const string & key_material,HidlBuf * key_blob,KeyCharacteristics * key_characteristics)456     ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
457                         const string& key_material, HidlBuf* key_blob,
458                         KeyCharacteristics* key_characteristics) {
459         ErrorCode error;
460         EXPECT_TRUE(keymaster_
461                         ->importKey(key_desc.hidl_data(), format, HidlBuf(key_material),
462                                     [&](ErrorCode hidl_error, const HidlBuf& hidl_key_blob,
463                                         const KeyCharacteristics& hidl_key_characteristics) {
464                                         error = hidl_error;
465                                         *key_blob = hidl_key_blob;
466                                         *key_characteristics = hidl_key_characteristics;
467                                     })
468                         .isOk());
469         // On error, blob & characteristics should be empty.
470         if (error != ErrorCode::OK) {
471             EXPECT_EQ(0U, key_blob->size());
472             EXPECT_EQ(0U, (key_characteristics->softwareEnforced.size() +
473                            key_characteristics->teeEnforced.size()));
474         }
475         return error;
476     }
477 
ImportKey(const AuthorizationSet & key_desc,KeyFormat format,const string & key_material)478     ErrorCode ImportKey(const AuthorizationSet& key_desc, KeyFormat format,
479                         const string& key_material) {
480         return ImportKey(key_desc, format, key_material, &key_blob_, &key_characteristics_);
481     }
482 
ExportKey(KeyFormat format,const HidlBuf & key_blob,const HidlBuf & client_id,const HidlBuf & app_data,HidlBuf * key_material)483     ErrorCode ExportKey(KeyFormat format, const HidlBuf& key_blob, const HidlBuf& client_id,
484                         const HidlBuf& app_data, HidlBuf* key_material) {
485         ErrorCode error;
486         EXPECT_TRUE(
487             keymaster_
488                 ->exportKey(format, key_blob, client_id, app_data,
489                             [&](ErrorCode hidl_error_code, const HidlBuf& hidl_key_material) {
490                                 error = hidl_error_code;
491                                 *key_material = hidl_key_material;
492                             })
493                 .isOk());
494         // On error, blob should be empty.
495         if (error != ErrorCode::OK) {
496             EXPECT_EQ(0U, key_material->size());
497         }
498         return error;
499     }
500 
ExportKey(KeyFormat format,HidlBuf * key_material)501     ErrorCode ExportKey(KeyFormat format, HidlBuf* key_material) {
502         HidlBuf client_id, app_data;
503         return ExportKey(format, key_blob_, client_id, app_data, key_material);
504     }
505 
DeleteKey(HidlBuf * key_blob,bool keep_key_blob=false)506     ErrorCode DeleteKey(HidlBuf* key_blob, bool keep_key_blob = false) {
507         ErrorCode error = keymaster_->deleteKey(*key_blob);
508         if (!keep_key_blob) *key_blob = HidlBuf();
509         return error;
510     }
511 
DeleteKey(bool keep_key_blob=false)512     ErrorCode DeleteKey(bool keep_key_blob = false) {
513         return DeleteKey(&key_blob_, keep_key_blob);
514     }
515 
DeleteAllKeys()516     ErrorCode DeleteAllKeys() {
517         ErrorCode error = keymaster_->deleteAllKeys();
518         return error;
519     }
520 
CheckedDeleteKey(HidlBuf * key_blob,bool keep_key_blob=false)521     void CheckedDeleteKey(HidlBuf* key_blob, bool keep_key_blob = false) {
522         auto rc = DeleteKey(key_blob, keep_key_blob);
523         EXPECT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
524     }
525 
CheckedDeleteKey()526     void CheckedDeleteKey() { CheckedDeleteKey(&key_blob_); }
527 
GetCharacteristics(const HidlBuf & key_blob,const HidlBuf & client_id,const HidlBuf & app_data,KeyCharacteristics * key_characteristics)528     ErrorCode GetCharacteristics(const HidlBuf& key_blob, const HidlBuf& client_id,
529                                  const HidlBuf& app_data, KeyCharacteristics* key_characteristics) {
530         ErrorCode error;
531         keymaster_->getKeyCharacteristics(
532             key_blob, client_id, app_data,
533             [&](ErrorCode hidl_error, const KeyCharacteristics& hidl_key_characteristics) {
534                 error = hidl_error, *key_characteristics = hidl_key_characteristics;
535             });
536         return error;
537     }
538 
GetCharacteristics(const HidlBuf & key_blob,KeyCharacteristics * key_characteristics)539     ErrorCode GetCharacteristics(const HidlBuf& key_blob, KeyCharacteristics* key_characteristics) {
540         HidlBuf client_id, app_data;
541         return GetCharacteristics(key_blob, client_id, app_data, key_characteristics);
542     }
543 
Begin(KeyPurpose purpose,const HidlBuf & key_blob,const AuthorizationSet & in_params,AuthorizationSet * out_params,OperationHandle * op_handle)544     ErrorCode Begin(KeyPurpose purpose, const HidlBuf& key_blob, const AuthorizationSet& in_params,
545                     AuthorizationSet* out_params, OperationHandle* op_handle) {
546         SCOPED_TRACE("Begin");
547         ErrorCode error;
548         OperationHandle saved_handle = *op_handle;
549         EXPECT_TRUE(
550             keymaster_
551                 ->begin(purpose, key_blob, in_params.hidl_data(),
552                         [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params,
553                             uint64_t hidl_op_handle) {
554                             error = hidl_error;
555                             *out_params = hidl_out_params;
556                             *op_handle = hidl_op_handle;
557                         })
558                 .isOk());
559         if (error != ErrorCode::OK) {
560             // Some implementations may modify *op_handle on error.
561             *op_handle = saved_handle;
562         }
563         return error;
564     }
565 
Begin(KeyPurpose purpose,const AuthorizationSet & in_params,AuthorizationSet * out_params)566     ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params,
567                     AuthorizationSet* out_params) {
568         SCOPED_TRACE("Begin");
569         EXPECT_EQ(kOpHandleSentinel, op_handle_);
570         return Begin(purpose, key_blob_, in_params, out_params, &op_handle_);
571     }
572 
Begin(KeyPurpose purpose,const AuthorizationSet & in_params)573     ErrorCode Begin(KeyPurpose purpose, const AuthorizationSet& in_params) {
574         SCOPED_TRACE("Begin");
575         AuthorizationSet out_params;
576         ErrorCode error = Begin(purpose, in_params, &out_params);
577         EXPECT_TRUE(out_params.empty());
578         return error;
579     }
580 
Update(OperationHandle op_handle,const AuthorizationSet & in_params,const string & input,AuthorizationSet * out_params,string * output,size_t * input_consumed)581     ErrorCode Update(OperationHandle op_handle, const AuthorizationSet& in_params,
582                      const string& input, AuthorizationSet* out_params, string* output,
583                      size_t* input_consumed) {
584         SCOPED_TRACE("Update");
585         ErrorCode error;
586         EXPECT_TRUE(keymaster_
587                         ->update(op_handle, in_params.hidl_data(), HidlBuf(input),
588                                  [&](ErrorCode hidl_error, uint32_t hidl_input_consumed,
589                                      const hidl_vec<KeyParameter>& hidl_out_params,
590                                      const HidlBuf& hidl_output) {
591                                      error = hidl_error;
592                                      out_params->push_back(AuthorizationSet(hidl_out_params));
593                                      output->append(hidl_output.to_string());
594                                      *input_consumed = hidl_input_consumed;
595                                  })
596                         .isOk());
597         return error;
598     }
599 
Update(const string & input,string * out,size_t * input_consumed)600     ErrorCode Update(const string& input, string* out, size_t* input_consumed) {
601         SCOPED_TRACE("Update");
602         AuthorizationSet out_params;
603         ErrorCode error = Update(op_handle_, AuthorizationSet() /* in_params */, input, &out_params,
604                                  out, input_consumed);
605         EXPECT_TRUE(out_params.empty());
606         return error;
607     }
608 
Finish(OperationHandle op_handle,const AuthorizationSet & in_params,const string & input,const string & signature,AuthorizationSet * out_params,string * output)609     ErrorCode Finish(OperationHandle op_handle, const AuthorizationSet& in_params,
610                      const string& input, const string& signature, AuthorizationSet* out_params,
611                      string* output) {
612         SCOPED_TRACE("Finish");
613         ErrorCode error;
614         EXPECT_TRUE(
615             keymaster_
616                 ->finish(op_handle, in_params.hidl_data(), HidlBuf(input), HidlBuf(signature),
617                          [&](ErrorCode hidl_error, const hidl_vec<KeyParameter>& hidl_out_params,
618                              const HidlBuf& hidl_output) {
619                              error = hidl_error;
620                              *out_params = hidl_out_params;
621                              output->append(hidl_output.to_string());
622                          })
623                 .isOk());
624         op_handle_ = kOpHandleSentinel;  // So dtor doesn't Abort().
625         return error;
626     }
627 
Finish(const string & message,string * output)628     ErrorCode Finish(const string& message, string* output) {
629         SCOPED_TRACE("Finish");
630         AuthorizationSet out_params;
631         string finish_output;
632         ErrorCode error = Finish(op_handle_, AuthorizationSet() /* in_params */, message,
633                                  "" /* signature */, &out_params, output);
634         if (error != ErrorCode::OK) {
635             return error;
636         }
637         EXPECT_EQ(0U, out_params.size());
638         return error;
639     }
640 
Finish(const string & message,const string & signature,string * output)641     ErrorCode Finish(const string& message, const string& signature, string* output) {
642         SCOPED_TRACE("Finish");
643         AuthorizationSet out_params;
644         ErrorCode error = Finish(op_handle_, AuthorizationSet() /* in_params */, message, signature,
645                                  &out_params, output);
646         op_handle_ = kOpHandleSentinel;  // So dtor doesn't Abort().
647         if (error != ErrorCode::OK) {
648             return error;
649         }
650         EXPECT_EQ(0U, out_params.size());
651         return error;
652     }
653 
Abort(OperationHandle op_handle)654     ErrorCode Abort(OperationHandle op_handle) {
655         SCOPED_TRACE("Abort");
656         auto retval = keymaster_->abort(op_handle);
657         EXPECT_TRUE(retval.isOk());
658         return retval;
659     }
660 
AbortIfNeeded()661     void AbortIfNeeded() {
662         SCOPED_TRACE("AbortIfNeeded");
663         if (op_handle_ != kOpHandleSentinel) {
664             EXPECT_EQ(ErrorCode::OK, Abort(op_handle_));
665             op_handle_ = kOpHandleSentinel;
666         }
667     }
668 
AttestKey(const HidlBuf & key_blob,const AuthorizationSet & attest_params,hidl_vec<hidl_vec<uint8_t>> * cert_chain)669     ErrorCode AttestKey(const HidlBuf& key_blob, const AuthorizationSet& attest_params,
670                         hidl_vec<hidl_vec<uint8_t>>* cert_chain) {
671         SCOPED_TRACE("AttestKey");
672         ErrorCode error;
673         keymaster_->attestKey(
674             key_blob, attest_params.hidl_data(),
675             [&](ErrorCode hidl_error, const hidl_vec<hidl_vec<uint8_t>>& hidl_cert_chain) {
676                 error = hidl_error;
677                 *cert_chain = hidl_cert_chain;
678             });
679         return error;
680     }
681 
AttestKey(const AuthorizationSet & attest_params,hidl_vec<hidl_vec<uint8_t>> * cert_chain)682     ErrorCode AttestKey(const AuthorizationSet& attest_params,
683                         hidl_vec<hidl_vec<uint8_t>>* cert_chain) {
684         SCOPED_TRACE("AttestKey");
685         return AttestKey(key_blob_, attest_params, cert_chain);
686     }
687 
ProcessMessage(const HidlBuf & key_blob,KeyPurpose operation,const string & message,const AuthorizationSet & in_params,AuthorizationSet * out_params)688     string ProcessMessage(const HidlBuf& key_blob, KeyPurpose operation, const string& message,
689                           const AuthorizationSet& in_params, AuthorizationSet* out_params) {
690         SCOPED_TRACE("ProcessMessage");
691         AuthorizationSet begin_out_params;
692         EXPECT_EQ(ErrorCode::OK,
693                   Begin(operation, key_blob, in_params, &begin_out_params, &op_handle_));
694 
695         string unused;
696         AuthorizationSet finish_params;
697         AuthorizationSet finish_out_params;
698         string output;
699         EXPECT_EQ(ErrorCode::OK,
700                   Finish(op_handle_, finish_params, message, unused, &finish_out_params, &output));
701         op_handle_ = kOpHandleSentinel;
702 
703         out_params->push_back(begin_out_params);
704         out_params->push_back(finish_out_params);
705         return output;
706     }
707 
SignMessage(const HidlBuf & key_blob,const string & message,const AuthorizationSet & params)708     string SignMessage(const HidlBuf& key_blob, const string& message,
709                        const AuthorizationSet& params) {
710         SCOPED_TRACE("SignMessage");
711         AuthorizationSet out_params;
712         string signature = ProcessMessage(key_blob, KeyPurpose::SIGN, message, params, &out_params);
713         EXPECT_TRUE(out_params.empty());
714         return signature;
715     }
716 
SignMessage(const string & message,const AuthorizationSet & params)717     string SignMessage(const string& message, const AuthorizationSet& params) {
718         SCOPED_TRACE("SignMessage");
719         return SignMessage(key_blob_, message, params);
720     }
721 
MacMessage(const string & message,Digest digest,size_t mac_length)722     string MacMessage(const string& message, Digest digest, size_t mac_length) {
723         SCOPED_TRACE("MacMessage");
724         return SignMessage(
725             key_blob_, message,
726             AuthorizationSetBuilder().Digest(digest).Authorization(TAG_MAC_LENGTH, mac_length));
727     }
728 
CheckHmacTestVector(const string & key,const string & message,Digest digest,const string & expected_mac)729     void CheckHmacTestVector(const string& key, const string& message, Digest digest,
730                              const string& expected_mac) {
731         SCOPED_TRACE("CheckHmacTestVector");
732         ASSERT_EQ(ErrorCode::OK,
733                   ImportKey(AuthorizationSetBuilder()
734                                 .Authorization(TAG_NO_AUTH_REQUIRED)
735                                 .HmacKey(key.size() * 8)
736                                 .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
737                                 .Digest(digest),
738                             KeyFormat::RAW, key));
739         string signature = MacMessage(message, digest, expected_mac.size() * 8);
740         EXPECT_EQ(expected_mac, signature) << "Test vector didn't match for digest " << (int)digest;
741         CheckedDeleteKey();
742     }
743 
CheckAesCtrTestVector(const string & key,const string & nonce,const string & message,const string & expected_ciphertext)744     void CheckAesCtrTestVector(const string& key, const string& nonce, const string& message,
745                                const string& expected_ciphertext) {
746         SCOPED_TRACE("CheckAesCtrTestVector");
747         ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
748                                                .Authorization(TAG_NO_AUTH_REQUIRED)
749                                                .AesEncryptionKey(key.size() * 8)
750                                                .BlockMode(BlockMode::CTR)
751                                                .Authorization(TAG_CALLER_NONCE)
752                                                .Padding(PaddingMode::NONE),
753                                            KeyFormat::RAW, key));
754 
755         auto params = AuthorizationSetBuilder()
756                           .Authorization(TAG_NONCE, nonce.data(), nonce.size())
757                           .BlockMode(BlockMode::CTR)
758                           .Padding(PaddingMode::NONE);
759         AuthorizationSet out_params;
760         string ciphertext = EncryptMessage(key_blob_, message, params, &out_params);
761         EXPECT_EQ(expected_ciphertext, ciphertext);
762     }
763 
VerifyMessage(const HidlBuf & key_blob,const string & message,const string & signature,const AuthorizationSet & params)764     void VerifyMessage(const HidlBuf& key_blob, const string& message, const string& signature,
765                        const AuthorizationSet& params) {
766         SCOPED_TRACE("VerifyMessage");
767         AuthorizationSet begin_out_params;
768         ASSERT_EQ(ErrorCode::OK,
769                   Begin(KeyPurpose::VERIFY, key_blob, params, &begin_out_params, &op_handle_));
770 
771         string unused;
772         AuthorizationSet finish_params;
773         AuthorizationSet finish_out_params;
774         string output;
775         EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, signature,
776                                         &finish_out_params, &output));
777         op_handle_ = kOpHandleSentinel;
778         EXPECT_TRUE(output.empty());
779     }
780 
VerifyMessage(const string & message,const string & signature,const AuthorizationSet & params)781     void VerifyMessage(const string& message, const string& signature,
782                        const AuthorizationSet& params) {
783         SCOPED_TRACE("VerifyMessage");
784         VerifyMessage(key_blob_, message, signature, params);
785     }
786 
EncryptMessage(const HidlBuf & key_blob,const string & message,const AuthorizationSet & in_params,AuthorizationSet * out_params)787     string EncryptMessage(const HidlBuf& key_blob, const string& message,
788                           const AuthorizationSet& in_params, AuthorizationSet* out_params) {
789         SCOPED_TRACE("EncryptMessage");
790         return ProcessMessage(key_blob, KeyPurpose::ENCRYPT, message, in_params, out_params);
791     }
792 
EncryptMessage(const string & message,const AuthorizationSet & params,AuthorizationSet * out_params)793     string EncryptMessage(const string& message, const AuthorizationSet& params,
794                           AuthorizationSet* out_params) {
795         SCOPED_TRACE("EncryptMessage");
796         return EncryptMessage(key_blob_, message, params, out_params);
797     }
798 
EncryptMessage(const string & message,const AuthorizationSet & params)799     string EncryptMessage(const string& message, const AuthorizationSet& params) {
800         SCOPED_TRACE("EncryptMessage");
801         AuthorizationSet out_params;
802         string ciphertext = EncryptMessage(message, params, &out_params);
803         EXPECT_TRUE(out_params.empty())
804             << "Output params should be empty. Contained: " << out_params;
805         return ciphertext;
806     }
807 
DecryptMessage(const HidlBuf & key_blob,const string & ciphertext,const AuthorizationSet & params)808     string DecryptMessage(const HidlBuf& key_blob, const string& ciphertext,
809                           const AuthorizationSet& params) {
810         SCOPED_TRACE("DecryptMessage");
811         AuthorizationSet out_params;
812         string plaintext =
813             ProcessMessage(key_blob, KeyPurpose::DECRYPT, ciphertext, params, &out_params);
814         EXPECT_TRUE(out_params.empty());
815         return plaintext;
816     }
817 
DecryptMessage(const string & ciphertext,const AuthorizationSet & params)818     string DecryptMessage(const string& ciphertext, const AuthorizationSet& params) {
819         SCOPED_TRACE("DecryptMessage");
820         return DecryptMessage(key_blob_, ciphertext, params);
821     }
822 
823     template <TagType tag_type, Tag tag, typename ValueT>
CheckKm0CryptoParam(TypedTag<tag_type,tag> ttag,ValueT expected)824     void CheckKm0CryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
825         SCOPED_TRACE("CheckKm0CryptoParam");
826         if (is_secure_) {
827             EXPECT_TRUE(contains(key_characteristics_.teeEnforced, ttag, expected));
828             EXPECT_FALSE(contains(key_characteristics_.softwareEnforced, ttag));
829         } else {
830             EXPECT_TRUE(contains(key_characteristics_.softwareEnforced, ttag, expected));
831             EXPECT_FALSE(contains(key_characteristics_.teeEnforced, ttag));
832         }
833     }
834 
835     template <TagType tag_type, Tag tag, typename ValueT>
CheckKm1CryptoParam(TypedTag<tag_type,tag> ttag,ValueT expected)836     void CheckKm1CryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
837         SCOPED_TRACE("CheckKm1CryptoParam");
838         if (is_secure_ && supports_symmetric_) {
839             EXPECT_TRUE(contains(key_characteristics_.teeEnforced, ttag, expected));
840             EXPECT_FALSE(contains(key_characteristics_.softwareEnforced, ttag));
841         } else {
842             EXPECT_TRUE(contains(key_characteristics_.softwareEnforced, ttag, expected));
843             EXPECT_FALSE(contains(key_characteristics_.teeEnforced, ttag));
844         }
845     }
846 
847     template <TagType tag_type, Tag tag, typename ValueT>
CheckKm2CryptoParam(TypedTag<tag_type,tag> ttag,ValueT expected)848     void CheckKm2CryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
849         SCOPED_TRACE("CheckKm2CryptoParam");
850         if (supports_attestation_) {
851             EXPECT_TRUE(contains(key_characteristics_.teeEnforced, ttag, expected));
852             EXPECT_FALSE(contains(key_characteristics_.softwareEnforced, ttag));
853         } else if (!supports_symmetric_ /* KM version < 1 or SW */) {
854             EXPECT_TRUE(contains(key_characteristics_.softwareEnforced, ttag, expected));
855             EXPECT_FALSE(contains(key_characteristics_.teeEnforced, ttag));
856         }
857     }
858 
CheckOrigin()859     void CheckOrigin() {
860         SCOPED_TRACE("CheckOrigin");
861         if (is_secure_ && supports_symmetric_) {
862             EXPECT_TRUE(
863                 contains(key_characteristics_.teeEnforced, TAG_ORIGIN, KeyOrigin::IMPORTED));
864         } else if (is_secure_) {
865             EXPECT_TRUE(contains(key_characteristics_.teeEnforced, TAG_ORIGIN, KeyOrigin::UNKNOWN));
866         } else {
867             EXPECT_TRUE(
868                 contains(key_characteristics_.softwareEnforced, TAG_ORIGIN, KeyOrigin::IMPORTED));
869         }
870     }
871 
IsSecure()872     static bool IsSecure() { return is_secure_; }
SupportsEc()873     static bool SupportsEc() { return supports_ec_; }
SupportsSymmetric()874     static bool SupportsSymmetric() { return supports_symmetric_; }
SupportsAllDigests()875     static bool SupportsAllDigests() { return supports_all_digests_; }
SupportsAttestation()876     static bool SupportsAttestation() { return supports_attestation_; }
877 
Km2Profile()878     static bool Km2Profile() {
879         return SupportsAttestation() && SupportsAllDigests() && SupportsSymmetric() &&
880                SupportsEc() && IsSecure();
881     }
882 
Km1Profile()883     static bool Km1Profile() {
884         return !SupportsAttestation() && SupportsSymmetric() && SupportsEc() && IsSecure();
885     }
886 
Km0Profile()887     static bool Km0Profile() {
888         return !SupportsAttestation() && !SupportsAllDigests() && !SupportsSymmetric() &&
889                IsSecure();
890     }
891 
SwOnlyProfile()892     static bool SwOnlyProfile() {
893         return !SupportsAttestation() && !SupportsAllDigests() && !SupportsSymmetric() &&
894                !SupportsEc() && !IsSecure();
895     }
896 
897     HidlBuf key_blob_;
898     KeyCharacteristics key_characteristics_;
899     OperationHandle op_handle_ = kOpHandleSentinel;
900 
901   private:
902     static sp<IKeymasterDevice> keymaster_;
903     static uint32_t os_version_;
904     static uint32_t os_patch_level_;
905 
906     static bool is_secure_;
907     static bool supports_ec_;
908     static bool supports_symmetric_;
909     static bool supports_attestation_;
910     static bool supports_all_digests_;
911     static hidl_string name_;
912     static hidl_string author_;
913 };
914 
verify_attestation_record(const string & challenge,const string & app_id,AuthorizationSet expected_sw_enforced,AuthorizationSet expected_tee_enforced,const hidl_vec<uint8_t> & attestation_cert)915 bool verify_attestation_record(const string& challenge, const string& app_id,
916                                AuthorizationSet expected_sw_enforced,
917                                AuthorizationSet expected_tee_enforced,
918                                const hidl_vec<uint8_t>& attestation_cert) {
919     X509_Ptr cert(parse_cert_blob(attestation_cert));
920     EXPECT_TRUE(!!cert.get());
921     if (!cert.get()) return false;
922 
923     ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
924     EXPECT_TRUE(!!attest_rec);
925     if (!attest_rec) return false;
926 
927     AuthorizationSet att_sw_enforced;
928     AuthorizationSet att_tee_enforced;
929     uint32_t att_attestation_version;
930     uint32_t att_keymaster_version;
931     SecurityLevel att_attestation_security_level;
932     SecurityLevel att_keymaster_security_level;
933     HidlBuf att_challenge;
934     HidlBuf att_unique_id;
935     HidlBuf att_app_id;
936     EXPECT_EQ(ErrorCode::OK,
937               parse_attestation_record(attest_rec->data,                 //
938                                        attest_rec->length,               //
939                                        &att_attestation_version,         //
940                                        &att_attestation_security_level,  //
941                                        &att_keymaster_version,           //
942                                        &att_keymaster_security_level,    //
943                                        &att_challenge,                   //
944                                        &att_sw_enforced,                 //
945                                        &att_tee_enforced,                //
946                                        &att_unique_id));
947 
948     EXPECT_TRUE(att_attestation_version == 1 || att_attestation_version == 2);
949 
950     expected_sw_enforced.push_back(TAG_ATTESTATION_APPLICATION_ID,
951                                    HidlBuf(app_id));
952 
953     if (!KeymasterHidlTest::IsSecure()) {
954         // SW is KM2
955         EXPECT_EQ(att_keymaster_version, 2U);
956     }
957 
958     if (KeymasterHidlTest::SupportsSymmetric()) {
959         EXPECT_GE(att_keymaster_version, 1U);
960     }
961 
962     if (KeymasterHidlTest::SupportsAttestation()) {
963         EXPECT_GE(att_keymaster_version, 2U);
964     }
965 
966     EXPECT_EQ(KeymasterHidlTest::IsSecure() ? SecurityLevel::TRUSTED_ENVIRONMENT
967                                             : SecurityLevel::SOFTWARE,
968               att_keymaster_security_level);
969     EXPECT_EQ(KeymasterHidlTest::SupportsAttestation() ? SecurityLevel::TRUSTED_ENVIRONMENT
970                                                        : SecurityLevel::SOFTWARE,
971               att_attestation_security_level);
972 
973     EXPECT_EQ(challenge.length(), att_challenge.size());
974     EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data(), challenge.length()));
975 
976     att_sw_enforced.Sort();
977     expected_sw_enforced.Sort();
978     EXPECT_EQ(filter_tags(expected_sw_enforced), filter_tags(att_sw_enforced));
979 
980     att_tee_enforced.Sort();
981     expected_tee_enforced.Sort();
982     EXPECT_EQ(filter_tags(expected_tee_enforced), filter_tags(att_tee_enforced));
983 
984     return true;
985 }
986 
987 sp<IKeymasterDevice> KeymasterHidlTest::keymaster_;
988 uint32_t KeymasterHidlTest::os_version_;
989 uint32_t KeymasterHidlTest::os_patch_level_;
990 bool KeymasterHidlTest::is_secure_;
991 bool KeymasterHidlTest::supports_ec_;
992 bool KeymasterHidlTest::supports_symmetric_;
993 bool KeymasterHidlTest::supports_all_digests_;
994 bool KeymasterHidlTest::supports_attestation_;
995 hidl_string KeymasterHidlTest::name_;
996 hidl_string KeymasterHidlTest::author_;
997 
998 typedef KeymasterHidlTest KeymasterVersionTest;
999 
1000 /*
1001  * KeymasterVersionTest.SensibleFeatures:
1002  *
1003  * Queries keymaster to find the set of features it supports. Fails if the combination doesn't
1004  * correspond to any well-defined keymaster version.
1005  */
TEST_F(KeymasterVersionTest,SensibleFeatures)1006 TEST_F(KeymasterVersionTest, SensibleFeatures) {
1007     EXPECT_TRUE(Km2Profile() || Km1Profile() || Km0Profile() || SwOnlyProfile())
1008         << "Keymaster feature set doesn't fit any reasonable profile.  Reported features:"
1009         << "SupportsAttestation [" << SupportsAttestation() << "], "
1010         << "SupportsSymmetric [" << SupportsSymmetric() << "], "
1011         << "SupportsAllDigests [" << SupportsAllDigests() << "], "
1012         << "SupportsEc [" << SupportsEc() << "], "
1013         << "IsSecure [" << IsSecure() << "]";
1014 }
1015 
1016 class NewKeyGenerationTest : public KeymasterHidlTest {
1017   protected:
CheckBaseParams(const KeyCharacteristics & keyCharacteristics)1018     void CheckBaseParams(const KeyCharacteristics& keyCharacteristics) {
1019         // TODO(swillden): Distinguish which params should be in which auth list.
1020 
1021         AuthorizationSet auths(keyCharacteristics.teeEnforced);
1022         auths.push_back(AuthorizationSet(keyCharacteristics.softwareEnforced));
1023 
1024         EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1025 
1026         EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1027         EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1028         EXPECT_TRUE(auths.Contains(TAG_USER_ID, 7))
1029             << "User ID should be 7, was " << auths.GetTagValue(TAG_USER_ID);
1030 
1031         // Verify that App ID, App data and ROT are NOT included.
1032         EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1033         EXPECT_FALSE(auths.Contains(TAG_APPLICATION_ID));
1034         EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1035 
1036         // Check that some unexpected tags/values are NOT present.
1037         EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
1038         EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1039         EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301));
1040 
1041         // Now check that unspecified, defaulted tags are correct.
1042         EXPECT_TRUE(auths.Contains(TAG_CREATION_DATETIME));
1043 
1044         if (SupportsAttestation()) {
1045             EXPECT_TRUE(auths.Contains(TAG_OS_VERSION, os_version()))
1046                 << "OS version is " << os_version() << " key reported "
1047                 << auths.GetTagValue(TAG_OS_VERSION);
1048             EXPECT_TRUE(auths.Contains(TAG_OS_PATCHLEVEL, os_patch_level()))
1049                 << "OS patch level is " << os_patch_level() << " key reported "
1050                 << auths.GetTagValue(TAG_OS_PATCHLEVEL);
1051         }
1052     }
1053 };
1054 
1055 /*
1056  * NewKeyGenerationTest.Rsa
1057  *
1058  * Verifies that keymaster can generate all required RSA key sizes, and that the resulting keys have
1059  * correct characteristics.
1060  */
TEST_F(NewKeyGenerationTest,Rsa)1061 TEST_F(NewKeyGenerationTest, Rsa) {
1062     for (auto key_size : {1024, 2048, 3072, 4096}) {
1063         HidlBuf key_blob;
1064         KeyCharacteristics key_characteristics;
1065         ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1066                                                  .RsaSigningKey(key_size, 3)
1067                                                  .Digest(Digest::NONE)
1068                                                  .Padding(PaddingMode::NONE)
1069                                                  .Authorizations(UserAuths()),
1070                                              &key_blob, &key_characteristics));
1071 
1072         ASSERT_GT(key_blob.size(), 0U);
1073         CheckBaseParams(key_characteristics);
1074 
1075         AuthorizationSet crypto_params;
1076         if (IsSecure()) {
1077             crypto_params = key_characteristics.teeEnforced;
1078         } else {
1079             crypto_params = key_characteristics.softwareEnforced;
1080         }
1081 
1082         EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, KM_ALGORITHM_RSA));
1083         EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size));
1084         EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 3));
1085 
1086         CheckedDeleteKey(&key_blob);
1087     }
1088 }
1089 
1090 /*
1091  * NewKeyGenerationTest.RsaNoDefaultSize
1092  *
1093  * Verifies that failing to specify a key size for RSA key generation returns UNSUPPORTED_KEY_SIZE.
1094  */
TEST_F(NewKeyGenerationTest,RsaNoDefaultSize)1095 TEST_F(NewKeyGenerationTest, RsaNoDefaultSize) {
1096     ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1097               GenerateKey(AuthorizationSetBuilder()
1098                               .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1099                               .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3)
1100                               .SigningKey()));
1101 }
1102 
1103 /*
1104  * NewKeyGenerationTest.Ecdsa
1105  *
1106  * Verifies that keymaster can generate all required EC key sizes, and that the resulting keys have
1107  * correct characteristics.
1108  */
TEST_F(NewKeyGenerationTest,Ecdsa)1109 TEST_F(NewKeyGenerationTest, Ecdsa) {
1110     for (auto key_size : {224, 256, 384, 521}) {
1111         HidlBuf key_blob;
1112         KeyCharacteristics key_characteristics;
1113         ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1114                                                  .EcdsaSigningKey(key_size)
1115                                                  .Digest(Digest::NONE)
1116                                                  .Authorizations(UserAuths()),
1117                                              &key_blob, &key_characteristics));
1118         ASSERT_GT(key_blob.size(), 0U);
1119         CheckBaseParams(key_characteristics);
1120 
1121         AuthorizationSet crypto_params;
1122         if (IsSecure()) {
1123             crypto_params = key_characteristics.teeEnforced;
1124         } else {
1125             crypto_params = key_characteristics.softwareEnforced;
1126         }
1127 
1128         EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1129         EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size));
1130 
1131         CheckedDeleteKey(&key_blob);
1132     }
1133 }
1134 
1135 /*
1136  * NewKeyGenerationTest.EcdsaDefaultSize
1137  *
1138  * Verifies that failing to specify a key size for EC key generation returns UNSUPPORTED_KEY_SIZE.
1139  */
TEST_F(NewKeyGenerationTest,EcdsaDefaultSize)1140 TEST_F(NewKeyGenerationTest, EcdsaDefaultSize) {
1141     ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1142               GenerateKey(AuthorizationSetBuilder()
1143                               .Authorization(TAG_ALGORITHM, Algorithm::EC)
1144                               .SigningKey()
1145                               .Digest(Digest::NONE)));
1146 }
1147 
1148 /*
1149  * NewKeyGenerationTest.EcdsaInvalidSize
1150  *
1151  * Verifies that failing to specify an invalid key size for EC key generation returns
1152  * UNSUPPORTED_KEY_SIZE.
1153  */
TEST_F(NewKeyGenerationTest,EcdsaInvalidSize)1154 TEST_F(NewKeyGenerationTest, EcdsaInvalidSize) {
1155     ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1156               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(Digest::NONE)));
1157 }
1158 
1159 /*
1160  * NewKeyGenerationTest.EcdsaMismatchKeySize
1161  *
1162  * Verifies that specifying mismatched key size and curve for EC key generation returns
1163  * INVALID_ARGUMENT.
1164  */
TEST_F(NewKeyGenerationTest,EcdsaMismatchKeySize)1165 TEST_F(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1166     ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
1167               GenerateKey(AuthorizationSetBuilder()
1168                               .EcdsaSigningKey(224)
1169                               .Authorization(TAG_EC_CURVE, EcCurve::P_256)
1170                               .Digest(Digest::NONE)))
1171         << "(Possibly b/36233343)";
1172 }
1173 
TEST_F(NewKeyGenerationTest,EcdsaAllValidSizes)1174 TEST_F(NewKeyGenerationTest, EcdsaAllValidSizes) {
1175     size_t valid_sizes[] = {224, 256, 384, 521};
1176     for (size_t size : valid_sizes) {
1177         EXPECT_EQ(ErrorCode::OK,
1178                   GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(size).Digest(Digest::NONE)))
1179             << "Failed to generate size: " << size;
1180         CheckedDeleteKey();
1181     }
1182 }
1183 
1184 /*
1185  * NewKeyGenerationTest.EcdsaAllValidCurves
1186  *
1187  * Verifies that keymaster supports all required EC curves.
1188  */
TEST_F(NewKeyGenerationTest,EcdsaAllValidCurves)1189 TEST_F(NewKeyGenerationTest, EcdsaAllValidCurves) {
1190     EcCurve curves[] = {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521};
1191     for (auto curve : curves) {
1192         EXPECT_EQ(
1193             ErrorCode::OK,
1194             GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(curve).Digest(Digest::SHA_2_512)))
1195             << "Failed to generate key on curve: " << curve;
1196         CheckedDeleteKey();
1197     }
1198 }
1199 
1200 /*
1201  * NewKeyGenerationTest.Hmac
1202  *
1203  * Verifies that keymaster supports all required digests, and that the resulting keys have correct
1204  * characteristics.
1205  */
TEST_F(NewKeyGenerationTest,Hmac)1206 TEST_F(NewKeyGenerationTest, Hmac) {
1207     for (auto digest : {Digest::MD5, Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256,
1208                         Digest::SHA_2_384, Digest::SHA_2_512}) {
1209         HidlBuf key_blob;
1210         KeyCharacteristics key_characteristics;
1211         constexpr size_t key_size = 128;
1212         ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1213                                                  .HmacKey(key_size)
1214                                                  .Digest(digest)
1215                                                  .Authorization(TAG_MIN_MAC_LENGTH, 128)
1216                                                  .Authorizations(UserAuths()),
1217                                              &key_blob, &key_characteristics));
1218 
1219         ASSERT_GT(key_blob.size(), 0U);
1220         CheckBaseParams(key_characteristics);
1221 
1222         AuthorizationSet teeEnforced = key_characteristics.teeEnforced;
1223         AuthorizationSet softwareEnforced = key_characteristics.softwareEnforced;
1224         if (SupportsAttestation() || SupportsAllDigests()) {
1225             // Either KM2, which must support all, or KM1 that claims full support
1226             EXPECT_TRUE(teeEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1227             EXPECT_TRUE(teeEnforced.Contains(TAG_KEY_SIZE, key_size));
1228         } else if (SupportsSymmetric()) {
1229             if (digest == Digest::SHA1 || digest == Digest::SHA_2_256) {
1230                 // KM1 must support SHA1 and SHA256 in hardware
1231                 EXPECT_TRUE(teeEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1232                 EXPECT_TRUE(teeEnforced.Contains(TAG_KEY_SIZE, key_size));
1233             } else {
1234                 // Othere digests may or may not be supported
1235                 EXPECT_TRUE(teeEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC) ||
1236                             softwareEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1237                 EXPECT_TRUE(teeEnforced.Contains(TAG_KEY_SIZE, key_size) ||
1238                             softwareEnforced.Contains(TAG_KEY_SIZE, key_size));
1239             }
1240         } else {
1241             // KM0 and SW KM do all digests in SW.
1242             EXPECT_TRUE(softwareEnforced.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1243             EXPECT_TRUE(softwareEnforced.Contains(TAG_KEY_SIZE, key_size));
1244         }
1245 
1246         CheckedDeleteKey(&key_blob);
1247     }
1248 }
1249 
1250 /*
1251  * NewKeyGenerationTest.HmacCheckKeySizes
1252  *
1253  * Verifies that keymaster supports all key sizes, and rejects all invalid key sizes.
1254  */
TEST_F(NewKeyGenerationTest,HmacCheckKeySizes)1255 TEST_F(NewKeyGenerationTest, HmacCheckKeySizes) {
1256     for (size_t key_size = 0; key_size <= 512; ++key_size) {
1257         if (key_size < 64 || key_size % 8 != 0) {
1258             // To keep this test from being very slow, we only test a random fraction of non-byte
1259             // key sizes.  We test only ~10% of such cases. Since there are 392 of them, we expect
1260             // to run ~40 of them in each run.
1261             if (key_size % 8 == 0 || random() % 10 == 0) {
1262                 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1263                           GenerateKey(AuthorizationSetBuilder()
1264                                           .HmacKey(key_size)
1265                                           .Digest(Digest::SHA_2_256)
1266                                           .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1267                     << "HMAC key size " << key_size << " invalid (Possibly b/33462346)";
1268             }
1269         } else {
1270             EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1271                                                      .HmacKey(key_size)
1272                                                      .Digest(Digest::SHA_2_256)
1273                                                      .Authorization(TAG_MIN_MAC_LENGTH, 256)));
1274             CheckedDeleteKey();
1275         }
1276     }
1277 }
1278 
1279 /*
1280  * NewKeyGenerationTest.HmacCheckMinMacLengths
1281  *
1282  * Verifies that keymaster supports all required MAC lengths and rejects all invalid lengths.  This
1283  * test is probabilistic in order to keep the runtime down, but any failure prints out the specific
1284  * MAC length that failed, so reproducing a failed run will be easy.
1285  */
TEST_F(NewKeyGenerationTest,HmacCheckMinMacLengths)1286 TEST_F(NewKeyGenerationTest, HmacCheckMinMacLengths) {
1287     for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
1288         if (min_mac_length < 64 || min_mac_length % 8 != 0) {
1289             // To keep this test from being very long, we only test a random fraction of non-byte
1290             // lengths.  We test only ~10% of such cases. Since there are 172 of them, we expect to
1291             // run ~17 of them in each run.
1292             if (min_mac_length % 8 == 0 || random() % 10 == 0) {
1293                 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
1294                           GenerateKey(AuthorizationSetBuilder()
1295                                           .HmacKey(128)
1296                                           .Digest(Digest::SHA_2_256)
1297                                           .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1298                     << "HMAC min mac length " << min_mac_length << " invalid.";
1299             }
1300         } else {
1301             EXPECT_EQ(ErrorCode::OK,
1302                       GenerateKey(AuthorizationSetBuilder()
1303                                       .HmacKey(128)
1304                                       .Digest(Digest::SHA_2_256)
1305                                       .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)));
1306             CheckedDeleteKey();
1307         }
1308     }
1309 }
1310 
1311 /*
1312  * NewKeyGenerationTest.HmacMultipleDigests
1313  *
1314  * Verifies that keymaster rejects HMAC key generation with multiple specified digest algorithms.
1315  */
TEST_F(NewKeyGenerationTest,HmacMultipleDigests)1316 TEST_F(NewKeyGenerationTest, HmacMultipleDigests) {
1317     ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1318               GenerateKey(AuthorizationSetBuilder()
1319                               .HmacKey(128)
1320                               .Digest(Digest::SHA1)
1321                               .Digest(Digest::SHA_2_256)
1322                               .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1323 }
1324 
1325 /*
1326  * NewKeyGenerationTest.HmacDigestNone
1327  *
1328  * Verifies that keymaster rejects HMAC key generation with no digest or Digest::NONE
1329  */
TEST_F(NewKeyGenerationTest,HmacDigestNone)1330 TEST_F(NewKeyGenerationTest, HmacDigestNone) {
1331     ASSERT_EQ(
1332         ErrorCode::UNSUPPORTED_DIGEST,
1333         GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH, 128)));
1334 
1335     ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1336               GenerateKey(AuthorizationSetBuilder()
1337                               .HmacKey(128)
1338                               .Digest(Digest::NONE)
1339                               .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1340 }
1341 
1342 typedef KeymasterHidlTest GetKeyCharacteristicsTest;
1343 
1344 /*
1345  * GetKeyCharacteristicsTest.HmacDigestNone
1346  *
1347  * Verifies that getKeyCharacteristics functions, and that generated and retrieved key
1348  * characteristics match.
1349  */
TEST_F(GetKeyCharacteristicsTest,SimpleRsa)1350 TEST_F(GetKeyCharacteristicsTest, SimpleRsa) {
1351     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1352                                              .RsaSigningKey(1024, 3)
1353                                              .Digest(Digest::NONE)
1354                                              .Padding(PaddingMode::NONE)));
1355 
1356     KeyCharacteristics retrieved_chars;
1357     ASSERT_EQ(ErrorCode::OK, GetCharacteristics(key_blob_, &retrieved_chars));
1358 
1359     AuthorizationSet gen_sw = key_characteristics_.softwareEnforced;
1360     AuthorizationSet gen_tee = key_characteristics_.teeEnforced;
1361     AuthorizationSet retrieved_sw = retrieved_chars.softwareEnforced;
1362     AuthorizationSet retrieved_tee = retrieved_chars.teeEnforced;
1363 
1364     EXPECT_EQ(gen_sw, retrieved_sw);
1365     EXPECT_EQ(gen_tee, retrieved_tee);
1366 }
1367 
1368 typedef KeymasterHidlTest SigningOperationsTest;
1369 
1370 /*
1371  * SigningOperationsTest.RsaSuccess
1372  *
1373  * Verifies that raw RSA signature operations succeed.
1374  */
TEST_F(SigningOperationsTest,RsaSuccess)1375 TEST_F(SigningOperationsTest, RsaSuccess) {
1376     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1377                                              .RsaSigningKey(1024, 3)
1378                                              .Digest(Digest::NONE)
1379                                              .Padding(PaddingMode::NONE)
1380                                              .Authorization(TAG_NO_AUTH_REQUIRED)));
1381     string message = "12345678901234567890123456789012";
1382     string signature = SignMessage(
1383         message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1384 }
1385 
1386 /*
1387  * SigningOperationsTest.RsaPssSha256Success
1388  *
1389  * Verifies that RSA-PSS signature operations succeed.
1390  */
TEST_F(SigningOperationsTest,RsaPssSha256Success)1391 TEST_F(SigningOperationsTest, RsaPssSha256Success) {
1392     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1393                                              .RsaSigningKey(1024, 3)
1394                                              .Digest(Digest::SHA_2_256)
1395                                              .Padding(PaddingMode::RSA_PSS)
1396                                              .Authorization(TAG_NO_AUTH_REQUIRED)));
1397     // Use large message, which won't work without digesting.
1398     string message(1024, 'a');
1399     string signature = SignMessage(
1400         message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
1401 }
1402 
1403 /*
1404  * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
1405  *
1406  * Verifies that keymaster rejects signature operations that specify a padding mode when the key
1407  * supports only unpadded operations.
1408  */
TEST_F(SigningOperationsTest,RsaPaddingNoneDoesNotAllowOther)1409 TEST_F(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
1410     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1411                                              .RsaSigningKey(1024, 3)
1412                                              .Digest(Digest::NONE)
1413                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1414                                              .Padding(PaddingMode::NONE)));
1415     string message = "12345678901234567890123456789012";
1416     string signature;
1417 
1418     EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
1419               Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1420                                           .Digest(Digest::NONE)
1421                                           .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1422 }
1423 
1424 /*
1425  * SigningOperationsTest.RsaPkcs1Sha256Success
1426  *
1427  * Verifies that digested RSA-PKCS1 signature operations succeed.
1428  */
TEST_F(SigningOperationsTest,RsaPkcs1Sha256Success)1429 TEST_F(SigningOperationsTest, RsaPkcs1Sha256Success) {
1430     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1431                                              .RsaSigningKey(1024, 3)
1432                                              .Digest(Digest::SHA_2_256)
1433                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1434                                              .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1435     string message(1024, 'a');
1436     string signature = SignMessage(message, AuthorizationSetBuilder()
1437                                                 .Digest(Digest::SHA_2_256)
1438                                                 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1439 }
1440 
1441 /*
1442  * SigningOperationsTest.RsaPkcs1NoDigestSuccess
1443  *
1444  * Verifies that undigested RSA-PKCS1 signature operations succeed.
1445  */
TEST_F(SigningOperationsTest,RsaPkcs1NoDigestSuccess)1446 TEST_F(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
1447     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1448                                              .RsaSigningKey(1024, 3)
1449                                              .Digest(Digest::NONE)
1450                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1451                                              .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1452     string message(53, 'a');
1453     string signature = SignMessage(
1454         message,
1455         AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1456 }
1457 
1458 /*
1459  * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
1460  *
1461  * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
1462  * given a too-long message.
1463  */
TEST_F(SigningOperationsTest,RsaPkcs1NoDigestTooLong)1464 TEST_F(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
1465     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1466                                              .RsaSigningKey(1024, 3)
1467                                              .Digest(Digest::NONE)
1468                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1469                                              .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1470     string message(129, 'a');
1471 
1472     EXPECT_EQ(ErrorCode::OK,
1473               Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1474                                           .Digest(Digest::NONE)
1475                                           .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1476     string signature;
1477     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
1478 }
1479 
1480 /*
1481  * SigningOperationsTest.RsaPssSha512TooSmallKey
1482  *
1483  * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
1484  * used with a key that is too small for the message.
1485  *
1486  * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the keymaster
1487  * specification requires that salt_size == digest_size, so the message will be digest_size * 2 +
1488  * 16. Such a message can only be signed by a given key if the key is at least that size. This test
1489  * uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large for a
1490  * 1024-bit key.
1491  */
TEST_F(SigningOperationsTest,RsaPssSha512TooSmallKey)1492 TEST_F(SigningOperationsTest, RsaPssSha512TooSmallKey) {
1493     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1494                                              .RsaSigningKey(1024, 3)
1495                                              .Digest(Digest::SHA_2_512)
1496                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1497                                              .Padding(PaddingMode::RSA_PSS)));
1498     EXPECT_EQ(
1499         ErrorCode::INCOMPATIBLE_DIGEST,
1500         Begin(KeyPurpose::SIGN,
1501               AuthorizationSetBuilder().Digest(Digest::SHA_2_512).Padding(PaddingMode::RSA_PSS)))
1502         << "(Possibly b/33346750)";
1503 }
1504 
1505 /*
1506  * SigningOperationsTest.RsaNoPaddingTooLong
1507  *
1508  * Verifies that raw RSA signature operations fail with the correct error code when
1509  * given a too-long message.
1510  */
TEST_F(SigningOperationsTest,RsaNoPaddingTooLong)1511 TEST_F(SigningOperationsTest, RsaNoPaddingTooLong) {
1512     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1513                                              .RsaSigningKey(1024, 3)
1514                                              .Digest(Digest::NONE)
1515                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1516                                              .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1517     // One byte too long
1518     string message(1024 / 8 + 1, 'a');
1519     ASSERT_EQ(ErrorCode::OK,
1520               Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1521                                           .Digest(Digest::NONE)
1522                                           .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1523     string result;
1524     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
1525 
1526     // Very large message that should exceed the transfer buffer size of any reasonable TEE.
1527     message = string(128 * 1024, 'a');
1528     ASSERT_EQ(ErrorCode::OK,
1529               Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1530                                           .Digest(Digest::NONE)
1531                                           .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1532     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
1533 }
1534 
1535 /*
1536  * SigningOperationsTest.RsaAbort
1537  *
1538  * Verifies that operations can be aborted correctly.  Uses an RSA signing operation for the test,
1539  * but the behavior should be algorithm and purpose-independent.
1540  */
TEST_F(SigningOperationsTest,RsaAbort)1541 TEST_F(SigningOperationsTest, RsaAbort) {
1542     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1543                                              .RsaSigningKey(1024, 3)
1544                                              .Digest(Digest::NONE)
1545                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1546                                              .Padding(PaddingMode::NONE)));
1547 
1548     ASSERT_EQ(ErrorCode::OK,
1549               Begin(KeyPurpose::SIGN,
1550                     AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1551     EXPECT_EQ(ErrorCode::OK, Abort(op_handle_));
1552 
1553     // Another abort should fail
1554     EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort(op_handle_));
1555 
1556     // Set to sentinel, so TearDown() doesn't try to abort again.
1557     op_handle_ = kOpHandleSentinel;
1558 }
1559 
1560 /*
1561  * SigningOperationsTest.RsaUnsupportedPadding
1562  *
1563  * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used with a
1564  * padding mode inappropriate for RSA.
1565  */
TEST_F(SigningOperationsTest,RsaUnsupportedPadding)1566 TEST_F(SigningOperationsTest, RsaUnsupportedPadding) {
1567     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1568                                              .RsaSigningKey(1024, 3)
1569                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1570                                              .Digest(Digest::SHA_2_256 /* supported digest */)
1571                                              .Padding(PaddingMode::PKCS7)));
1572     ASSERT_EQ(
1573         ErrorCode::UNSUPPORTED_PADDING_MODE,
1574         Begin(KeyPurpose::SIGN,
1575               AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
1576 }
1577 
1578 /*
1579  * SigningOperationsTest.RsaPssNoDigest
1580  *
1581  * Verifies that RSA PSS operations fail when no digest is used.  PSS requires a digest.
1582  */
TEST_F(SigningOperationsTest,RsaNoDigest)1583 TEST_F(SigningOperationsTest, RsaNoDigest) {
1584     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1585                                              .RsaSigningKey(1024, 3)
1586                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1587                                              .Digest(Digest::NONE)
1588                                              .Padding(PaddingMode::RSA_PSS)));
1589     ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
1590               Begin(KeyPurpose::SIGN,
1591                     AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
1592 
1593     ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1594               Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
1595 }
1596 
1597 /*
1598  * SigningOperationsTest.RsaPssNoDigest
1599  *
1600  * Verifies that RSA operations fail when no padding mode is specified.  PaddingMode::NONE is
1601  * supported in some cases (as validated in other tests), but a mode must be specified.
1602  */
TEST_F(SigningOperationsTest,RsaNoPadding)1603 TEST_F(SigningOperationsTest, RsaNoPadding) {
1604     // Padding must be specified
1605     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1606                                              .RsaKey(1024, 3)
1607                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1608                                              .SigningKey()
1609                                              .Digest(Digest::NONE)));
1610     ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
1611               Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
1612 }
1613 
1614 /*
1615  * SigningOperationsTest.RsaShortMessage
1616  *
1617  * Verifies that raw RSA signatures succeed with a message shorter than the key size.
1618  */
TEST_F(SigningOperationsTest,RsaTooShortMessage)1619 TEST_F(SigningOperationsTest, RsaTooShortMessage) {
1620     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1621                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1622                                              .RsaSigningKey(1024, 3)
1623                                              .Digest(Digest::NONE)
1624                                              .Padding(PaddingMode::NONE)));
1625 
1626     // Barely shorter
1627     string message(1024 / 8 - 1, 'a');
1628     SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1629 
1630     // Much shorter
1631     message = "a";
1632     SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1633 }
1634 
1635 /*
1636  * SigningOperationsTest.RsaSignWithEncryptionKey
1637  *
1638  * Verifies that RSA encryption keys cannot be used to sign.
1639  */
TEST_F(SigningOperationsTest,RsaSignWithEncryptionKey)1640 TEST_F(SigningOperationsTest, RsaSignWithEncryptionKey) {
1641     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1642                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1643                                              .RsaEncryptionKey(1024, 3)
1644                                              .Digest(Digest::NONE)
1645                                              .Padding(PaddingMode::NONE)));
1646     ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
1647               Begin(KeyPurpose::SIGN,
1648                     AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1649 }
1650 
1651 /*
1652  * SigningOperationsTest.RsaSignTooLargeMessage
1653  *
1654  * Verifies that attempting a raw signature of a message which is the same length as the key, but
1655  * numerically larger than the public modulus, fails with the correct error.
1656  */
TEST_F(SigningOperationsTest,RsaSignTooLargeMessage)1657 TEST_F(SigningOperationsTest, RsaSignTooLargeMessage) {
1658     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1659                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1660                                              .RsaSigningKey(1024, 3)
1661                                              .Digest(Digest::NONE)
1662                                              .Padding(PaddingMode::NONE)));
1663 
1664     // Largest possible message will always be larger than the public modulus.
1665     string message(1024 / 8, static_cast<char>(0xff));
1666     ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1667                                                          .Authorization(TAG_NO_AUTH_REQUIRED)
1668                                                          .Digest(Digest::NONE)
1669                                                          .Padding(PaddingMode::NONE)));
1670     string signature;
1671     ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
1672 }
1673 
1674 /*
1675  * SigningOperationsTest.EcdsaAllSizesAndHashes
1676  *
1677  * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
1678  */
TEST_F(SigningOperationsTest,EcdsaAllSizesAndHashes)1679 TEST_F(SigningOperationsTest, EcdsaAllSizesAndHashes) {
1680     for (auto key_size : {224, 256, 384, 521}) {
1681         for (auto digest : {
1682                  Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1683                  Digest::SHA_2_512,
1684              }) {
1685             ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1686                                               .Authorization(TAG_NO_AUTH_REQUIRED)
1687                                               .EcdsaSigningKey(key_size)
1688                                               .Digest(digest));
1689             EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
1690                                             << " and digest " << digest;
1691             if (error != ErrorCode::OK) continue;
1692 
1693             string message(1024, 'a');
1694             if (digest == Digest::NONE) message.resize(key_size / 8);
1695             SignMessage(message, AuthorizationSetBuilder().Digest(digest));
1696             CheckedDeleteKey();
1697         }
1698     }
1699 }
1700 
1701 /*
1702  * SigningOperationsTest.EcdsaAllCurves
1703  *
1704  * Verifies that ECDSA operations succeed with all possible curves.
1705  */
TEST_F(SigningOperationsTest,EcdsaAllCurves)1706 TEST_F(SigningOperationsTest, EcdsaAllCurves) {
1707     for (auto curve : {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521}) {
1708         ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1709                                           .Authorization(TAG_NO_AUTH_REQUIRED)
1710                                           .EcdsaSigningKey(curve)
1711                                           .Digest(Digest::SHA_2_256));
1712         EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
1713         if (error != ErrorCode::OK) continue;
1714 
1715         string message(1024, 'a');
1716         SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1717         CheckedDeleteKey();
1718     }
1719 }
1720 
1721 /*
1722  * SigningOperationsTest.EcdsaNoDigestHugeData
1723  *
1724  * Verifies that ECDSA operations support very large messages, even without digesting.  This should
1725  * work because ECDSA actually only signs the leftmost L_n bits of the message, however large it may
1726  * be.  Not using digesting is a bad idea, but in some cases digesting is done by the framework.
1727  */
TEST_F(SigningOperationsTest,EcdsaNoDigestHugeData)1728 TEST_F(SigningOperationsTest, EcdsaNoDigestHugeData) {
1729     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1730                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1731                                              .EcdsaSigningKey(224)
1732                                              .Digest(Digest::NONE)));
1733     string message(64 * 1024, 'a');
1734     SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
1735 }
1736 
1737 /*
1738  * SigningOperationsTest.AesEcbSign
1739  *
1740  * Verifies that attempts to use AES keys to sign fail in the correct way.
1741  */
TEST_F(SigningOperationsTest,AesEcbSign)1742 TEST_F(SigningOperationsTest, AesEcbSign) {
1743     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1744                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1745                                              .SigningKey()
1746                                              .AesEncryptionKey(128)
1747                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)))
1748         << "(Possibly b/36252957)";
1749 
1750     AuthorizationSet out_params;
1751     EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1752               Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params))
1753         << "(Possibly b/36233187)";
1754 
1755     EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1756               Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params))
1757         << "(Possibly b/36233187)";
1758 }
1759 
1760 /*
1761  * SigningOperationsTest.HmacAllDigests
1762  *
1763  * Verifies that HMAC works with all digests.
1764  */
TEST_F(SigningOperationsTest,HmacAllDigests)1765 TEST_F(SigningOperationsTest, HmacAllDigests) {
1766     for (auto digest : {Digest::SHA1, Digest::SHA_2_224, Digest::SHA_2_256, Digest::SHA_2_384,
1767                         Digest::SHA_2_512}) {
1768         ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1769                                                  .Authorization(TAG_NO_AUTH_REQUIRED)
1770                                                  .HmacKey(128)
1771                                                  .Digest(digest)
1772                                                  .Authorization(TAG_MIN_MAC_LENGTH, 160)))
1773             << "Failed to create HMAC key with digest " << digest;
1774         string message = "12345678901234567890123456789012";
1775         string signature = MacMessage(message, digest, 160);
1776         EXPECT_EQ(160U / 8U, signature.size())
1777             << "Failed to sign with HMAC key with digest " << digest;
1778         CheckedDeleteKey();
1779     }
1780 }
1781 
1782 /*
1783  * SigningOperationsTest.HmacSha256TooLargeMacLength
1784  *
1785  * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the digest
1786  * size.
1787  */
TEST_F(SigningOperationsTest,HmacSha256TooLargeMacLength)1788 TEST_F(SigningOperationsTest, HmacSha256TooLargeMacLength) {
1789     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1790                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1791                                              .HmacKey(128)
1792                                              .Digest(Digest::SHA_2_256)
1793                                              .Authorization(TAG_MIN_MAC_LENGTH, 256)));
1794     AuthorizationSet output_params;
1795     EXPECT_EQ(
1796         ErrorCode::UNSUPPORTED_MAC_LENGTH,
1797         Begin(
1798             KeyPurpose::SIGN, key_blob_,
1799             AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 264),
1800             &output_params, &op_handle_));
1801 }
1802 
1803 /*
1804  * SigningOperationsTest.HmacSha256TooSmallMacLength
1805  *
1806  * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
1807  * specified minimum MAC length.
1808  */
TEST_F(SigningOperationsTest,HmacSha256TooSmallMacLength)1809 TEST_F(SigningOperationsTest, HmacSha256TooSmallMacLength) {
1810     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1811                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1812                                              .HmacKey(128)
1813                                              .Digest(Digest::SHA_2_256)
1814                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1815     AuthorizationSet output_params;
1816     EXPECT_EQ(
1817         ErrorCode::INVALID_MAC_LENGTH,
1818         Begin(
1819             KeyPurpose::SIGN, key_blob_,
1820             AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 120),
1821             &output_params, &op_handle_));
1822 }
1823 
1824 /*
1825  * SigningOperationsTest.HmacRfc4231TestCase3
1826  *
1827  * Validates against the test vectors from RFC 4231 test case 3.
1828  */
TEST_F(SigningOperationsTest,HmacRfc4231TestCase3)1829 TEST_F(SigningOperationsTest, HmacRfc4231TestCase3) {
1830     string key(20, 0xaa);
1831     string message(50, 0xdd);
1832     uint8_t sha_224_expected[] = {
1833         0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
1834         0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
1835     };
1836     uint8_t sha_256_expected[] = {
1837         0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
1838         0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
1839         0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
1840     };
1841     uint8_t sha_384_expected[] = {
1842         0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
1843         0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
1844         0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
1845         0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
1846     };
1847     uint8_t sha_512_expected[] = {
1848         0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
1849         0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
1850         0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
1851         0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
1852         0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
1853     };
1854 
1855     CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1856     CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1857     CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1858     CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1859 }
1860 
1861 /*
1862  * SigningOperationsTest.HmacRfc4231TestCase5
1863  *
1864  * Validates against the test vectors from RFC 4231 test case 5.
1865  */
TEST_F(SigningOperationsTest,HmacRfc4231TestCase5)1866 TEST_F(SigningOperationsTest, HmacRfc4231TestCase5) {
1867     string key(20, 0x0c);
1868     string message = "Test With Truncation";
1869 
1870     uint8_t sha_224_expected[] = {
1871         0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
1872         0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
1873     };
1874     uint8_t sha_256_expected[] = {
1875         0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
1876         0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
1877     };
1878     uint8_t sha_384_expected[] = {
1879         0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
1880         0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
1881     };
1882     uint8_t sha_512_expected[] = {
1883         0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
1884         0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
1885     };
1886 
1887     CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1888     CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1889     CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1890     CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1891 }
1892 
1893 /*
1894  * SigningOperationsTest.HmacRfc4231TestCase6
1895  *
1896  * Validates against the test vectors from RFC 4231 test case 6.
1897  */
TEST_F(SigningOperationsTest,HmacRfc4231TestCase6)1898 TEST_F(SigningOperationsTest, HmacRfc4231TestCase6) {
1899     string key(131, 0xaa);
1900     string message = "Test Using Larger Than Block-Size Key - Hash Key First";
1901 
1902     uint8_t sha_224_expected[] = {
1903         0x95, 0xe9, 0xa0, 0xdb, 0x96, 0x20, 0x95, 0xad, 0xae, 0xbe, 0x9b, 0x2d, 0x6f, 0x0d,
1904         0xbc, 0xe2, 0xd4, 0x99, 0xf1, 0x12, 0xf2, 0xd2, 0xb7, 0x27, 0x3f, 0xa6, 0x87, 0x0e,
1905     };
1906     uint8_t sha_256_expected[] = {
1907         0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26,
1908         0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28,
1909         0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54,
1910     };
1911     uint8_t sha_384_expected[] = {
1912         0x4e, 0xce, 0x08, 0x44, 0x85, 0x81, 0x3e, 0x90, 0x88, 0xd2, 0xc6, 0x3a,
1913         0x04, 0x1b, 0xc5, 0xb4, 0x4f, 0x9e, 0xf1, 0x01, 0x2a, 0x2b, 0x58, 0x8f,
1914         0x3c, 0xd1, 0x1f, 0x05, 0x03, 0x3a, 0xc4, 0xc6, 0x0c, 0x2e, 0xf6, 0xab,
1915         0x40, 0x30, 0xfe, 0x82, 0x96, 0x24, 0x8d, 0xf1, 0x63, 0xf4, 0x49, 0x52,
1916     };
1917     uint8_t sha_512_expected[] = {
1918         0x80, 0xb2, 0x42, 0x63, 0xc7, 0xc1, 0xa3, 0xeb, 0xb7, 0x14, 0x93, 0xc1, 0xdd,
1919         0x7b, 0xe8, 0xb4, 0x9b, 0x46, 0xd1, 0xf4, 0x1b, 0x4a, 0xee, 0xc1, 0x12, 0x1b,
1920         0x01, 0x37, 0x83, 0xf8, 0xf3, 0x52, 0x6b, 0x56, 0xd0, 0x37, 0xe0, 0x5f, 0x25,
1921         0x98, 0xbd, 0x0f, 0xd2, 0x21, 0x5d, 0x6a, 0x1e, 0x52, 0x95, 0xe6, 0x4f, 0x73,
1922         0xf6, 0x3f, 0x0a, 0xec, 0x8b, 0x91, 0x5a, 0x98, 0x5d, 0x78, 0x65, 0x98,
1923     };
1924 
1925     CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1926     CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1927     CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1928     CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1929 }
1930 
1931 /*
1932  * SigningOperationsTest.HmacRfc4231TestCase7
1933  *
1934  * Validates against the test vectors from RFC 4231 test case 7.
1935  */
TEST_F(SigningOperationsTest,HmacRfc4231TestCase7)1936 TEST_F(SigningOperationsTest, HmacRfc4231TestCase7) {
1937     string key(131, 0xaa);
1938     string message = "This is a test using a larger than block-size key and a larger than "
1939                      "block-size data. The key needs to be hashed before being used by the HMAC "
1940                      "algorithm.";
1941 
1942     uint8_t sha_224_expected[] = {
1943         0x3a, 0x85, 0x41, 0x66, 0xac, 0x5d, 0x9f, 0x02, 0x3f, 0x54, 0xd5, 0x17, 0xd0, 0xb3,
1944         0x9d, 0xbd, 0x94, 0x67, 0x70, 0xdb, 0x9c, 0x2b, 0x95, 0xc9, 0xf6, 0xf5, 0x65, 0xd1,
1945     };
1946     uint8_t sha_256_expected[] = {
1947         0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f,
1948         0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07,
1949         0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2,
1950     };
1951     uint8_t sha_384_expected[] = {
1952         0x66, 0x17, 0x17, 0x8e, 0x94, 0x1f, 0x02, 0x0d, 0x35, 0x1e, 0x2f, 0x25,
1953         0x4e, 0x8f, 0xd3, 0x2c, 0x60, 0x24, 0x20, 0xfe, 0xb0, 0xb8, 0xfb, 0x9a,
1954         0xdc, 0xce, 0xbb, 0x82, 0x46, 0x1e, 0x99, 0xc5, 0xa6, 0x78, 0xcc, 0x31,
1955         0xe7, 0x99, 0x17, 0x6d, 0x38, 0x60, 0xe6, 0x11, 0x0c, 0x46, 0x52, 0x3e,
1956     };
1957     uint8_t sha_512_expected[] = {
1958         0xe3, 0x7b, 0x6a, 0x77, 0x5d, 0xc8, 0x7d, 0xba, 0xa4, 0xdf, 0xa9, 0xf9, 0x6e,
1959         0x5e, 0x3f, 0xfd, 0xde, 0xbd, 0x71, 0xf8, 0x86, 0x72, 0x89, 0x86, 0x5d, 0xf5,
1960         0xa3, 0x2d, 0x20, 0xcd, 0xc9, 0x44, 0xb6, 0x02, 0x2c, 0xac, 0x3c, 0x49, 0x82,
1961         0xb1, 0x0d, 0x5e, 0xeb, 0x55, 0xc3, 0xe4, 0xde, 0x15, 0x13, 0x46, 0x76, 0xfb,
1962         0x6d, 0xe0, 0x44, 0x60, 0x65, 0xc9, 0x74, 0x40, 0xfa, 0x8c, 0x6a, 0x58,
1963     };
1964 
1965     CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1966     CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1967     CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1968     CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1969 }
1970 
1971 typedef KeymasterHidlTest VerificationOperationsTest;
1972 
1973 /*
1974  * VerificationOperationsTest.RsaSuccess
1975  *
1976  * Verifies that a simple RSA signature/verification sequence succeeds.
1977  */
TEST_F(VerificationOperationsTest,RsaSuccess)1978 TEST_F(VerificationOperationsTest, RsaSuccess) {
1979     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1980                                              .Authorization(TAG_NO_AUTH_REQUIRED)
1981                                              .RsaSigningKey(1024, 3)
1982                                              .Digest(Digest::NONE)
1983                                              .Padding(PaddingMode::NONE)));
1984     string message = "12345678901234567890123456789012";
1985     string signature = SignMessage(
1986         message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1987     VerifyMessage(message, signature,
1988                   AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1989 }
1990 
1991 /*
1992  * VerificationOperationsTest.RsaSuccess
1993  *
1994  * Verifies RSA signature/verification for all padding modes and digests.
1995  */
TEST_F(VerificationOperationsTest,RsaAllPaddingsAndDigests)1996 TEST_F(VerificationOperationsTest, RsaAllPaddingsAndDigests) {
1997     ASSERT_EQ(ErrorCode::OK,
1998               GenerateKey(AuthorizationSetBuilder()
1999                               .Authorization(TAG_NO_AUTH_REQUIRED)
2000                               .RsaSigningKey(2048, 3)
2001                               .Digest(Digest::NONE, Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
2002                                       Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512)
2003                               .Padding(PaddingMode::NONE)
2004                               .Padding(PaddingMode::RSA_PSS)
2005                               .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2006 
2007     string message(128, 'a');
2008     string corrupt_message(message);
2009     ++corrupt_message[corrupt_message.size() / 2];
2010 
2011     for (auto padding :
2012          {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2013 
2014         for (auto digest : {Digest::NONE, Digest::MD5, Digest::SHA1, Digest::SHA_2_224,
2015                             Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512}) {
2016             if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2017                 // Digesting only makes sense with padding.
2018                 continue;
2019             }
2020 
2021             if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2022                 // PSS requires digesting.
2023                 continue;
2024             }
2025 
2026             string signature =
2027                 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2028             VerifyMessage(message, signature,
2029                           AuthorizationSetBuilder().Digest(digest).Padding(padding));
2030 
2031             if (digest != Digest::NONE) {
2032                 // Verify with OpenSSL.
2033                 HidlBuf pubkey;
2034                 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey));
2035 
2036                 const uint8_t* p = pubkey.data();
2037                 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
2038                 ASSERT_TRUE(pkey.get());
2039 
2040                 EVP_MD_CTX digest_ctx;
2041                 EVP_MD_CTX_init(&digest_ctx);
2042                 EVP_PKEY_CTX* pkey_ctx;
2043                 const EVP_MD* md = openssl_digest(digest);
2044                 ASSERT_NE(md, nullptr);
2045                 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr /* engine */,
2046                                                   pkey.get()));
2047 
2048                 switch (padding) {
2049                 case PaddingMode::RSA_PSS:
2050                     EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING), 0);
2051                     EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, EVP_MD_size(md)), 0);
2052                     break;
2053                 case PaddingMode::RSA_PKCS1_1_5_SIGN:
2054                     // PKCS1 is the default; don't need to set anything.
2055                     break;
2056                 default:
2057                     FAIL();
2058                     break;
2059                 }
2060 
2061                 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()));
2062                 EXPECT_EQ(1, EVP_DigestVerifyFinal(
2063                                  &digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
2064                                  signature.size()));
2065                 EVP_MD_CTX_cleanup(&digest_ctx);
2066             }
2067 
2068             // Corrupt signature shouldn't verify.
2069             string corrupt_signature(signature);
2070             ++corrupt_signature[corrupt_signature.size() / 2];
2071 
2072             EXPECT_EQ(ErrorCode::OK,
2073                       Begin(KeyPurpose::VERIFY,
2074                             AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2075             string result;
2076             EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result));
2077 
2078             // Corrupt message shouldn't verify
2079             EXPECT_EQ(ErrorCode::OK,
2080                       Begin(KeyPurpose::VERIFY,
2081                             AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2082             EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result));
2083         }
2084     }
2085 }
2086 
2087 /*
2088  * VerificationOperationsTest.RsaSuccess
2089  *
2090  * Verifies ECDSA signature/verification for all digests and curves.
2091  */
TEST_F(VerificationOperationsTest,EcdsaAllDigestsAndCurves)2092 TEST_F(VerificationOperationsTest, EcdsaAllDigestsAndCurves) {
2093     auto digests = {
2094         Digest::NONE,      Digest::SHA1,      Digest::SHA_2_224,
2095         Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512,
2096     };
2097 
2098     string message = "1234567890";
2099     string corrupt_message = "2234567890";
2100     for (auto curve : {EcCurve::P_224, EcCurve::P_256, EcCurve::P_384, EcCurve::P_521}) {
2101         ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2102                                           .Authorization(TAG_NO_AUTH_REQUIRED)
2103                                           .EcdsaSigningKey(curve)
2104                                           .Digest(digests));
2105         EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2106         if (error != ErrorCode::OK) {
2107             continue;
2108         }
2109 
2110         for (auto digest : digests) {
2111             string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2112             VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2113 
2114             // Verify with OpenSSL
2115             if (digest != Digest::NONE) {
2116                 HidlBuf pubkey;
2117                 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey))
2118                     << curve << ' ' << digest;
2119 
2120                 const uint8_t* p = pubkey.data();
2121                 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
2122                 ASSERT_TRUE(pkey.get());
2123 
2124                 EVP_MD_CTX digest_ctx;
2125                 EVP_MD_CTX_init(&digest_ctx);
2126                 EVP_PKEY_CTX* pkey_ctx;
2127                 const EVP_MD* md = openssl_digest(digest);
2128 
2129                 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md, nullptr /* engine */,
2130                                                   pkey.get()))
2131                     << curve << ' ' << digest;
2132 
2133                 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()))
2134                     << curve << ' ' << digest;
2135 
2136                 EXPECT_EQ(1, EVP_DigestVerifyFinal(
2137                                  &digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
2138                                  signature.size()))
2139                     << curve << ' ' << digest;
2140 
2141                 EVP_MD_CTX_cleanup(&digest_ctx);
2142             }
2143 
2144             // Corrupt signature shouldn't verify.
2145             string corrupt_signature(signature);
2146             ++corrupt_signature[corrupt_signature.size() / 2];
2147 
2148             EXPECT_EQ(ErrorCode::OK,
2149                       Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2150                 << curve << ' ' << digest;
2151 
2152             string result;
2153             EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result))
2154                 << curve << ' ' << digest;
2155 
2156             // Corrupt message shouldn't verify
2157             EXPECT_EQ(ErrorCode::OK,
2158                       Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2159                 << curve << ' ' << digest;
2160 
2161             EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result))
2162                 << curve << ' ' << digest;
2163         }
2164 
2165         auto rc = DeleteKey();
2166         ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2167     }
2168 }
2169 
2170 /*
2171  * VerificationOperationsTest.HmacSigningKeyCannotVerify
2172  *
2173  * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2174  */
TEST_F(VerificationOperationsTest,HmacSigningKeyCannotVerify)2175 TEST_F(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2176     string key_material = "HelloThisIsAKey";
2177 
2178     HidlBuf signing_key, verification_key;
2179     KeyCharacteristics signing_key_chars, verification_key_chars;
2180     EXPECT_EQ(ErrorCode::OK,
2181               ImportKey(AuthorizationSetBuilder()
2182                             .Authorization(TAG_NO_AUTH_REQUIRED)
2183                             .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2184                             .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2185                             .Digest(Digest::SHA1)
2186                             .Authorization(TAG_MIN_MAC_LENGTH, 160),
2187                         KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2188     EXPECT_EQ(ErrorCode::OK,
2189               ImportKey(AuthorizationSetBuilder()
2190                             .Authorization(TAG_NO_AUTH_REQUIRED)
2191                             .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2192                             .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2193                             .Digest(Digest::SHA1)
2194                             .Authorization(TAG_MIN_MAC_LENGTH, 160),
2195                         KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2196 
2197     string message = "This is a message.";
2198     string signature = SignMessage(
2199         signing_key, message,
2200         AuthorizationSetBuilder().Digest(Digest::SHA1).Authorization(TAG_MAC_LENGTH, 160));
2201 
2202     // Signing key should not work.
2203     AuthorizationSet out_params;
2204     EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2205               Begin(KeyPurpose::VERIFY, signing_key, AuthorizationSetBuilder().Digest(Digest::SHA1),
2206                     &out_params, &op_handle_));
2207 
2208     // Verification key should work.
2209     VerifyMessage(verification_key, message, signature,
2210                   AuthorizationSetBuilder().Digest(Digest::SHA1));
2211 
2212     CheckedDeleteKey(&signing_key);
2213     CheckedDeleteKey(&verification_key);
2214 }
2215 
2216 typedef KeymasterHidlTest ExportKeyTest;
2217 
2218 /*
2219  * ExportKeyTest.RsaUnsupportedKeyFormat
2220  *
2221  * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2222  */
TEST_F(ExportKeyTest,RsaUnsupportedKeyFormat)2223 TEST_F(ExportKeyTest, RsaUnsupportedKeyFormat) {
2224     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2225                                              .RsaSigningKey(1024, 3)
2226                                              .Digest(Digest::NONE)
2227                                              .Padding(PaddingMode::NONE)));
2228     HidlBuf export_data;
2229     ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::PKCS8, &export_data));
2230 }
2231 
2232 /*
2233  * ExportKeyTest.RsaCorruptedKeyBlob
2234  *
2235  * Verifies that attempting to export RSA keys from corrupted key blobs fails.  This is essentially
2236  * a poor-man's key blob fuzzer.
2237  */
2238 // Disabled due to b/33385206
TEST_F(ExportKeyTest,DISABLED_RsaCorruptedKeyBlob)2239 TEST_F(ExportKeyTest, DISABLED_RsaCorruptedKeyBlob) {
2240     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2241                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2242                                              .RsaSigningKey(1024, 3)
2243                                              .Digest(Digest::NONE)
2244                                              .Padding(PaddingMode::NONE)));
2245     for (size_t i = 0; i < key_blob_.size(); ++i) {
2246         HidlBuf corrupted(key_blob_);
2247         ++corrupted[i];
2248 
2249         HidlBuf export_data;
2250         EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2251                   ExportKey(KeyFormat::X509, corrupted, HidlBuf(), HidlBuf(), &export_data))
2252             << "Blob corrupted at offset " << i << " erroneously accepted as valid";
2253     }
2254 }
2255 
2256 /*
2257  * ExportKeyTest.RsaCorruptedKeyBlob
2258  *
2259  * Verifies that attempting to export ECDSA keys from corrupted key blobs fails.  This is
2260  * essentially a poor-man's key blob fuzzer.
2261  */
2262 // Disabled due to b/33385206
TEST_F(ExportKeyTest,DISABLED_EcCorruptedKeyBlob)2263 TEST_F(ExportKeyTest, DISABLED_EcCorruptedKeyBlob) {
2264     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2265                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2266                                              .EcdsaSigningKey(EcCurve::P_256)
2267                                              .Digest(Digest::NONE)));
2268     for (size_t i = 0; i < key_blob_.size(); ++i) {
2269         HidlBuf corrupted(key_blob_);
2270         ++corrupted[i];
2271 
2272         HidlBuf export_data;
2273         EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2274                   ExportKey(KeyFormat::X509, corrupted, HidlBuf(), HidlBuf(), &export_data))
2275             << "Blob corrupted at offset " << i << " erroneously accepted as valid";
2276     }
2277 }
2278 
2279 /*
2280  * ExportKeyTest.AesKeyUnexportable
2281  *
2282  * Verifies that attempting to export AES keys fails in the expected way.
2283  */
TEST_F(ExportKeyTest,AesKeyUnexportable)2284 TEST_F(ExportKeyTest, AesKeyUnexportable) {
2285     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2286                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2287                                              .AesEncryptionKey(128)
2288                                              .EcbMode()
2289                                              .Padding(PaddingMode::NONE)));
2290 
2291     HidlBuf export_data;
2292     EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::X509, &export_data));
2293     EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::PKCS8, &export_data));
2294     EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_FORMAT, ExportKey(KeyFormat::RAW, &export_data));
2295 }
2296 typedef KeymasterHidlTest ImportKeyTest;
2297 
2298 /*
2299  * ImportKeyTest.RsaSuccess
2300  *
2301  * Verifies that importing and using an RSA key pair works correctly.
2302  */
TEST_F(ImportKeyTest,RsaSuccess)2303 TEST_F(ImportKeyTest, RsaSuccess) {
2304     ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2305                                            .Authorization(TAG_NO_AUTH_REQUIRED)
2306                                            .RsaSigningKey(1024, 65537)
2307                                            .Digest(Digest::SHA_2_256)
2308                                            .Padding(PaddingMode::RSA_PSS),
2309                                        KeyFormat::PKCS8, rsa_key));
2310 
2311     CheckKm0CryptoParam(TAG_ALGORITHM, Algorithm::RSA);
2312     CheckKm0CryptoParam(TAG_KEY_SIZE, 1024U);
2313     CheckKm0CryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
2314     CheckKm1CryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2315     CheckKm1CryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
2316     CheckOrigin();
2317 
2318     string message(1024 / 8, 'a');
2319     auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
2320     string signature = SignMessage(message, params);
2321     VerifyMessage(message, signature, params);
2322 }
2323 
2324 /*
2325  * ImportKeyTest.RsaKeySizeMismatch
2326  *
2327  * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
2328  * correct way.
2329  */
TEST_F(ImportKeyTest,RsaKeySizeMismatch)2330 TEST_F(ImportKeyTest, RsaKeySizeMismatch) {
2331     ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2332               ImportKey(AuthorizationSetBuilder()
2333                             .RsaSigningKey(2048 /* Doesn't match key */, 65537)
2334                             .Digest(Digest::NONE)
2335                             .Padding(PaddingMode::NONE),
2336                         KeyFormat::PKCS8, rsa_key));
2337 }
2338 
2339 /*
2340  * ImportKeyTest.RsaPublicExponentMismatch
2341  *
2342  * Verifies that importing an RSA key pair with a public exponent that doesn't match the key fails
2343  * in the correct way.
2344  */
TEST_F(ImportKeyTest,RsaPublicExponentMismatch)2345 TEST_F(ImportKeyTest, RsaPublicExponentMismatch) {
2346     ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2347               ImportKey(AuthorizationSetBuilder()
2348                             .RsaSigningKey(1024, 3 /* Doesn't match key */)
2349                             .Digest(Digest::NONE)
2350                             .Padding(PaddingMode::NONE),
2351                         KeyFormat::PKCS8, rsa_key));
2352 }
2353 
2354 /*
2355  * ImportKeyTest.EcdsaSuccess
2356  *
2357  * Verifies that importing and using an ECDSA P-256 key pair works correctly.
2358  */
TEST_F(ImportKeyTest,EcdsaSuccess)2359 TEST_F(ImportKeyTest, EcdsaSuccess) {
2360     ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2361                                            .Authorization(TAG_NO_AUTH_REQUIRED)
2362                                            .EcdsaSigningKey(256)
2363                                            .Digest(Digest::SHA_2_256),
2364                                        KeyFormat::PKCS8, ec_256_key))
2365         << "(Possibly b/33945114)";
2366 
2367     CheckKm0CryptoParam(TAG_ALGORITHM, Algorithm::EC);
2368     CheckKm0CryptoParam(TAG_KEY_SIZE, 256U);
2369     CheckKm1CryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2370     CheckKm2CryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2371 
2372     CheckOrigin();
2373 
2374     string message(32, 'a');
2375     auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2376     string signature = SignMessage(message, params);
2377     VerifyMessage(message, signature, params);
2378 }
2379 
2380 /*
2381  * ImportKeyTest.Ecdsa521Success
2382  *
2383  * Verifies that importing and using an ECDSA P-521 key pair works correctly.
2384  */
TEST_F(ImportKeyTest,Ecdsa521Success)2385 TEST_F(ImportKeyTest, Ecdsa521Success) {
2386     ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2387                                            .Authorization(TAG_NO_AUTH_REQUIRED)
2388                                            .EcdsaSigningKey(521)
2389                                            .Digest(Digest::SHA_2_256),
2390                                        KeyFormat::PKCS8, ec_521_key))
2391         << "(Possibly b/33945114)";
2392 
2393     CheckKm0CryptoParam(TAG_ALGORITHM, Algorithm::EC);
2394     CheckKm0CryptoParam(TAG_KEY_SIZE, 521U);
2395     CheckKm1CryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2396     CheckKm2CryptoParam(TAG_EC_CURVE, EcCurve::P_521);
2397 
2398     CheckOrigin();
2399 
2400     string message(32, 'a');
2401     auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2402     string signature = SignMessage(message, params);
2403     VerifyMessage(message, signature, params);
2404 }
2405 
2406 /*
2407  * ImportKeyTest.EcdsaSizeMismatch
2408  *
2409  * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
2410  * correct way.
2411  */
TEST_F(ImportKeyTest,EcdsaSizeMismatch)2412 TEST_F(ImportKeyTest, EcdsaSizeMismatch) {
2413     ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2414               ImportKey(AuthorizationSetBuilder()
2415                             .EcdsaSigningKey(224 /* Doesn't match key */)
2416                             .Digest(Digest::NONE),
2417                         KeyFormat::PKCS8, ec_256_key));
2418 }
2419 
2420 /*
2421  * ImportKeyTest.EcdsaCurveMismatch
2422  *
2423  * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in the
2424  * correct way.
2425  */
TEST_F(ImportKeyTest,EcdsaCurveMismatch)2426 TEST_F(ImportKeyTest, EcdsaCurveMismatch) {
2427     if (SupportsSymmetric() && !SupportsAttestation()) {
2428         // KM1 hardware doesn't know about curves
2429         return;
2430     }
2431 
2432     ASSERT_EQ(
2433         ErrorCode::IMPORT_PARAMETER_MISMATCH,
2434         ImportKey(AuthorizationSetBuilder()
2435                       .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
2436                       .Digest(Digest::NONE),
2437                   KeyFormat::PKCS8, ec_256_key))
2438         << "(Possibly b/36233241)";
2439 }
2440 
2441 /*
2442  * ImportKeyTest.AesSuccess
2443  *
2444  * Verifies that importing and using an AES key works.
2445  */
TEST_F(ImportKeyTest,AesSuccess)2446 TEST_F(ImportKeyTest, AesSuccess) {
2447     string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2448     ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2449                                            .Authorization(TAG_NO_AUTH_REQUIRED)
2450                                            .AesEncryptionKey(key.size() * 8)
2451                                            .EcbMode()
2452                                            .Padding(PaddingMode::PKCS7),
2453                                        KeyFormat::RAW, key));
2454 
2455     CheckKm1CryptoParam(TAG_ALGORITHM, Algorithm::AES);
2456     CheckKm1CryptoParam(TAG_KEY_SIZE, 128U);
2457     CheckKm1CryptoParam(TAG_PADDING, PaddingMode::PKCS7);
2458     CheckKm1CryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
2459     CheckOrigin();
2460 
2461     string message = "Hello World!";
2462     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2463     string ciphertext = EncryptMessage(message, params);
2464     string plaintext = DecryptMessage(ciphertext, params);
2465     EXPECT_EQ(message, plaintext);
2466 }
2467 
2468 /*
2469  * ImportKeyTest.AesSuccess
2470  *
2471  * Verifies that importing and using an HMAC key works.
2472  */
TEST_F(ImportKeyTest,HmacKeySuccess)2473 TEST_F(ImportKeyTest, HmacKeySuccess) {
2474     string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2475     ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2476                                            .Authorization(TAG_NO_AUTH_REQUIRED)
2477                                            .HmacKey(key.size() * 8)
2478                                            .Digest(Digest::SHA_2_256)
2479                                            .Authorization(TAG_MIN_MAC_LENGTH, 256),
2480                                        KeyFormat::RAW, key));
2481 
2482     CheckKm1CryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
2483     CheckKm1CryptoParam(TAG_KEY_SIZE, 128U);
2484     CheckKm1CryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2485     CheckOrigin();
2486 
2487     string message = "Hello World!";
2488     string signature = MacMessage(message, Digest::SHA_2_256, 256);
2489     VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2490 }
2491 
2492 typedef KeymasterHidlTest EncryptionOperationsTest;
2493 
2494 /*
2495  * EncryptionOperationsTest.RsaNoPaddingSuccess
2496  *
2497  * Verifies that raw RSA encryption works.
2498  */
TEST_F(EncryptionOperationsTest,RsaNoPaddingSuccess)2499 TEST_F(EncryptionOperationsTest, RsaNoPaddingSuccess) {
2500     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2501                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2502                                              .RsaEncryptionKey(1024, 3)
2503                                              .Padding(PaddingMode::NONE)));
2504 
2505     string message = string(1024 / 8, 'a');
2506     auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2507     string ciphertext1 = EncryptMessage(message, params);
2508     EXPECT_EQ(1024U / 8, ciphertext1.size());
2509 
2510     string ciphertext2 = EncryptMessage(message, params);
2511     EXPECT_EQ(1024U / 8, ciphertext2.size());
2512 
2513     // Unpadded RSA is deterministic
2514     EXPECT_EQ(ciphertext1, ciphertext2);
2515 }
2516 
2517 /*
2518  * EncryptionOperationsTest.RsaNoPaddingShortMessage
2519  *
2520  * Verifies that raw RSA encryption of short messages works.
2521  */
TEST_F(EncryptionOperationsTest,RsaNoPaddingShortMessage)2522 TEST_F(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
2523     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2524                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2525                                              .RsaEncryptionKey(1024, 3)
2526                                              .Padding(PaddingMode::NONE)));
2527 
2528     string message = "1";
2529     auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2530 
2531     string ciphertext = EncryptMessage(message, params);
2532     EXPECT_EQ(1024U / 8, ciphertext.size());
2533 
2534     string expected_plaintext = string(1024 / 8 - 1, 0) + message;
2535     string plaintext = DecryptMessage(ciphertext, params);
2536 
2537     EXPECT_EQ(expected_plaintext, plaintext);
2538 
2539     // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
2540     message = static_cast<char>(1);
2541     ciphertext = EncryptMessage(message, params);
2542     EXPECT_EQ(1024U / 8, ciphertext.size());
2543     EXPECT_EQ(ciphertext, string(1024 / 8 - 1, 0) + message);
2544 }
2545 
2546 /*
2547  * EncryptionOperationsTest.RsaNoPaddingTooLong
2548  *
2549  * Verifies that raw RSA encryption of too-long messages fails in the expected way.
2550  */
TEST_F(EncryptionOperationsTest,RsaNoPaddingTooLong)2551 TEST_F(EncryptionOperationsTest, RsaNoPaddingTooLong) {
2552     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2553                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2554                                              .RsaEncryptionKey(1024, 3)
2555                                              .Padding(PaddingMode::NONE)));
2556 
2557     string message(1024 / 8 + 1, 'a');
2558 
2559     auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2560     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2561 
2562     string result;
2563     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
2564 }
2565 
2566 /*
2567  * EncryptionOperationsTest.RsaNoPaddingTooLong
2568  *
2569  * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected way.
2570  */
TEST_F(EncryptionOperationsTest,RsaNoPaddingTooLarge)2571 TEST_F(EncryptionOperationsTest, RsaNoPaddingTooLarge) {
2572     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2573                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2574                                              .RsaEncryptionKey(1024, 3)
2575                                              .Padding(PaddingMode::NONE)));
2576 
2577     HidlBuf exported;
2578     ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &exported));
2579 
2580     const uint8_t* p = exported.data();
2581     EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr /* alloc new */, &p, exported.size()));
2582     RSA_Ptr rsa(EVP_PKEY_get1_RSA(pkey.get()));
2583 
2584     size_t modulus_len = BN_num_bytes(rsa->n);
2585     ASSERT_EQ(1024U / 8, modulus_len);
2586     std::unique_ptr<uint8_t[]> modulus_buf(new uint8_t[modulus_len]);
2587     BN_bn2bin(rsa->n, modulus_buf.get());
2588 
2589     // The modulus is too big to encrypt.
2590     string message(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
2591 
2592     auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2593     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2594 
2595     string result;
2596     EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &result));
2597 
2598     // One smaller than the modulus is okay.
2599     BN_sub(rsa->n, rsa->n, BN_value_one());
2600     modulus_len = BN_num_bytes(rsa->n);
2601     ASSERT_EQ(1024U / 8, modulus_len);
2602     BN_bn2bin(rsa->n, modulus_buf.get());
2603     message = string(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
2604     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2605     EXPECT_EQ(ErrorCode::OK, Finish(message, &result));
2606 }
2607 
2608 /*
2609  * EncryptionOperationsTest.RsaOaepSuccess
2610  *
2611  * Verifies that RSA-OAEP encryption operations work, with all digests.
2612  */
TEST_F(EncryptionOperationsTest,RsaOaepSuccess)2613 TEST_F(EncryptionOperationsTest, RsaOaepSuccess) {
2614     auto digests = {Digest::MD5,       Digest::SHA1,      Digest::SHA_2_224,
2615                     Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
2616 
2617     size_t key_size = 2048;  // Need largish key for SHA-512 test.
2618     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2619                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2620                                              .RsaEncryptionKey(key_size, 3)
2621                                              .Padding(PaddingMode::RSA_OAEP)
2622                                              .Digest(digests)));
2623 
2624     string message = "Hello";
2625 
2626     for (auto digest : digests) {
2627         auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
2628         string ciphertext1 = EncryptMessage(message, params);
2629         if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
2630         EXPECT_EQ(key_size / 8, ciphertext1.size());
2631 
2632         string ciphertext2 = EncryptMessage(message, params);
2633         EXPECT_EQ(key_size / 8, ciphertext2.size());
2634 
2635         // OAEP randomizes padding so every result should be different (with astronomically high
2636         // probability).
2637         EXPECT_NE(ciphertext1, ciphertext2);
2638 
2639         string plaintext1 = DecryptMessage(ciphertext1, params);
2640         EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
2641         string plaintext2 = DecryptMessage(ciphertext2, params);
2642         EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
2643 
2644         // Decrypting corrupted ciphertext should fail.
2645         size_t offset_to_corrupt = random() % ciphertext1.size();
2646         char corrupt_byte;
2647         do {
2648             corrupt_byte = static_cast<char>(random() % 256);
2649         } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2650         ciphertext1[offset_to_corrupt] = corrupt_byte;
2651 
2652         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2653         string result;
2654         EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2655         EXPECT_EQ(0U, result.size());
2656     }
2657 }
2658 
2659 /*
2660  * EncryptionOperationsTest.RsaOaepInvalidDigest
2661  *
2662  * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2663  * without a digest.
2664  */
TEST_F(EncryptionOperationsTest,RsaOaepInvalidDigest)2665 TEST_F(EncryptionOperationsTest, RsaOaepInvalidDigest) {
2666     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2667                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2668                                              .RsaEncryptionKey(1024, 3)
2669                                              .Padding(PaddingMode::RSA_OAEP)
2670                                              .Digest(Digest::NONE)));
2671     string message = "Hello World!";
2672 
2673     auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
2674     EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2675 }
2676 
2677 /*
2678  * EncryptionOperationsTest.RsaOaepInvalidDigest
2679  *
2680  * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt with a
2681  * different digest than was used to encrypt.
2682  */
TEST_F(EncryptionOperationsTest,RsaOaepDecryptWithWrongDigest)2683 TEST_F(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
2684     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2685                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2686                                              .RsaEncryptionKey(1024, 3)
2687                                              .Padding(PaddingMode::RSA_OAEP)
2688                                              .Digest(Digest::SHA_2_256, Digest::SHA_2_224)));
2689     string message = "Hello World!";
2690     string ciphertext = EncryptMessage(
2691         message,
2692         AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
2693 
2694     EXPECT_EQ(
2695         ErrorCode::OK,
2696         Begin(KeyPurpose::DECRYPT,
2697               AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP)));
2698     string result;
2699     EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
2700     EXPECT_EQ(0U, result.size());
2701 }
2702 
2703 /*
2704  * EncryptionOperationsTest.RsaOaepTooLarge
2705  *
2706  * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
2707  * too-large message.
2708  */
TEST_F(EncryptionOperationsTest,RsaOaepTooLarge)2709 TEST_F(EncryptionOperationsTest, RsaOaepTooLarge) {
2710     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2711                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2712                                              .RsaEncryptionKey(1024, 3)
2713                                              .Padding(PaddingMode::RSA_OAEP)
2714                                              .Digest(Digest::SHA1)));
2715     constexpr size_t digest_size = 160 /* SHA1 */ / 8;
2716     constexpr size_t oaep_overhead = 2 * digest_size + 2;
2717     string message(1024 / 8 - oaep_overhead + 1, 'a');
2718     EXPECT_EQ(ErrorCode::OK,
2719               Begin(KeyPurpose::ENCRYPT,
2720                     AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::SHA1)));
2721     string result;
2722     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
2723     EXPECT_EQ(0U, result.size());
2724 }
2725 
2726 /*
2727  * EncryptionOperationsTest.RsaPkcs1Success
2728  *
2729  * Verifies that RSA PKCS encryption/decrypts works.
2730  */
TEST_F(EncryptionOperationsTest,RsaPkcs1Success)2731 TEST_F(EncryptionOperationsTest, RsaPkcs1Success) {
2732     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2733                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2734                                              .RsaEncryptionKey(1024, 3)
2735                                              .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)));
2736 
2737     string message = "Hello World!";
2738     auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2739     string ciphertext1 = EncryptMessage(message, params);
2740     EXPECT_EQ(1024U / 8, ciphertext1.size());
2741 
2742     string ciphertext2 = EncryptMessage(message, params);
2743     EXPECT_EQ(1024U / 8, ciphertext2.size());
2744 
2745     // PKCS1 v1.5 randomizes padding so every result should be different.
2746     EXPECT_NE(ciphertext1, ciphertext2);
2747 
2748     string plaintext = DecryptMessage(ciphertext1, params);
2749     EXPECT_EQ(message, plaintext);
2750 
2751     // Decrypting corrupted ciphertext should fail.
2752     size_t offset_to_corrupt = random() % ciphertext1.size();
2753     char corrupt_byte;
2754     do {
2755         corrupt_byte = static_cast<char>(random() % 256);
2756     } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2757     ciphertext1[offset_to_corrupt] = corrupt_byte;
2758 
2759     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2760     string result;
2761     EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2762     EXPECT_EQ(0U, result.size());
2763 }
2764 
2765 /*
2766  * EncryptionOperationsTest.RsaPkcs1TooLarge
2767  *
2768  * Verifies that RSA PKCS encryption fails in the correct way when the mssage is too large.
2769  */
TEST_F(EncryptionOperationsTest,RsaPkcs1TooLarge)2770 TEST_F(EncryptionOperationsTest, RsaPkcs1TooLarge) {
2771     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2772                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2773                                              .RsaEncryptionKey(1024, 3)
2774                                              .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)));
2775     string message(1024 / 8 - 10, 'a');
2776 
2777     auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2778     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2779     string result;
2780     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
2781     EXPECT_EQ(0U, result.size());
2782 }
2783 
2784 /*
2785  * EncryptionOperationsTest.EcdsaEncrypt
2786  *
2787  * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
2788  */
TEST_F(EncryptionOperationsTest,EcdsaEncrypt)2789 TEST_F(EncryptionOperationsTest, EcdsaEncrypt) {
2790     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2791                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2792                                              .EcdsaSigningKey(224)
2793                                              .Digest(Digest::NONE)));
2794     auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
2795     ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params))
2796         << "(Possibly b/33543625)";
2797     ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params))
2798         << "(Possibly b/33543625)";
2799 }
2800 
2801 /*
2802  * EncryptionOperationsTest.HmacEncrypt
2803  *
2804  * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
2805  */
TEST_F(EncryptionOperationsTest,HmacEncrypt)2806 TEST_F(EncryptionOperationsTest, HmacEncrypt) {
2807     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2808                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2809                                              .HmacKey(128)
2810                                              .Digest(Digest::SHA_2_256)
2811                                              .Padding(PaddingMode::NONE)
2812                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2813     auto params = AuthorizationSetBuilder()
2814                       .Digest(Digest::SHA_2_256)
2815                       .Padding(PaddingMode::NONE)
2816                       .Authorization(TAG_MAC_LENGTH, 128);
2817     ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params))
2818         << "(Possibly b/33543625)";
2819     ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params))
2820         << "(Possibly b/33543625)";
2821 }
2822 
2823 /*
2824  * EncryptionOperationsTest.AesEcbRoundTripSuccess
2825  *
2826  * Verifies that AES ECB mode works.
2827  */
TEST_F(EncryptionOperationsTest,AesEcbRoundTripSuccess)2828 TEST_F(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
2829     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2830                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2831                                              .AesEncryptionKey(128)
2832                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2833                                              .Padding(PaddingMode::NONE)));
2834 
2835     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2836 
2837     // Two-block message.
2838     string message = "12345678901234567890123456789012";
2839     string ciphertext1 = EncryptMessage(message, params);
2840     EXPECT_EQ(message.size(), ciphertext1.size());
2841 
2842     string ciphertext2 = EncryptMessage(string(message), params);
2843     EXPECT_EQ(message.size(), ciphertext2.size());
2844 
2845     // ECB is deterministic.
2846     EXPECT_EQ(ciphertext1, ciphertext2);
2847 
2848     string plaintext = DecryptMessage(ciphertext1, params);
2849     EXPECT_EQ(message, plaintext);
2850 }
2851 
2852 /*
2853  * EncryptionOperationsTest.AesEcbRoundTripSuccess
2854  *
2855  * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
2856  */
TEST_F(EncryptionOperationsTest,AesWrongMode)2857 TEST_F(EncryptionOperationsTest, AesWrongMode) {
2858     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2859                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2860                                              .AesEncryptionKey(128)
2861                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
2862                                              .Padding(PaddingMode::NONE)));
2863     // Two-block message.
2864     string message = "12345678901234567890123456789012";
2865     EXPECT_EQ(
2866         ErrorCode::INCOMPATIBLE_BLOCK_MODE,
2867         Begin(KeyPurpose::ENCRYPT,
2868               AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
2869 }
2870 
2871 /*
2872  * EncryptionOperationsTest.AesEcbNoPaddingWrongInputSize
2873  *
2874  * Verifies that AES encryption fails in the correct way when provided an input that is not a
2875  * multiple of the block size and no padding is specified.
2876  */
TEST_F(EncryptionOperationsTest,AesEcbNoPaddingWrongInputSize)2877 TEST_F(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
2878     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2879                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2880                                              .AesEncryptionKey(128)
2881                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2882                                              .Padding(PaddingMode::NONE)));
2883     // Message is slightly shorter than two blocks.
2884     string message(16 * 2 - 1, 'a');
2885 
2886     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2887     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2888     string ciphertext;
2889     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
2890     EXPECT_EQ(0U, ciphertext.size());
2891 }
2892 
2893 /*
2894  * EncryptionOperationsTest.AesEcbPkcs7Padding
2895  *
2896  * Verifies that AES PKCS7 padding works for any message length.
2897  */
TEST_F(EncryptionOperationsTest,AesEcbPkcs7Padding)2898 TEST_F(EncryptionOperationsTest, AesEcbPkcs7Padding) {
2899     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2900                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2901                                              .AesEncryptionKey(128)
2902                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2903                                              .Padding(PaddingMode::PKCS7)));
2904 
2905     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2906 
2907     // Try various message lengths; all should work.
2908     for (size_t i = 0; i < 32; ++i) {
2909         string message(i, 'a');
2910         string ciphertext = EncryptMessage(message, params);
2911         EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2912         string plaintext = DecryptMessage(ciphertext, params);
2913         EXPECT_EQ(message, plaintext);
2914     }
2915 }
2916 
2917 /*
2918  * EncryptionOperationsTest.AesEcbWrongPadding
2919  *
2920  * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
2921  * specified.
2922  */
TEST_F(EncryptionOperationsTest,AesEcbWrongPadding)2923 TEST_F(EncryptionOperationsTest, AesEcbWrongPadding) {
2924     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2925                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2926                                              .AesEncryptionKey(128)
2927                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2928                                              .Padding(PaddingMode::NONE)));
2929 
2930     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2931 
2932     // Try various message lengths; all should fail
2933     for (size_t i = 0; i < 32; ++i) {
2934         string message(i, 'a');
2935         EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
2936     }
2937 }
2938 
2939 /*
2940  * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
2941  *
2942  * Verifies that AES decryption fails in the correct way when the padding is corrupted.
2943  */
TEST_F(EncryptionOperationsTest,AesEcbPkcs7PaddingCorrupted)2944 TEST_F(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
2945     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2946                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2947                                              .AesEncryptionKey(128)
2948                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2949                                              .Padding(PaddingMode::PKCS7)));
2950 
2951     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2952 
2953     string message = "a";
2954     string ciphertext = EncryptMessage(message, params);
2955     EXPECT_EQ(16U, ciphertext.size());
2956     EXPECT_NE(ciphertext, message);
2957     ++ciphertext[ciphertext.size() / 2];
2958 
2959     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2960     string plaintext;
2961     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
2962 }
2963 
CopyIv(const AuthorizationSet & set)2964 HidlBuf CopyIv(const AuthorizationSet& set) {
2965     auto iv = set.GetTagValue(TAG_NONCE);
2966     EXPECT_TRUE(iv.isOk());
2967     return iv.value();
2968 }
2969 
2970 /*
2971  * EncryptionOperationsTest.AesCtrRoundTripSuccess
2972  *
2973  * Verifies that AES CTR mode works.
2974  */
TEST_F(EncryptionOperationsTest,AesCtrRoundTripSuccess)2975 TEST_F(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
2976     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2977                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2978                                              .AesEncryptionKey(128)
2979                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
2980                                              .Padding(PaddingMode::NONE)));
2981 
2982     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
2983 
2984     string message = "123";
2985     AuthorizationSet out_params;
2986     string ciphertext1 = EncryptMessage(message, params, &out_params);
2987     HidlBuf iv1 = CopyIv(out_params);
2988     EXPECT_EQ(16U, iv1.size());
2989 
2990     EXPECT_EQ(message.size(), ciphertext1.size());
2991 
2992     out_params.Clear();
2993     string ciphertext2 = EncryptMessage(message, params, &out_params);
2994     HidlBuf iv2 = CopyIv(out_params);
2995     EXPECT_EQ(16U, iv2.size());
2996 
2997     // IVs should be random, so ciphertexts should differ.
2998     EXPECT_NE(ciphertext1, ciphertext2);
2999 
3000     auto params_iv1 =
3001         AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
3002     auto params_iv2 =
3003         AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
3004 
3005     string plaintext = DecryptMessage(ciphertext1, params_iv1);
3006     EXPECT_EQ(message, plaintext);
3007     plaintext = DecryptMessage(ciphertext2, params_iv2);
3008     EXPECT_EQ(message, plaintext);
3009 
3010     // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
3011     plaintext = DecryptMessage(ciphertext1, params_iv2);
3012     EXPECT_NE(message, plaintext);
3013     plaintext = DecryptMessage(ciphertext2, params_iv1);
3014     EXPECT_NE(message, plaintext);
3015 }
3016 
3017 /*
3018  * EncryptionOperationsTest.AesIncremental
3019  *
3020  * Verifies that AES works, all modes, when provided data in various size increments.
3021  */
TEST_F(EncryptionOperationsTest,AesIncremental)3022 TEST_F(EncryptionOperationsTest, AesIncremental) {
3023     auto block_modes = {
3024         BlockMode::ECB, BlockMode::CBC, BlockMode::CTR, BlockMode::GCM,
3025     };
3026 
3027     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3028                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3029                                              .AesEncryptionKey(128)
3030                                              .BlockMode(block_modes)
3031                                              .Padding(PaddingMode::NONE)
3032                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3033 
3034     for (int increment = 1; increment <= 240; ++increment) {
3035         for (auto block_mode : block_modes) {
3036             string message(240, 'a');
3037             auto params = AuthorizationSetBuilder()
3038                               .BlockMode(block_mode)
3039                               .Padding(PaddingMode::NONE)
3040                               .Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
3041 
3042             AuthorizationSet output_params;
3043             EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
3044 
3045             string ciphertext;
3046             size_t input_consumed;
3047             string to_send;
3048             for (size_t i = 0; i < message.size(); i += increment) {
3049                 to_send.append(message.substr(i, increment));
3050                 EXPECT_EQ(ErrorCode::OK, Update(to_send, &ciphertext, &input_consumed));
3051                 to_send = to_send.substr(input_consumed);
3052 
3053                 switch (block_mode) {
3054                 case BlockMode::ECB:
3055                 case BlockMode::CBC:
3056                     // Implementations must take as many blocks as possible, leaving less than
3057                     // a block.
3058                     EXPECT_LE(to_send.length(), 16U);
3059                     break;
3060                 case BlockMode::GCM:
3061                 case BlockMode::CTR:
3062                     // Implementations must always take all the data.
3063                     EXPECT_EQ(0U, to_send.length());
3064                     break;
3065                 }
3066             }
3067             EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext)) << "Error sending " << to_send;
3068 
3069             switch (block_mode) {
3070             case BlockMode::GCM:
3071                 EXPECT_EQ(message.size() + 16, ciphertext.size());
3072                 break;
3073             case BlockMode::CTR:
3074                 EXPECT_EQ(message.size(), ciphertext.size());
3075                 break;
3076             case BlockMode::CBC:
3077             case BlockMode::ECB:
3078                 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
3079                 break;
3080             }
3081 
3082             auto iv = output_params.GetTagValue(TAG_NONCE);
3083             switch (block_mode) {
3084             case BlockMode::CBC:
3085             case BlockMode::GCM:
3086             case BlockMode::CTR:
3087                 ASSERT_TRUE(iv.isOk()) << "No IV for block mode " << block_mode;
3088                 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv.value().size());
3089                 params.push_back(TAG_NONCE, iv.value());
3090                 break;
3091 
3092             case BlockMode::ECB:
3093                 EXPECT_FALSE(iv.isOk()) << "ECB mode should not generate IV";
3094                 break;
3095             }
3096 
3097             EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
3098                 << "Decrypt begin() failed for block mode " << block_mode;
3099 
3100             string plaintext;
3101             for (size_t i = 0; i < ciphertext.size(); i += increment) {
3102                 to_send.append(ciphertext.substr(i, increment));
3103                 EXPECT_EQ(ErrorCode::OK, Update(to_send, &plaintext, &input_consumed));
3104                 to_send = to_send.substr(input_consumed);
3105             }
3106             ErrorCode error = Finish(to_send, &plaintext);
3107             ASSERT_EQ(ErrorCode::OK, error)
3108                 << "Decryption failed for block mode " << block_mode << " and increment "
3109                 << increment << " (Possibly b/33584622)";
3110             if (error == ErrorCode::OK) {
3111                 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
3112                                               << block_mode << " and increment " << increment;
3113             }
3114         }
3115     }
3116 }
3117 
3118 struct AesCtrSp80038aTestVector {
3119     const char* key;
3120     const char* nonce;
3121     const char* plaintext;
3122     const char* ciphertext;
3123 };
3124 
3125 // These test vectors are taken from
3126 // http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
3127 static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
3128     // AES-128
3129     {
3130         "2b7e151628aed2a6abf7158809cf4f3c", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3131         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3132         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3133         "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
3134         "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
3135     },
3136     // AES-192
3137     {
3138         "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3139         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3140         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3141         "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
3142         "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
3143     },
3144     // AES-256
3145     {
3146         "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
3147         "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3148         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3149         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3150         "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
3151         "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
3152     },
3153 };
3154 
3155 /*
3156  * EncryptionOperationsTest.AesCtrSp80038aTestVector
3157  *
3158  * Verifies AES CTR implementation against SP800-38A test vectors.
3159  */
TEST_F(EncryptionOperationsTest,AesCtrSp80038aTestVector)3160 TEST_F(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
3161     for (size_t i = 0; i < 3; i++) {
3162         const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
3163         const string key = hex2str(test.key);
3164         const string nonce = hex2str(test.nonce);
3165         const string plaintext = hex2str(test.plaintext);
3166         const string ciphertext = hex2str(test.ciphertext);
3167         CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
3168     }
3169 }
3170 
3171 /*
3172  * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
3173  *
3174  * Verifies that keymaster rejects use of CTR mode with PKCS7 padding in the correct way.
3175  */
TEST_F(EncryptionOperationsTest,AesCtrIncompatiblePaddingMode)3176 TEST_F(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
3177     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3178                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3179                                              .AesEncryptionKey(128)
3180                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3181                                              .Padding(PaddingMode::PKCS7)));
3182     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3183     EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3184 }
3185 
3186 /*
3187  * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3188  *
3189  * Verifies that keymaster fails correctly when the user supplies an incorrect-size nonce.
3190  */
TEST_F(EncryptionOperationsTest,AesCtrInvalidCallerNonce)3191 TEST_F(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
3192     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3193                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3194                                              .AesEncryptionKey(128)
3195                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3196                                              .Authorization(TAG_CALLER_NONCE)
3197                                              .Padding(PaddingMode::NONE)));
3198 
3199     auto params = AuthorizationSetBuilder()
3200                       .BlockMode(BlockMode::CTR)
3201                       .Padding(PaddingMode::NONE)
3202                       .Authorization(TAG_NONCE, HidlBuf(string(1, 'a')));
3203     EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3204 
3205     params = AuthorizationSetBuilder()
3206                  .BlockMode(BlockMode::CTR)
3207                  .Padding(PaddingMode::NONE)
3208                  .Authorization(TAG_NONCE, HidlBuf(string(15, 'a')));
3209     EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3210 
3211     params = AuthorizationSetBuilder()
3212                  .BlockMode(BlockMode::CTR)
3213                  .Padding(PaddingMode::NONE)
3214                  .Authorization(TAG_NONCE, HidlBuf(string(17, 'a')));
3215     EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3216 }
3217 
3218 /*
3219  * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3220  *
3221  * Verifies that keymaster fails correctly when the user supplies an incorrect-size nonce.
3222  */
TEST_F(EncryptionOperationsTest,AesCbcRoundTripSuccess)3223 TEST_F(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
3224     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3225                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3226                                              .AesEncryptionKey(128)
3227                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3228                                              .Padding(PaddingMode::NONE)));
3229     // Two-block message.
3230     string message = "12345678901234567890123456789012";
3231     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3232     AuthorizationSet out_params;
3233     string ciphertext1 = EncryptMessage(message, params, &out_params);
3234     HidlBuf iv1 = CopyIv(out_params);
3235     EXPECT_EQ(message.size(), ciphertext1.size());
3236 
3237     out_params.Clear();
3238 
3239     string ciphertext2 = EncryptMessage(message, params, &out_params);
3240     HidlBuf iv2 = CopyIv(out_params);
3241     EXPECT_EQ(message.size(), ciphertext2.size());
3242 
3243     // IVs should be random, so ciphertexts should differ.
3244     EXPECT_NE(ciphertext1, ciphertext2);
3245 
3246     params.push_back(TAG_NONCE, iv1);
3247     string plaintext = DecryptMessage(ciphertext1, params);
3248     EXPECT_EQ(message, plaintext);
3249 }
3250 
3251 /*
3252  * EncryptionOperationsTest.AesCallerNonce
3253  *
3254  * Verifies that AES caller-provided nonces work correctly.
3255  */
TEST_F(EncryptionOperationsTest,AesCallerNonce)3256 TEST_F(EncryptionOperationsTest, AesCallerNonce) {
3257     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3258                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3259                                              .AesEncryptionKey(128)
3260                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3261                                              .Authorization(TAG_CALLER_NONCE)
3262                                              .Padding(PaddingMode::NONE)));
3263 
3264     string message = "12345678901234567890123456789012";
3265 
3266     // Don't specify nonce, should get a random one.
3267     AuthorizationSetBuilder params =
3268         AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3269     AuthorizationSet out_params;
3270     string ciphertext = EncryptMessage(message, params, &out_params);
3271     EXPECT_EQ(message.size(), ciphertext.size());
3272     EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE).value().size());
3273 
3274     params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE).value());
3275     string plaintext = DecryptMessage(ciphertext, params);
3276     EXPECT_EQ(message, plaintext);
3277 
3278     // Now specify a nonce, should also work.
3279     params = AuthorizationSetBuilder()
3280                  .BlockMode(BlockMode::CBC)
3281                  .Padding(PaddingMode::NONE)
3282                  .Authorization(TAG_NONCE, HidlBuf("abcdefghijklmnop"));
3283     out_params.Clear();
3284     ciphertext = EncryptMessage(message, params, &out_params);
3285 
3286     // Decrypt with correct nonce.
3287     plaintext = DecryptMessage(ciphertext, params);
3288     EXPECT_EQ(message, plaintext);
3289 
3290     // Try with wrong nonce.
3291     params = AuthorizationSetBuilder()
3292                  .BlockMode(BlockMode::CBC)
3293                  .Padding(PaddingMode::NONE)
3294                  .Authorization(TAG_NONCE, HidlBuf("aaaaaaaaaaaaaaaa"));
3295     plaintext = DecryptMessage(ciphertext, params);
3296     EXPECT_NE(message, plaintext);
3297 }
3298 
3299 /*
3300  * EncryptionOperationsTest.AesCallerNonceProhibited
3301  *
3302  * Verifies that caller-provided nonces are not permitted when not specified in the key
3303  * authorizations.
3304  */
TEST_F(EncryptionOperationsTest,AesCallerNonceProhibited)3305 TEST_F(EncryptionOperationsTest, AesCallerNonceProhibited) {
3306     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3307                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3308                                              .AesEncryptionKey(128)
3309                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3310                                              .Padding(PaddingMode::NONE)));
3311 
3312     string message = "12345678901234567890123456789012";
3313 
3314     // Don't specify nonce, should get a random one.
3315     AuthorizationSetBuilder params =
3316         AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3317     AuthorizationSet out_params;
3318     string ciphertext = EncryptMessage(message, params, &out_params);
3319     EXPECT_EQ(message.size(), ciphertext.size());
3320     EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE).value().size());
3321 
3322     params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE).value());
3323     string plaintext = DecryptMessage(ciphertext, params);
3324     EXPECT_EQ(message, plaintext);
3325 
3326     // Now specify a nonce, should fail
3327     params = AuthorizationSetBuilder()
3328                  .BlockMode(BlockMode::CBC)
3329                  .Padding(PaddingMode::NONE)
3330                  .Authorization(TAG_NONCE, HidlBuf("abcdefghijklmnop"));
3331     out_params.Clear();
3332     EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
3333 }
3334 
3335 /*
3336  * EncryptionOperationsTest.AesGcmRoundTripSuccess
3337  *
3338  * Verifies that AES GCM mode works.
3339  */
TEST_F(EncryptionOperationsTest,AesGcmRoundTripSuccess)3340 TEST_F(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
3341     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3342                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3343                                              .AesEncryptionKey(128)
3344                                              .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3345                                              .Padding(PaddingMode::NONE)
3346                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3347 
3348     string aad = "foobar";
3349     string message = "123456789012345678901234567890123456";
3350 
3351     auto begin_params = AuthorizationSetBuilder()
3352                             .BlockMode(BlockMode::GCM)
3353                             .Padding(PaddingMode::NONE)
3354                             .Authorization(TAG_MAC_LENGTH, 128);
3355 
3356     auto update_params =
3357         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3358 
3359     // Encrypt
3360     AuthorizationSet begin_out_params;
3361     ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
3362         << "Begin encrypt";
3363     string ciphertext;
3364     AuthorizationSet update_out_params;
3365     ASSERT_EQ(ErrorCode::OK,
3366               Finish(op_handle_, update_params, message, "", &update_out_params, &ciphertext));
3367 
3368     // Grab nonce
3369     begin_params.push_back(begin_out_params);
3370 
3371     // Decrypt.
3372     ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
3373     string plaintext;
3374     size_t input_consumed;
3375     ASSERT_EQ(ErrorCode::OK, Update(op_handle_, update_params, ciphertext, &update_out_params,
3376                                     &plaintext, &input_consumed));
3377     EXPECT_EQ(ciphertext.size(), input_consumed);
3378     EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
3379 
3380     EXPECT_EQ(message, plaintext);
3381 }
3382 
3383 /*
3384  * EncryptionOperationsTest.AesGcmTooShortTag
3385  *
3386  * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
3387  */
TEST_F(EncryptionOperationsTest,AesGcmTooShortTag)3388 TEST_F(EncryptionOperationsTest, AesGcmTooShortTag) {
3389     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3390                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3391                                              .AesEncryptionKey(128)
3392                                              .BlockMode(BlockMode::GCM)
3393                                              .Padding(PaddingMode::NONE)
3394                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3395     string message = "123456789012345678901234567890123456";
3396     auto params = AuthorizationSetBuilder()
3397                       .BlockMode(BlockMode::GCM)
3398                       .Padding(PaddingMode::NONE)
3399                       .Authorization(TAG_MAC_LENGTH, 96);
3400 
3401     EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
3402 }
3403 
3404 /*
3405  * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
3406  *
3407  * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
3408  */
TEST_F(EncryptionOperationsTest,AesGcmTooShortTagOnDecrypt)3409 TEST_F(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
3410     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3411                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3412                                              .AesEncryptionKey(128)
3413                                              .BlockMode(BlockMode::GCM)
3414                                              .Padding(PaddingMode::NONE)
3415                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3416     string aad = "foobar";
3417     string message = "123456789012345678901234567890123456";
3418     auto params = AuthorizationSetBuilder()
3419                       .BlockMode(BlockMode::GCM)
3420                       .Padding(PaddingMode::NONE)
3421                       .Authorization(TAG_MAC_LENGTH, 128);
3422 
3423     auto finish_params =
3424         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3425 
3426     // Encrypt
3427     AuthorizationSet begin_out_params;
3428     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3429     EXPECT_EQ(1U, begin_out_params.size());
3430     ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE).isOk());
3431 
3432     AuthorizationSet finish_out_params;
3433     string ciphertext;
3434     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3435                                     &finish_out_params, &ciphertext));
3436 
3437     params = AuthorizationSetBuilder()
3438                  .Authorizations(begin_out_params)
3439                  .BlockMode(BlockMode::GCM)
3440                  .Padding(PaddingMode::NONE)
3441                  .Authorization(TAG_MAC_LENGTH, 96);
3442 
3443     // Decrypt.
3444     EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
3445 }
3446 
3447 /*
3448  * EncryptionOperationsTest.AesGcmCorruptKey
3449  *
3450  * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
3451  */
TEST_F(EncryptionOperationsTest,AesGcmCorruptKey)3452 TEST_F(EncryptionOperationsTest, AesGcmCorruptKey) {
3453     const uint8_t nonce_bytes[] = {
3454         0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
3455     };
3456     string nonce = make_string(nonce_bytes);
3457     const uint8_t ciphertext_bytes[] = {
3458         0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc, 0xd2, 0xcb, 0x16,
3459         0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78, 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a,
3460         0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d, 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76,
3461         0x76, 0x5e, 0xfb, 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
3462         0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
3463     };
3464     string ciphertext = make_string(ciphertext_bytes);
3465 
3466     auto params = AuthorizationSetBuilder()
3467                       .BlockMode(BlockMode::GCM)
3468                       .Padding(PaddingMode::NONE)
3469                       .Authorization(TAG_MAC_LENGTH, 128)
3470                       .Authorization(TAG_NONCE, nonce.data(), nonce.size());
3471 
3472     auto import_params = AuthorizationSetBuilder()
3473                              .Authorization(TAG_NO_AUTH_REQUIRED)
3474                              .AesEncryptionKey(128)
3475                              .BlockMode(BlockMode::GCM)
3476                              .Padding(PaddingMode::NONE)
3477                              .Authorization(TAG_CALLER_NONCE)
3478                              .Authorization(TAG_MIN_MAC_LENGTH, 128);
3479 
3480     // Import correct key and decrypt
3481     const uint8_t key_bytes[] = {
3482         0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
3483         0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
3484     };
3485     string key = make_string(key_bytes);
3486     ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3487     string plaintext = DecryptMessage(ciphertext, params);
3488     CheckedDeleteKey();
3489 
3490     // Corrupt key and attempt to decrypt
3491     key[0] = 0;
3492     ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3493     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3494     EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
3495     CheckedDeleteKey();
3496 }
3497 
3498 /*
3499  * EncryptionOperationsTest.AesGcmAadNoData
3500  *
3501  * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
3502  * encrypt.
3503  */
TEST_F(EncryptionOperationsTest,AesGcmAadNoData)3504 TEST_F(EncryptionOperationsTest, AesGcmAadNoData) {
3505     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3506                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3507                                              .AesEncryptionKey(128)
3508                                              .BlockMode(BlockMode::GCM)
3509                                              .Padding(PaddingMode::NONE)
3510                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3511 
3512     string aad = "1234567890123456";
3513     auto params = AuthorizationSetBuilder()
3514                       .BlockMode(BlockMode::GCM)
3515                       .Padding(PaddingMode::NONE)
3516                       .Authorization(TAG_MAC_LENGTH, 128);
3517 
3518     auto finish_params =
3519         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3520 
3521     // Encrypt
3522     AuthorizationSet begin_out_params;
3523     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3524     string ciphertext;
3525     AuthorizationSet finish_out_params;
3526     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, "" /* input */, "" /* signature */,
3527                                     &finish_out_params, &ciphertext));
3528     EXPECT_TRUE(finish_out_params.empty());
3529 
3530     // Grab nonce
3531     params.push_back(begin_out_params);
3532 
3533     // Decrypt.
3534     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3535     string plaintext;
3536     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, ciphertext, "" /* signature */,
3537                                     &finish_out_params, &plaintext))
3538         << "(Possibly b/33615032)";
3539 
3540     EXPECT_TRUE(finish_out_params.empty());
3541 
3542     EXPECT_EQ("", plaintext);
3543 }
3544 
3545 /*
3546  * EncryptionOperationsTest.AesGcmMultiPartAad
3547  *
3548  * Verifies that AES GCM mode works when provided additional authenticated data in multiple chunks.
3549  */
TEST_F(EncryptionOperationsTest,AesGcmMultiPartAad)3550 TEST_F(EncryptionOperationsTest, AesGcmMultiPartAad) {
3551     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3552                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3553                                              .AesEncryptionKey(128)
3554                                              .BlockMode(BlockMode::GCM)
3555                                              .Padding(PaddingMode::NONE)
3556                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3557 
3558     string message = "123456789012345678901234567890123456";
3559     auto begin_params = AuthorizationSetBuilder()
3560                             .BlockMode(BlockMode::GCM)
3561                             .Padding(PaddingMode::NONE)
3562                             .Authorization(TAG_MAC_LENGTH, 128);
3563     AuthorizationSet begin_out_params;
3564 
3565     auto update_params =
3566         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3);
3567 
3568     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3569 
3570     // No data, AAD only.
3571     string ciphertext;
3572     size_t input_consumed;
3573     AuthorizationSet update_out_params;
3574     EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, "" /* input */, &update_out_params,
3575                                     &ciphertext, &input_consumed));
3576     EXPECT_EQ(0U, input_consumed);
3577     EXPECT_EQ(0U, ciphertext.size());
3578     EXPECT_TRUE(update_out_params.empty());
3579 
3580     // AAD and data.
3581     EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, message, &update_out_params,
3582                                     &ciphertext, &input_consumed));
3583     EXPECT_EQ(message.size(), input_consumed);
3584     EXPECT_EQ(message.size(), ciphertext.size());
3585     EXPECT_TRUE(update_out_params.empty());
3586 
3587     EXPECT_EQ(ErrorCode::OK, Finish("" /* input */, &ciphertext));
3588 
3589     // Grab nonce.
3590     begin_params.push_back(begin_out_params);
3591 
3592     // Decrypt
3593     update_params =
3594         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foofoo", (size_t)6);
3595 
3596     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
3597     string plaintext;
3598     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, update_params, ciphertext, "" /* signature */,
3599                                     &update_out_params, &plaintext));
3600     EXPECT_TRUE(update_out_params.empty());
3601     EXPECT_EQ(message, plaintext);
3602 }
3603 
3604 /*
3605  * EncryptionOperationsTest.AesGcmAadOutOfOrder
3606  *
3607  * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
3608  */
TEST_F(EncryptionOperationsTest,AesGcmAadOutOfOrder)3609 TEST_F(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
3610     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3611                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3612                                              .AesEncryptionKey(128)
3613                                              .BlockMode(BlockMode::GCM)
3614                                              .Padding(PaddingMode::NONE)
3615                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3616 
3617     string message = "123456789012345678901234567890123456";
3618     auto begin_params = AuthorizationSetBuilder()
3619                             .BlockMode(BlockMode::GCM)
3620                             .Padding(PaddingMode::NONE)
3621                             .Authorization(TAG_MAC_LENGTH, 128);
3622     AuthorizationSet begin_out_params;
3623 
3624     auto update_params =
3625         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3);
3626 
3627     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3628 
3629     // No data, AAD only.
3630     string ciphertext;
3631     size_t input_consumed;
3632     AuthorizationSet update_out_params;
3633     EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, "" /* input */, &update_out_params,
3634                                     &ciphertext, &input_consumed));
3635     EXPECT_EQ(0U, input_consumed);
3636     EXPECT_EQ(0U, ciphertext.size());
3637     EXPECT_TRUE(update_out_params.empty());
3638 
3639     // AAD and data.
3640     EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, message, &update_out_params,
3641                                     &ciphertext, &input_consumed));
3642     EXPECT_EQ(message.size(), input_consumed);
3643     EXPECT_EQ(message.size(), ciphertext.size());
3644     EXPECT_TRUE(update_out_params.empty());
3645 
3646     // More AAD
3647     EXPECT_EQ(ErrorCode::INVALID_TAG, Update(op_handle_, update_params, "", &update_out_params,
3648                                              &ciphertext, &input_consumed));
3649 
3650     op_handle_ = kOpHandleSentinel;
3651 }
3652 
3653 /*
3654  * EncryptionOperationsTest.AesGcmBadAad
3655  *
3656  * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
3657  */
TEST_F(EncryptionOperationsTest,AesGcmBadAad)3658 TEST_F(EncryptionOperationsTest, AesGcmBadAad) {
3659     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3660                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3661                                              .AesEncryptionKey(128)
3662                                              .BlockMode(BlockMode::GCM)
3663                                              .Padding(PaddingMode::NONE)
3664                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3665 
3666     string message = "12345678901234567890123456789012";
3667     auto begin_params = AuthorizationSetBuilder()
3668                             .BlockMode(BlockMode::GCM)
3669                             .Padding(PaddingMode::NONE)
3670                             .Authorization(TAG_MAC_LENGTH, 128);
3671 
3672     auto finish_params =
3673         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6);
3674 
3675     // Encrypt
3676     AuthorizationSet begin_out_params;
3677     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3678     string ciphertext;
3679     AuthorizationSet finish_out_params;
3680     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3681                                     &finish_out_params, &ciphertext));
3682 
3683     // Grab nonce
3684     begin_params.push_back(begin_out_params);
3685 
3686     finish_params = AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA,
3687                                                             "barfoo" /* Wrong AAD */, (size_t)6);
3688 
3689     // Decrypt.
3690     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
3691     string plaintext;
3692     EXPECT_EQ(ErrorCode::VERIFICATION_FAILED,
3693               Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params,
3694                      &plaintext));
3695 }
3696 
3697 /*
3698  * EncryptionOperationsTest.AesGcmWrongNonce
3699  *
3700  * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
3701  */
TEST_F(EncryptionOperationsTest,AesGcmWrongNonce)3702 TEST_F(EncryptionOperationsTest, AesGcmWrongNonce) {
3703     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3704                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3705                                              .AesEncryptionKey(128)
3706                                              .BlockMode(BlockMode::GCM)
3707                                              .Padding(PaddingMode::NONE)
3708                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3709 
3710     string message = "12345678901234567890123456789012";
3711     auto begin_params = AuthorizationSetBuilder()
3712                             .BlockMode(BlockMode::GCM)
3713                             .Padding(PaddingMode::NONE)
3714                             .Authorization(TAG_MAC_LENGTH, 128);
3715 
3716     auto finish_params =
3717         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6);
3718 
3719     // Encrypt
3720     AuthorizationSet begin_out_params;
3721     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3722     string ciphertext;
3723     AuthorizationSet finish_out_params;
3724     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3725                                     &finish_out_params, &ciphertext));
3726 
3727     // Wrong nonce
3728     begin_params.push_back(TAG_NONCE, HidlBuf("123456789012"));
3729 
3730     // Decrypt.
3731     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
3732     string plaintext;
3733     EXPECT_EQ(ErrorCode::VERIFICATION_FAILED,
3734               Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params,
3735                      &plaintext));
3736 
3737     // With wrong nonce, should have gotten garbage plaintext (or none).
3738     EXPECT_NE(message, plaintext);
3739 }
3740 
3741 /*
3742  * EncryptionOperationsTest.AesGcmCorruptTag
3743  *
3744  * Verifies that AES GCM decryption fails correctly when the tag is wrong.
3745  */
TEST_F(EncryptionOperationsTest,AesGcmCorruptTag)3746 TEST_F(EncryptionOperationsTest, AesGcmCorruptTag) {
3747     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3748                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3749                                              .AesEncryptionKey(128)
3750                                              .BlockMode(BlockMode::GCM)
3751                                              .Padding(PaddingMode::NONE)
3752                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3753 
3754     string aad = "1234567890123456";
3755     string message = "123456789012345678901234567890123456";
3756 
3757     auto params = AuthorizationSetBuilder()
3758                       .BlockMode(BlockMode::GCM)
3759                       .Padding(PaddingMode::NONE)
3760                       .Authorization(TAG_MAC_LENGTH, 128);
3761 
3762     auto finish_params =
3763         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3764 
3765     // Encrypt
3766     AuthorizationSet begin_out_params;
3767     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3768     string ciphertext;
3769     AuthorizationSet finish_out_params;
3770     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3771                                     &finish_out_params, &ciphertext));
3772     EXPECT_TRUE(finish_out_params.empty());
3773 
3774     // Corrupt tag
3775     ++(*ciphertext.rbegin());
3776 
3777     // Grab nonce
3778     params.push_back(begin_out_params);
3779 
3780     // Decrypt.
3781     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3782     string plaintext;
3783     EXPECT_EQ(ErrorCode::VERIFICATION_FAILED,
3784               Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params,
3785                      &plaintext));
3786     EXPECT_TRUE(finish_out_params.empty());
3787 }
3788 
3789 typedef KeymasterHidlTest MaxOperationsTest;
3790 
3791 /*
3792  * MaxOperationsTest.TestLimitAes
3793  *
3794  * Verifies that the max uses per boot tag works correctly with AES keys.
3795  */
TEST_F(MaxOperationsTest,TestLimitAes)3796 TEST_F(MaxOperationsTest, TestLimitAes) {
3797     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3798                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3799                                              .AesEncryptionKey(128)
3800                                              .EcbMode()
3801                                              .Padding(PaddingMode::NONE)
3802                                              .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3803 
3804     string message = "1234567890123456";
3805 
3806     auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
3807 
3808     EncryptMessage(message, params);
3809     EncryptMessage(message, params);
3810     EncryptMessage(message, params);
3811 
3812     // Fourth time should fail.
3813     EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
3814 }
3815 
3816 /*
3817  * MaxOperationsTest.TestLimitAes
3818  *
3819  * Verifies that the max uses per boot tag works correctly with RSA keys.
3820  */
TEST_F(MaxOperationsTest,TestLimitRsa)3821 TEST_F(MaxOperationsTest, TestLimitRsa) {
3822     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3823                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3824                                              .RsaSigningKey(1024, 3)
3825                                              .NoDigestOrPadding()
3826                                              .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3827 
3828     string message = "1234567890123456";
3829 
3830     auto params = AuthorizationSetBuilder().NoDigestOrPadding();
3831 
3832     SignMessage(message, params);
3833     SignMessage(message, params);
3834     SignMessage(message, params);
3835 
3836     // Fourth time should fail.
3837     EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
3838 }
3839 
3840 typedef KeymasterHidlTest AddEntropyTest;
3841 
3842 /*
3843  * AddEntropyTest.AddEntropy
3844  *
3845  * Verifies that the addRngEntropy method doesn't blow up.  There's no way to test that entropy is
3846  * actually added.
3847  */
TEST_F(AddEntropyTest,AddEntropy)3848 TEST_F(AddEntropyTest, AddEntropy) {
3849     EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf("foo")));
3850 }
3851 
3852 /*
3853  * AddEntropyTest.AddEmptyEntropy
3854  *
3855  * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
3856  */
TEST_F(AddEntropyTest,AddEmptyEntropy)3857 TEST_F(AddEntropyTest, AddEmptyEntropy) {
3858     EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf()));
3859 }
3860 
3861 /*
3862  * AddEntropyTest.AddLargeEntropy
3863  *
3864  * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
3865  */
TEST_F(AddEntropyTest,AddLargeEntropy)3866 TEST_F(AddEntropyTest, AddLargeEntropy) {
3867     EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf(string(16 * 1024, 'a'))));
3868 }
3869 
3870 typedef KeymasterHidlTest AttestationTest;
3871 
3872 /*
3873  * AttestationTest.RsaAttestation
3874  *
3875  * Verifies that attesting to RSA keys works and generates the expected output.
3876  */
TEST_F(AttestationTest,RsaAttestation)3877 TEST_F(AttestationTest, RsaAttestation) {
3878     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3879                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3880                                              .RsaSigningKey(1024, 3)
3881                                              .Digest(Digest::NONE)
3882                                              .Padding(PaddingMode::NONE)
3883                                              .Authorization(TAG_INCLUDE_UNIQUE_ID)));
3884 
3885     hidl_vec<hidl_vec<uint8_t>> cert_chain;
3886     EXPECT_EQ(
3887         ErrorCode::OK,
3888         AttestKey(
3889             AuthorizationSetBuilder()
3890                 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
3891                 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
3892             &cert_chain));
3893     EXPECT_GE(cert_chain.size(), 2U);
3894     EXPECT_TRUE(verify_chain(cert_chain));
3895     EXPECT_TRUE(
3896         verify_attestation_record("challenge", "foo",                     //
3897                                   key_characteristics_.softwareEnforced,  //
3898                                   key_characteristics_.teeEnforced,       //
3899                                   cert_chain[0]));
3900 }
3901 
3902 /*
3903  * AttestationTest.RsaAttestationRequiresAppId
3904  *
3905  * Verifies that attesting to RSA requires app ID.
3906  */
TEST_F(AttestationTest,RsaAttestationRequiresAppId)3907 TEST_F(AttestationTest, RsaAttestationRequiresAppId) {
3908     ASSERT_EQ(ErrorCode::OK,
3909               GenerateKey(AuthorizationSetBuilder()
3910                               .Authorization(TAG_NO_AUTH_REQUIRED)
3911                               .RsaSigningKey(1024, 3)
3912                               .Digest(Digest::NONE)
3913                               .Padding(PaddingMode::NONE)
3914                               .Authorization(TAG_INCLUDE_UNIQUE_ID)));
3915 
3916     hidl_vec<hidl_vec<uint8_t>> cert_chain;
3917     EXPECT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
3918               AttestKey(AuthorizationSetBuilder().Authorization(
3919                             TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge")),
3920                         &cert_chain));
3921 }
3922 
3923 /*
3924  * AttestationTest.EcAttestation
3925  *
3926  * Verifies that attesting to EC keys works and generates the expected output.
3927  */
TEST_F(AttestationTest,EcAttestation)3928 TEST_F(AttestationTest, EcAttestation) {
3929     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3930                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3931                                              .EcdsaSigningKey(EcCurve::P_256)
3932                                              .Digest(Digest::SHA_2_256)
3933                                              .Authorization(TAG_INCLUDE_UNIQUE_ID)));
3934 
3935     hidl_vec<hidl_vec<uint8_t>> cert_chain;
3936     EXPECT_EQ(
3937         ErrorCode::OK,
3938         AttestKey(
3939             AuthorizationSetBuilder()
3940                 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
3941                 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
3942             &cert_chain));
3943     EXPECT_GE(cert_chain.size(), 2U);
3944     EXPECT_TRUE(verify_chain(cert_chain));
3945 
3946     EXPECT_TRUE(
3947         verify_attestation_record("challenge", "foo",                     //
3948                                   key_characteristics_.softwareEnforced,  //
3949                                   key_characteristics_.teeEnforced,       //
3950                                   cert_chain[0]));
3951 }
3952 
3953 /*
3954  * AttestationTest.EcAttestationRequiresAttestationAppId
3955  *
3956  * Verifies that attesting to EC keys requires app ID
3957  */
TEST_F(AttestationTest,EcAttestationRequiresAttestationAppId)3958 TEST_F(AttestationTest, EcAttestationRequiresAttestationAppId) {
3959     ASSERT_EQ(ErrorCode::OK,
3960               GenerateKey(AuthorizationSetBuilder()
3961                               .Authorization(TAG_NO_AUTH_REQUIRED)
3962                               .EcdsaSigningKey(EcCurve::P_256)
3963                               .Digest(Digest::SHA_2_256)
3964                               .Authorization(TAG_INCLUDE_UNIQUE_ID)));
3965 
3966     hidl_vec<hidl_vec<uint8_t>> cert_chain;
3967     EXPECT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
3968               AttestKey(AuthorizationSetBuilder().Authorization(
3969                             TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge")),
3970                         &cert_chain));
3971 }
3972 
3973 /*
3974  * AttestationTest.AesAttestation
3975  *
3976  * Verifies that attesting to AES keys fails in the expected way.
3977  */
TEST_F(AttestationTest,AesAttestation)3978 TEST_F(AttestationTest, AesAttestation) {
3979     ASSERT_EQ(ErrorCode::OK,
3980               GenerateKey(AuthorizationSetBuilder()
3981                               .Authorization(TAG_NO_AUTH_REQUIRED)
3982                               .AesEncryptionKey(128)
3983                               .EcbMode()
3984                               .Padding(PaddingMode::PKCS7)));
3985 
3986     hidl_vec<hidl_vec<uint8_t>> cert_chain;
3987     EXPECT_EQ(
3988         ErrorCode::INCOMPATIBLE_ALGORITHM,
3989         AttestKey(
3990             AuthorizationSetBuilder()
3991                 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
3992                 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
3993             &cert_chain));
3994 }
3995 
3996 /*
3997  * AttestationTest.HmacAttestation
3998  *
3999  * Verifies that attesting to HMAC keys fails in the expected way.
4000  */
TEST_F(AttestationTest,HmacAttestation)4001 TEST_F(AttestationTest, HmacAttestation) {
4002     ASSERT_EQ(ErrorCode::OK,
4003               GenerateKey(AuthorizationSetBuilder()
4004                               .Authorization(TAG_NO_AUTH_REQUIRED)
4005                               .HmacKey(128)
4006                               .EcbMode()
4007                               .Digest(Digest::SHA_2_256)
4008                               .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4009 
4010     hidl_vec<hidl_vec<uint8_t>> cert_chain;
4011     EXPECT_EQ(
4012         ErrorCode::INCOMPATIBLE_ALGORITHM,
4013         AttestKey(
4014             AuthorizationSetBuilder()
4015                 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
4016                 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
4017             &cert_chain));
4018 }
4019 
4020 typedef KeymasterHidlTest KeyDeletionTest;
4021 
4022 /**
4023  * KeyDeletionTest.DeleteKey
4024  *
4025  * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
4026  * valid key blob.
4027  */
TEST_F(KeyDeletionTest,DeleteKey)4028 TEST_F(KeyDeletionTest, DeleteKey) {
4029     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4030                                              .RsaSigningKey(1024, 3)
4031                                              .Digest(Digest::NONE)
4032                                              .Padding(PaddingMode::NONE)
4033                                              .Authorization(TAG_NO_AUTH_REQUIRED)));
4034 
4035     // Delete must work if rollback protection is implemented
4036     AuthorizationSet teeEnforced(key_characteristics_.teeEnforced);
4037     bool rollback_protected = teeEnforced.Contains(TAG_ROLLBACK_RESISTANT);
4038 
4039     if (rollback_protected) {
4040         ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
4041     } else {
4042         auto delete_result = DeleteKey(true /* keep key blob */);
4043         ASSERT_TRUE(delete_result == ErrorCode::OK | delete_result == ErrorCode::UNIMPLEMENTED);
4044     }
4045 
4046     string message = "12345678901234567890123456789012";
4047     AuthorizationSet begin_out_params;
4048 
4049     if (rollback_protected) {
4050         EXPECT_EQ(
4051             ErrorCode::INVALID_KEY_BLOB,
4052             Begin(KeyPurpose::SIGN, key_blob_, AuthorizationSetBuilder()
4053                                                    .Digest(Digest::NONE)
4054                                                    .Padding(PaddingMode::NONE),
4055                   &begin_out_params, &op_handle_))
4056             << " (Possibly b/37623742)";
4057     } else {
4058         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_,
4059                                        AuthorizationSetBuilder()
4060                                            .Digest(Digest::NONE)
4061                                            .Padding(PaddingMode::NONE),
4062                                        &begin_out_params, &op_handle_));
4063     }
4064     AbortIfNeeded();
4065     key_blob_ = HidlBuf();
4066 }
4067 
4068 /**
4069  * KeyDeletionTest.DeleteInvalidKey
4070  *
4071  * This test checks that the HAL excepts invalid key blobs.
4072  */
TEST_F(KeyDeletionTest,DeleteInvalidKey)4073 TEST_F(KeyDeletionTest, DeleteInvalidKey) {
4074     // Generate key just to check if rollback protection is implemented
4075     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4076                                              .RsaSigningKey(1024, 3)
4077                                              .Digest(Digest::NONE)
4078                                              .Padding(PaddingMode::NONE)
4079                                              .Authorization(TAG_NO_AUTH_REQUIRED)));
4080 
4081     // Delete must work if rollback protection is implemented
4082     AuthorizationSet teeEnforced(key_characteristics_.teeEnforced);
4083     bool rollback_protected = teeEnforced.Contains(TAG_ROLLBACK_RESISTANT);
4084 
4085     // Delete the key we don't care about the result at this point.
4086     DeleteKey();
4087 
4088     // Now create an invalid key blob and delete it.
4089     key_blob_ = HidlBuf("just some garbage data which is not a valid key blob");
4090 
4091     if (rollback_protected) {
4092         ASSERT_EQ(ErrorCode::OK, DeleteKey());
4093     } else {
4094         auto delete_result = DeleteKey();
4095         ASSERT_TRUE(delete_result == ErrorCode::OK | delete_result == ErrorCode::UNIMPLEMENTED);
4096     }
4097 }
4098 
4099 /**
4100  * KeyDeletionTest.DeleteAllKeys
4101  *
4102  * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
4103  *
4104  * BEWARE: This test has serious side effects. All user keys will be lost! This includes
4105  * FBE/FDE encryption keys, which means that the device will not even boot until after the
4106  * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
4107  * been provisioned. Use this test only on dedicated testing devices that have no valuable
4108  * credentials stored in Keystore/Keymaster.
4109  */
TEST_F(KeyDeletionTest,DeleteAllKeys)4110 TEST_F(KeyDeletionTest, DeleteAllKeys) {
4111     if (!arm_deleteAllKeys) return;
4112     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4113                                              .RsaSigningKey(1024, 3)
4114                                              .Digest(Digest::NONE)
4115                                              .Padding(PaddingMode::NONE)
4116                                              .Authorization(TAG_NO_AUTH_REQUIRED)));
4117 
4118     // Delete must work if rollback protection is implemented
4119     AuthorizationSet teeEnforced(key_characteristics_.teeEnforced);
4120     bool rollback_protected = teeEnforced.Contains(TAG_ROLLBACK_RESISTANT);
4121 
4122     ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
4123 
4124     string message = "12345678901234567890123456789012";
4125     AuthorizationSet begin_out_params;
4126 
4127     if (rollback_protected) {
4128         EXPECT_EQ(
4129             ErrorCode::INVALID_KEY_BLOB,
4130             Begin(KeyPurpose::SIGN, key_blob_, AuthorizationSetBuilder()
4131                                                    .Digest(Digest::NONE)
4132                                                    .Padding(PaddingMode::NONE),
4133                   &begin_out_params, &op_handle_));
4134     } else {
4135         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_,
4136                                        AuthorizationSetBuilder()
4137                                            .Digest(Digest::NONE)
4138                                            .Padding(PaddingMode::NONE),
4139                                        &begin_out_params, &op_handle_));
4140     }
4141     AbortIfNeeded();
4142     key_blob_ = HidlBuf();
4143 }
4144 
4145 }  // namespace test
4146 }  // namespace V3_0
4147 }  // namespace keymaster
4148 }  // namespace hardware
4149 }  // namespace android
4150 
main(int argc,char ** argv)4151 int main(int argc, char** argv) {
4152     ::testing::InitGoogleTest(&argc, argv);
4153     std::vector<std::string> positional_args;
4154     for (int i = 1; i < argc; ++i) {
4155         if (argv[i][0] == '-') {
4156             if (std::string(argv[i]) == "--arm_deleteAllKeys") {
4157                 arm_deleteAllKeys = true;
4158             }
4159         } else {
4160             positional_args.push_back(argv[i]);
4161         }
4162     }
4163     if (positional_args.size()) {
4164         ALOGI("Running keymaster VTS against service \"%s\"", positional_args[0].c_str());
4165         service_name = positional_args[0];
4166     }
4167     int status = RUN_ALL_TESTS();
4168     ALOGI("Test result = %d", status);
4169     return status;
4170 }
4171