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