• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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::__anon241bf2ce0111::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     const BIGNUM* n = RSA_get0_n(rsa.get());
2621     size_t modulus_len = BN_num_bytes(n);
2622     ASSERT_EQ(1024U / 8, modulus_len);
2623     std::unique_ptr<uint8_t[]> modulus_buf(new uint8_t[modulus_len]);
2624     BN_bn2bin(n, modulus_buf.get());
2625 
2626     // The modulus is too big to encrypt.
2627     string message(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
2628 
2629     auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2630     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2631 
2632     string result;
2633     EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &result));
2634 
2635     // One smaller than the modulus is okay.
2636     BIGNUM_Ptr n_minus_1(BN_new());
2637     ASSERT_TRUE(n_minus_1);
2638     ASSERT_TRUE(BN_sub(n_minus_1.get(), n, BN_value_one()));
2639     modulus_len = BN_num_bytes(n_minus_1.get());
2640     ASSERT_EQ(1024U / 8, modulus_len);
2641     BN_bn2bin(n_minus_1.get(), modulus_buf.get());
2642     message = string(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
2643     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2644     EXPECT_EQ(ErrorCode::OK, Finish(message, &result));
2645 }
2646 
2647 /*
2648  * EncryptionOperationsTest.RsaOaepSuccess
2649  *
2650  * Verifies that RSA-OAEP encryption operations work, with all digests.
2651  */
TEST_P(EncryptionOperationsTest,RsaOaepSuccess)2652 TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
2653     auto digests = {Digest::MD5,       Digest::SHA1,      Digest::SHA_2_224,
2654                     Digest::SHA_2_256, Digest::SHA_2_384, Digest::SHA_2_512};
2655 
2656     size_t key_size = 2048;  // Need largish key for SHA-512 test.
2657     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2658                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2659                                              .RsaEncryptionKey(key_size, 3)
2660                                              .Padding(PaddingMode::RSA_OAEP)
2661                                              .Digest(digests)));
2662 
2663     string message = "Hello";
2664 
2665     for (auto digest : digests) {
2666         auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
2667         string ciphertext1 = EncryptMessage(message, params);
2668         if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
2669         EXPECT_EQ(key_size / 8, ciphertext1.size());
2670 
2671         string ciphertext2 = EncryptMessage(message, params);
2672         EXPECT_EQ(key_size / 8, ciphertext2.size());
2673 
2674         // OAEP randomizes padding so every result should be different (with astronomically high
2675         // probability).
2676         EXPECT_NE(ciphertext1, ciphertext2);
2677 
2678         string plaintext1 = DecryptMessage(ciphertext1, params);
2679         EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
2680         string plaintext2 = DecryptMessage(ciphertext2, params);
2681         EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
2682 
2683         // Decrypting corrupted ciphertext should fail.
2684         size_t offset_to_corrupt = random() % ciphertext1.size();
2685         char corrupt_byte;
2686         do {
2687             corrupt_byte = static_cast<char>(random() % 256);
2688         } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2689         ciphertext1[offset_to_corrupt] = corrupt_byte;
2690 
2691         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2692         string result;
2693         EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2694         EXPECT_EQ(0U, result.size());
2695     }
2696 }
2697 
2698 /*
2699  * EncryptionOperationsTest.RsaOaepInvalidDigest
2700  *
2701  * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2702  * without a digest.
2703  */
TEST_P(EncryptionOperationsTest,RsaOaepInvalidDigest)2704 TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
2705     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2706                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2707                                              .RsaEncryptionKey(1024, 3)
2708                                              .Padding(PaddingMode::RSA_OAEP)
2709                                              .Digest(Digest::NONE)));
2710     string message = "Hello World!";
2711 
2712     auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
2713     EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2714 }
2715 
2716 /*
2717  * EncryptionOperationsTest.RsaOaepInvalidDigest
2718  *
2719  * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt with a
2720  * different digest than was used to encrypt.
2721  */
TEST_P(EncryptionOperationsTest,RsaOaepDecryptWithWrongDigest)2722 TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
2723     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2724                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2725                                              .RsaEncryptionKey(1024, 3)
2726                                              .Padding(PaddingMode::RSA_OAEP)
2727                                              .Digest(Digest::SHA_2_256, Digest::SHA_2_224)));
2728     string message = "Hello World!";
2729     string ciphertext = EncryptMessage(
2730         message,
2731         AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
2732 
2733     EXPECT_EQ(
2734         ErrorCode::OK,
2735         Begin(KeyPurpose::DECRYPT,
2736               AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP)));
2737     string result;
2738     EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
2739     EXPECT_EQ(0U, result.size());
2740 }
2741 
2742 /*
2743  * EncryptionOperationsTest.RsaOaepTooLarge
2744  *
2745  * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
2746  * too-large message.
2747  */
TEST_P(EncryptionOperationsTest,RsaOaepTooLarge)2748 TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
2749     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2750                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2751                                              .RsaEncryptionKey(1024, 3)
2752                                              .Padding(PaddingMode::RSA_OAEP)
2753                                              .Digest(Digest::SHA1)));
2754     constexpr size_t digest_size = 160 /* SHA1 */ / 8;
2755     constexpr size_t oaep_overhead = 2 * digest_size + 2;
2756     string message(1024 / 8 - oaep_overhead + 1, 'a');
2757     EXPECT_EQ(ErrorCode::OK,
2758               Begin(KeyPurpose::ENCRYPT,
2759                     AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::SHA1)));
2760     string result;
2761     auto error = Finish(message, &result);
2762     EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2763     EXPECT_EQ(0U, result.size());
2764 }
2765 
2766 /*
2767  * EncryptionOperationsTest.RsaPkcs1Success
2768  *
2769  * Verifies that RSA PKCS encryption/decrypts works.
2770  */
TEST_P(EncryptionOperationsTest,RsaPkcs1Success)2771 TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
2772     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2773                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2774                                              .RsaEncryptionKey(1024, 3)
2775                                              .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)));
2776 
2777     string message = "Hello World!";
2778     auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2779     string ciphertext1 = EncryptMessage(message, params);
2780     EXPECT_EQ(1024U / 8, ciphertext1.size());
2781 
2782     string ciphertext2 = EncryptMessage(message, params);
2783     EXPECT_EQ(1024U / 8, ciphertext2.size());
2784 
2785     // PKCS1 v1.5 randomizes padding so every result should be different.
2786     EXPECT_NE(ciphertext1, ciphertext2);
2787 
2788     string plaintext = DecryptMessage(ciphertext1, params);
2789     EXPECT_EQ(message, plaintext);
2790 
2791     // Decrypting corrupted ciphertext should fail.
2792     size_t offset_to_corrupt = random() % ciphertext1.size();
2793     char corrupt_byte;
2794     do {
2795         corrupt_byte = static_cast<char>(random() % 256);
2796     } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2797     ciphertext1[offset_to_corrupt] = corrupt_byte;
2798 
2799     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2800     string result;
2801     EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2802     EXPECT_EQ(0U, result.size());
2803 }
2804 
2805 /*
2806  * EncryptionOperationsTest.RsaPkcs1TooLarge
2807  *
2808  * Verifies that RSA PKCS encryption fails in the correct way when the mssage is too large.
2809  */
TEST_P(EncryptionOperationsTest,RsaPkcs1TooLarge)2810 TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
2811     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2812                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2813                                              .RsaEncryptionKey(1024, 3)
2814                                              .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)));
2815     string message(1024 / 8 - 10, 'a');
2816 
2817     auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2818     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2819     string result;
2820     auto error = Finish(message, &result);
2821     EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2822     EXPECT_EQ(0U, result.size());
2823 }
2824 
2825 /*
2826  * EncryptionOperationsTest.EcdsaEncrypt
2827  *
2828  * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
2829  */
TEST_P(EncryptionOperationsTest,EcdsaEncrypt)2830 TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
2831     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2832                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2833                                              .EcdsaSigningKey(224)
2834                                              .Digest(Digest::NONE)));
2835     auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
2836     ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params))
2837         << "(Possibly b/33543625)";
2838     ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params))
2839         << "(Possibly b/33543625)";
2840 }
2841 
2842 /*
2843  * EncryptionOperationsTest.HmacEncrypt
2844  *
2845  * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
2846  */
TEST_P(EncryptionOperationsTest,HmacEncrypt)2847 TEST_P(EncryptionOperationsTest, HmacEncrypt) {
2848     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2849                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2850                                              .HmacKey(128)
2851                                              .Digest(Digest::SHA_2_256)
2852                                              .Padding(PaddingMode::NONE)
2853                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2854     auto params = AuthorizationSetBuilder()
2855                       .Digest(Digest::SHA_2_256)
2856                       .Padding(PaddingMode::NONE)
2857                       .Authorization(TAG_MAC_LENGTH, 128);
2858     ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params))
2859         << "(Possibly b/33543625)";
2860     ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params))
2861         << "(Possibly b/33543625)";
2862 }
2863 
2864 /*
2865  * EncryptionOperationsTest.AesEcbRoundTripSuccess
2866  *
2867  * Verifies that AES ECB mode works.
2868  */
TEST_P(EncryptionOperationsTest,AesEcbRoundTripSuccess)2869 TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
2870     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2871                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2872                                              .AesEncryptionKey(128)
2873                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2874                                              .Padding(PaddingMode::NONE)));
2875 
2876     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2877 
2878     // Two-block message.
2879     string message = "12345678901234567890123456789012";
2880     string ciphertext1 = EncryptMessage(message, params);
2881     EXPECT_EQ(message.size(), ciphertext1.size());
2882 
2883     string ciphertext2 = EncryptMessage(string(message), params);
2884     EXPECT_EQ(message.size(), ciphertext2.size());
2885 
2886     // ECB is deterministic.
2887     EXPECT_EQ(ciphertext1, ciphertext2);
2888 
2889     string plaintext = DecryptMessage(ciphertext1, params);
2890     EXPECT_EQ(message, plaintext);
2891 }
2892 
2893 /*
2894  * EncryptionOperationsTest.AesEcbRoundTripSuccess
2895  *
2896  * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
2897  */
TEST_P(EncryptionOperationsTest,AesWrongMode)2898 TEST_P(EncryptionOperationsTest, AesWrongMode) {
2899     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2900                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2901                                              .AesEncryptionKey(128)
2902                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
2903                                              .Padding(PaddingMode::NONE)));
2904     // Two-block message.
2905     string message = "12345678901234567890123456789012";
2906     EXPECT_EQ(
2907         ErrorCode::INCOMPATIBLE_BLOCK_MODE,
2908         Begin(KeyPurpose::ENCRYPT,
2909               AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
2910 }
2911 
2912 /*
2913  * EncryptionOperationsTest.AesEcbNoPaddingWrongInputSize
2914  *
2915  * Verifies that AES encryption fails in the correct way when provided an input that is not a
2916  * multiple of the block size and no padding is specified.
2917  */
TEST_P(EncryptionOperationsTest,AesEcbNoPaddingWrongInputSize)2918 TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
2919     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2920                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2921                                              .AesEncryptionKey(128)
2922                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2923                                              .Padding(PaddingMode::NONE)));
2924     // Message is slightly shorter than two blocks.
2925     string message(16 * 2 - 1, 'a');
2926 
2927     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2928     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2929     string ciphertext;
2930     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
2931     EXPECT_EQ(0U, ciphertext.size());
2932 }
2933 
2934 /*
2935  * EncryptionOperationsTest.AesEcbPkcs7Padding
2936  *
2937  * Verifies that AES PKCS7 padding works for any message length.
2938  */
TEST_P(EncryptionOperationsTest,AesEcbPkcs7Padding)2939 TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
2940     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2941                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2942                                              .AesEncryptionKey(128)
2943                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2944                                              .Padding(PaddingMode::PKCS7)));
2945 
2946     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2947 
2948     // Try various message lengths; all should work.
2949     for (size_t i = 0; i < 32; ++i) {
2950         string message(i, 'a');
2951         string ciphertext = EncryptMessage(message, params);
2952         EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2953         string plaintext = DecryptMessage(ciphertext, params);
2954         EXPECT_EQ(message, plaintext);
2955     }
2956 }
2957 
2958 /*
2959  * EncryptionOperationsTest.AesEcbWrongPadding
2960  *
2961  * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
2962  * specified.
2963  */
TEST_P(EncryptionOperationsTest,AesEcbWrongPadding)2964 TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
2965     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2966                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2967                                              .AesEncryptionKey(128)
2968                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2969                                              .Padding(PaddingMode::NONE)));
2970 
2971     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2972 
2973     // Try various message lengths; all should fail
2974     for (size_t i = 0; i < 32; ++i) {
2975         string message(i, 'a');
2976         EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
2977     }
2978 }
2979 
2980 /*
2981  * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
2982  *
2983  * Verifies that AES decryption fails in the correct way when the padding is corrupted.
2984  */
TEST_P(EncryptionOperationsTest,AesEcbPkcs7PaddingCorrupted)2985 TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
2986     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2987                                              .Authorization(TAG_NO_AUTH_REQUIRED)
2988                                              .AesEncryptionKey(128)
2989                                              .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2990                                              .Padding(PaddingMode::PKCS7)));
2991 
2992     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2993 
2994     string message = "a";
2995     string ciphertext = EncryptMessage(message, params);
2996     EXPECT_EQ(16U, ciphertext.size());
2997     EXPECT_NE(ciphertext, message);
2998     ++ciphertext[ciphertext.size() / 2];
2999 
3000     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3001     string plaintext;
3002     EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
3003 }
3004 
CopyIv(const AuthorizationSet & set)3005 HidlBuf CopyIv(const AuthorizationSet& set) {
3006     auto iv = set.GetTagValue(TAG_NONCE);
3007     EXPECT_TRUE(iv.isOk());
3008     return iv.value();
3009 }
3010 
3011 /*
3012  * EncryptionOperationsTest.AesCtrRoundTripSuccess
3013  *
3014  * Verifies that AES CTR mode works.
3015  */
TEST_P(EncryptionOperationsTest,AesCtrRoundTripSuccess)3016 TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
3017     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3018                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3019                                              .AesEncryptionKey(128)
3020                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3021                                              .Padding(PaddingMode::NONE)));
3022 
3023     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3024 
3025     string message = "123";
3026     AuthorizationSet out_params;
3027     string ciphertext1 = EncryptMessage(message, params, &out_params);
3028     HidlBuf iv1 = CopyIv(out_params);
3029     EXPECT_EQ(16U, iv1.size());
3030 
3031     EXPECT_EQ(message.size(), ciphertext1.size());
3032 
3033     out_params.Clear();
3034     string ciphertext2 = EncryptMessage(message, params, &out_params);
3035     HidlBuf iv2 = CopyIv(out_params);
3036     EXPECT_EQ(16U, iv2.size());
3037 
3038     // IVs should be random, so ciphertexts should differ.
3039     EXPECT_NE(ciphertext1, ciphertext2);
3040 
3041     auto params_iv1 =
3042         AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
3043     auto params_iv2 =
3044         AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
3045 
3046     string plaintext = DecryptMessage(ciphertext1, params_iv1);
3047     EXPECT_EQ(message, plaintext);
3048     plaintext = DecryptMessage(ciphertext2, params_iv2);
3049     EXPECT_EQ(message, plaintext);
3050 
3051     // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
3052     plaintext = DecryptMessage(ciphertext1, params_iv2);
3053     EXPECT_NE(message, plaintext);
3054     plaintext = DecryptMessage(ciphertext2, params_iv1);
3055     EXPECT_NE(message, plaintext);
3056 }
3057 
3058 /*
3059  * EncryptionOperationsTest.AesIncremental
3060  *
3061  * Verifies that AES works, all modes, when provided data in various size increments.
3062  */
TEST_P(EncryptionOperationsTest,AesIncremental)3063 TEST_P(EncryptionOperationsTest, AesIncremental) {
3064     auto block_modes = {
3065         BlockMode::ECB, BlockMode::CBC, BlockMode::CTR, BlockMode::GCM,
3066     };
3067 
3068     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3069                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3070                                              .AesEncryptionKey(128)
3071                                              .BlockMode(block_modes)
3072                                              .Padding(PaddingMode::NONE)
3073                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3074 
3075     for (int increment = 1; increment <= 240; ++increment) {
3076         for (auto block_mode : block_modes) {
3077             string message(240, 'a');
3078             auto params = AuthorizationSetBuilder()
3079                               .BlockMode(block_mode)
3080                               .Padding(PaddingMode::NONE)
3081                               .Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
3082 
3083             AuthorizationSet output_params;
3084             EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
3085 
3086             string ciphertext;
3087             size_t input_consumed;
3088             string to_send;
3089             for (size_t i = 0; i < message.size(); i += increment) {
3090                 to_send.append(message.substr(i, increment));
3091                 EXPECT_EQ(ErrorCode::OK, Update(to_send, &ciphertext, &input_consumed));
3092                 to_send = to_send.substr(input_consumed);
3093 
3094                 switch (block_mode) {
3095                 case BlockMode::ECB:
3096                 case BlockMode::CBC:
3097                     // Implementations must take as many blocks as possible, leaving less than
3098                     // a block.
3099                     EXPECT_LE(to_send.length(), 16U);
3100                     break;
3101                 case BlockMode::GCM:
3102                 case BlockMode::CTR:
3103                     // Implementations must always take all the data.
3104                     EXPECT_EQ(0U, to_send.length());
3105                     break;
3106                 }
3107             }
3108             EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext)) << "Error sending " << to_send;
3109 
3110             switch (block_mode) {
3111             case BlockMode::GCM:
3112                 EXPECT_EQ(message.size() + 16, ciphertext.size());
3113                 break;
3114             case BlockMode::CTR:
3115                 EXPECT_EQ(message.size(), ciphertext.size());
3116                 break;
3117             case BlockMode::CBC:
3118             case BlockMode::ECB:
3119                 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
3120                 break;
3121             }
3122 
3123             auto iv = output_params.GetTagValue(TAG_NONCE);
3124             switch (block_mode) {
3125             case BlockMode::CBC:
3126             case BlockMode::GCM:
3127             case BlockMode::CTR:
3128                 ASSERT_TRUE(iv.isOk()) << "No IV for block mode " << block_mode;
3129                 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv.value().size());
3130                 params.push_back(TAG_NONCE, iv.value());
3131                 break;
3132 
3133             case BlockMode::ECB:
3134                 EXPECT_FALSE(iv.isOk()) << "ECB mode should not generate IV";
3135                 break;
3136             }
3137 
3138             EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
3139                 << "Decrypt begin() failed for block mode " << block_mode;
3140 
3141             string plaintext;
3142             for (size_t i = 0; i < ciphertext.size(); i += increment) {
3143                 to_send.append(ciphertext.substr(i, increment));
3144                 EXPECT_EQ(ErrorCode::OK, Update(to_send, &plaintext, &input_consumed));
3145                 to_send = to_send.substr(input_consumed);
3146             }
3147             ErrorCode error = Finish(to_send, &plaintext);
3148             ASSERT_EQ(ErrorCode::OK, error)
3149                 << "Decryption failed for block mode " << block_mode << " and increment "
3150                 << increment << " (Possibly b/33584622)";
3151             if (error == ErrorCode::OK) {
3152                 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
3153                                               << block_mode << " and increment " << increment;
3154             }
3155         }
3156     }
3157 }
3158 
3159 struct AesCtrSp80038aTestVector {
3160     const char* key;
3161     const char* nonce;
3162     const char* plaintext;
3163     const char* ciphertext;
3164 };
3165 
3166 // These test vectors are taken from
3167 // http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
3168 static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
3169     // AES-128
3170     {
3171         "2b7e151628aed2a6abf7158809cf4f3c", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3172         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3173         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3174         "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
3175         "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
3176     },
3177     // AES-192
3178     {
3179         "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3180         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3181         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3182         "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
3183         "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
3184     },
3185     // AES-256
3186     {
3187         "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
3188         "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3189         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3190         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3191         "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
3192         "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
3193     },
3194 };
3195 
3196 /*
3197  * EncryptionOperationsTest.AesCtrSp80038aTestVector
3198  *
3199  * Verifies AES CTR implementation against SP800-38A test vectors.
3200  */
TEST_P(EncryptionOperationsTest,AesCtrSp80038aTestVector)3201 TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
3202     for (size_t i = 0; i < 3; i++) {
3203         const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
3204         const string key = hex2str(test.key);
3205         const string nonce = hex2str(test.nonce);
3206         const string plaintext = hex2str(test.plaintext);
3207         const string ciphertext = hex2str(test.ciphertext);
3208         CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
3209     }
3210 }
3211 
3212 /*
3213  * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
3214  *
3215  * Verifies that keymaster rejects use of CTR mode with PKCS7 padding in the correct way.
3216  */
TEST_P(EncryptionOperationsTest,AesCtrIncompatiblePaddingMode)3217 TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
3218     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3219                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3220                                              .AesEncryptionKey(128)
3221                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3222                                              .Padding(PaddingMode::PKCS7)));
3223     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3224     EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3225 }
3226 
3227 /*
3228  * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3229  *
3230  * Verifies that keymaster fails correctly when the user supplies an incorrect-size nonce.
3231  */
TEST_P(EncryptionOperationsTest,AesCtrInvalidCallerNonce)3232 TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
3233     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3234                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3235                                              .AesEncryptionKey(128)
3236                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3237                                              .Authorization(TAG_CALLER_NONCE)
3238                                              .Padding(PaddingMode::NONE)));
3239 
3240     auto params = AuthorizationSetBuilder()
3241                       .BlockMode(BlockMode::CTR)
3242                       .Padding(PaddingMode::NONE)
3243                       .Authorization(TAG_NONCE, HidlBuf(string(1, 'a')));
3244     EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3245 
3246     params = AuthorizationSetBuilder()
3247                  .BlockMode(BlockMode::CTR)
3248                  .Padding(PaddingMode::NONE)
3249                  .Authorization(TAG_NONCE, HidlBuf(string(15, 'a')));
3250     EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3251 
3252     params = AuthorizationSetBuilder()
3253                  .BlockMode(BlockMode::CTR)
3254                  .Padding(PaddingMode::NONE)
3255                  .Authorization(TAG_NONCE, HidlBuf(string(17, 'a')));
3256     EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3257 }
3258 
3259 /*
3260  * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3261  *
3262  * Verifies that keymaster fails correctly when the user supplies an incorrect-size nonce.
3263  */
TEST_P(EncryptionOperationsTest,AesCbcRoundTripSuccess)3264 TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
3265     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3266                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3267                                              .AesEncryptionKey(128)
3268                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3269                                              .Padding(PaddingMode::NONE)));
3270     // Two-block message.
3271     string message = "12345678901234567890123456789012";
3272     auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3273     AuthorizationSet out_params;
3274     string ciphertext1 = EncryptMessage(message, params, &out_params);
3275     HidlBuf iv1 = CopyIv(out_params);
3276     EXPECT_EQ(message.size(), ciphertext1.size());
3277 
3278     out_params.Clear();
3279 
3280     string ciphertext2 = EncryptMessage(message, params, &out_params);
3281     HidlBuf iv2 = CopyIv(out_params);
3282     EXPECT_EQ(message.size(), ciphertext2.size());
3283 
3284     // IVs should be random, so ciphertexts should differ.
3285     EXPECT_NE(ciphertext1, ciphertext2);
3286 
3287     params.push_back(TAG_NONCE, iv1);
3288     string plaintext = DecryptMessage(ciphertext1, params);
3289     EXPECT_EQ(message, plaintext);
3290 }
3291 
3292 /*
3293  * EncryptionOperationsTest.AesCallerNonce
3294  *
3295  * Verifies that AES caller-provided nonces work correctly.
3296  */
TEST_P(EncryptionOperationsTest,AesCallerNonce)3297 TEST_P(EncryptionOperationsTest, AesCallerNonce) {
3298     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3299                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3300                                              .AesEncryptionKey(128)
3301                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3302                                              .Authorization(TAG_CALLER_NONCE)
3303                                              .Padding(PaddingMode::NONE)));
3304 
3305     string message = "12345678901234567890123456789012";
3306 
3307     // Don't specify nonce, should get a random one.
3308     AuthorizationSetBuilder params =
3309         AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3310     AuthorizationSet out_params;
3311     string ciphertext = EncryptMessage(message, params, &out_params);
3312     EXPECT_EQ(message.size(), ciphertext.size());
3313     EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE).value().size());
3314 
3315     params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE).value());
3316     string plaintext = DecryptMessage(ciphertext, params);
3317     EXPECT_EQ(message, plaintext);
3318 
3319     // Now specify a nonce, should also work.
3320     params = AuthorizationSetBuilder()
3321                  .BlockMode(BlockMode::CBC)
3322                  .Padding(PaddingMode::NONE)
3323                  .Authorization(TAG_NONCE, HidlBuf("abcdefghijklmnop"));
3324     out_params.Clear();
3325     ciphertext = EncryptMessage(message, params, &out_params);
3326 
3327     // Decrypt with correct nonce.
3328     plaintext = DecryptMessage(ciphertext, params);
3329     EXPECT_EQ(message, plaintext);
3330 
3331     // Try with wrong nonce.
3332     params = AuthorizationSetBuilder()
3333                  .BlockMode(BlockMode::CBC)
3334                  .Padding(PaddingMode::NONE)
3335                  .Authorization(TAG_NONCE, HidlBuf("aaaaaaaaaaaaaaaa"));
3336     plaintext = DecryptMessage(ciphertext, params);
3337     EXPECT_NE(message, plaintext);
3338 }
3339 
3340 /*
3341  * EncryptionOperationsTest.AesCallerNonceProhibited
3342  *
3343  * Verifies that caller-provided nonces are not permitted when not specified in the key
3344  * authorizations.
3345  */
TEST_P(EncryptionOperationsTest,AesCallerNonceProhibited)3346 TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
3347     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3348                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3349                                              .AesEncryptionKey(128)
3350                                              .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3351                                              .Padding(PaddingMode::NONE)));
3352 
3353     string message = "12345678901234567890123456789012";
3354 
3355     // Don't specify nonce, should get a random one.
3356     AuthorizationSetBuilder params =
3357         AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3358     AuthorizationSet out_params;
3359     string ciphertext = EncryptMessage(message, params, &out_params);
3360     EXPECT_EQ(message.size(), ciphertext.size());
3361     EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE).value().size());
3362 
3363     params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE).value());
3364     string plaintext = DecryptMessage(ciphertext, params);
3365     EXPECT_EQ(message, plaintext);
3366 
3367     // Now specify a nonce, should fail
3368     params = AuthorizationSetBuilder()
3369                  .BlockMode(BlockMode::CBC)
3370                  .Padding(PaddingMode::NONE)
3371                  .Authorization(TAG_NONCE, HidlBuf("abcdefghijklmnop"));
3372     out_params.Clear();
3373     EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
3374 }
3375 
3376 /*
3377  * EncryptionOperationsTest.AesGcmRoundTripSuccess
3378  *
3379  * Verifies that AES GCM mode works.
3380  */
TEST_P(EncryptionOperationsTest,AesGcmRoundTripSuccess)3381 TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
3382     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3383                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3384                                              .AesEncryptionKey(128)
3385                                              .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3386                                              .Padding(PaddingMode::NONE)
3387                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3388 
3389     string aad = "foobar";
3390     string message = "123456789012345678901234567890123456";
3391 
3392     auto begin_params = AuthorizationSetBuilder()
3393                             .BlockMode(BlockMode::GCM)
3394                             .Padding(PaddingMode::NONE)
3395                             .Authorization(TAG_MAC_LENGTH, 128);
3396 
3397     auto update_params =
3398         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3399 
3400     // Encrypt
3401     AuthorizationSet begin_out_params;
3402     ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
3403         << "Begin encrypt";
3404     string ciphertext;
3405     AuthorizationSet update_out_params;
3406     ASSERT_EQ(ErrorCode::OK,
3407               Finish(op_handle_, update_params, message, "", &update_out_params, &ciphertext));
3408 
3409     // Grab nonce
3410     begin_params.push_back(begin_out_params);
3411 
3412     // Decrypt.
3413     ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
3414     string plaintext;
3415     size_t input_consumed;
3416     ASSERT_EQ(ErrorCode::OK, Update(op_handle_, update_params, ciphertext, &update_out_params,
3417                                     &plaintext, &input_consumed));
3418     EXPECT_EQ(ciphertext.size(), input_consumed);
3419     EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
3420 
3421     EXPECT_EQ(message, plaintext);
3422 }
3423 
3424 /*
3425  * EncryptionOperationsTest.AesGcmTooShortTag
3426  *
3427  * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
3428  */
TEST_P(EncryptionOperationsTest,AesGcmTooShortTag)3429 TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
3430     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3431                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3432                                              .AesEncryptionKey(128)
3433                                              .BlockMode(BlockMode::GCM)
3434                                              .Padding(PaddingMode::NONE)
3435                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3436     string message = "123456789012345678901234567890123456";
3437     auto params = AuthorizationSetBuilder()
3438                       .BlockMode(BlockMode::GCM)
3439                       .Padding(PaddingMode::NONE)
3440                       .Authorization(TAG_MAC_LENGTH, 96);
3441 
3442     EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
3443 }
3444 
3445 /*
3446  * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
3447  *
3448  * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
3449  */
TEST_P(EncryptionOperationsTest,AesGcmTooShortTagOnDecrypt)3450 TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
3451     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3452                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3453                                              .AesEncryptionKey(128)
3454                                              .BlockMode(BlockMode::GCM)
3455                                              .Padding(PaddingMode::NONE)
3456                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3457     string aad = "foobar";
3458     string message = "123456789012345678901234567890123456";
3459     auto params = AuthorizationSetBuilder()
3460                       .BlockMode(BlockMode::GCM)
3461                       .Padding(PaddingMode::NONE)
3462                       .Authorization(TAG_MAC_LENGTH, 128);
3463 
3464     auto finish_params =
3465         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3466 
3467     // Encrypt
3468     AuthorizationSet begin_out_params;
3469     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3470     EXPECT_EQ(1U, begin_out_params.size());
3471     ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE).isOk());
3472 
3473     AuthorizationSet finish_out_params;
3474     string ciphertext;
3475     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3476                                     &finish_out_params, &ciphertext));
3477 
3478     params = AuthorizationSetBuilder()
3479                  .Authorizations(begin_out_params)
3480                  .BlockMode(BlockMode::GCM)
3481                  .Padding(PaddingMode::NONE)
3482                  .Authorization(TAG_MAC_LENGTH, 96);
3483 
3484     // Decrypt.
3485     EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
3486 }
3487 
3488 /*
3489  * EncryptionOperationsTest.AesGcmCorruptKey
3490  *
3491  * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
3492  */
TEST_P(EncryptionOperationsTest,AesGcmCorruptKey)3493 TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
3494     const uint8_t nonce_bytes[] = {
3495         0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
3496     };
3497     string nonce = make_string(nonce_bytes);
3498     const uint8_t ciphertext_bytes[] = {
3499         0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc, 0xd2, 0xcb, 0x16,
3500         0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78, 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a,
3501         0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d, 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76,
3502         0x76, 0x5e, 0xfb, 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
3503         0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
3504     };
3505     string ciphertext = make_string(ciphertext_bytes);
3506 
3507     auto params = AuthorizationSetBuilder()
3508                       .BlockMode(BlockMode::GCM)
3509                       .Padding(PaddingMode::NONE)
3510                       .Authorization(TAG_MAC_LENGTH, 128)
3511                       .Authorization(TAG_NONCE, nonce.data(), nonce.size());
3512 
3513     auto import_params = AuthorizationSetBuilder()
3514                              .Authorization(TAG_NO_AUTH_REQUIRED)
3515                              .AesEncryptionKey(128)
3516                              .BlockMode(BlockMode::GCM)
3517                              .Padding(PaddingMode::NONE)
3518                              .Authorization(TAG_CALLER_NONCE)
3519                              .Authorization(TAG_MIN_MAC_LENGTH, 128);
3520 
3521     // Import correct key and decrypt
3522     const uint8_t key_bytes[] = {
3523         0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
3524         0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
3525     };
3526     string key = make_string(key_bytes);
3527     ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3528     string plaintext = DecryptMessage(ciphertext, params);
3529     CheckedDeleteKey();
3530 
3531     // Corrupt key and attempt to decrypt
3532     key[0] = 0;
3533     ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3534     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3535     EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
3536     CheckedDeleteKey();
3537 }
3538 
3539 /*
3540  * EncryptionOperationsTest.AesGcmAadNoData
3541  *
3542  * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
3543  * encrypt.
3544  */
TEST_P(EncryptionOperationsTest,AesGcmAadNoData)3545 TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
3546     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3547                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3548                                              .AesEncryptionKey(128)
3549                                              .BlockMode(BlockMode::GCM)
3550                                              .Padding(PaddingMode::NONE)
3551                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3552 
3553     string aad = "1234567890123456";
3554     auto params = AuthorizationSetBuilder()
3555                       .BlockMode(BlockMode::GCM)
3556                       .Padding(PaddingMode::NONE)
3557                       .Authorization(TAG_MAC_LENGTH, 128);
3558 
3559     auto finish_params =
3560         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3561 
3562     // Encrypt
3563     AuthorizationSet begin_out_params;
3564     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3565     string ciphertext;
3566     AuthorizationSet finish_out_params;
3567     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, "" /* input */, "" /* signature */,
3568                                     &finish_out_params, &ciphertext));
3569     EXPECT_TRUE(finish_out_params.empty());
3570 
3571     // Grab nonce
3572     params.push_back(begin_out_params);
3573 
3574     // Decrypt.
3575     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3576     string plaintext;
3577     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, ciphertext, "" /* signature */,
3578                                     &finish_out_params, &plaintext))
3579         << "(Possibly b/33615032)";
3580 
3581     EXPECT_TRUE(finish_out_params.empty());
3582 
3583     EXPECT_EQ("", plaintext);
3584 }
3585 
3586 /*
3587  * EncryptionOperationsTest.AesGcmMultiPartAad
3588  *
3589  * Verifies that AES GCM mode works when provided additional authenticated data in multiple chunks.
3590  */
TEST_P(EncryptionOperationsTest,AesGcmMultiPartAad)3591 TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
3592     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3593                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3594                                              .AesEncryptionKey(128)
3595                                              .BlockMode(BlockMode::GCM)
3596                                              .Padding(PaddingMode::NONE)
3597                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3598 
3599     string message = "123456789012345678901234567890123456";
3600     auto begin_params = AuthorizationSetBuilder()
3601                             .BlockMode(BlockMode::GCM)
3602                             .Padding(PaddingMode::NONE)
3603                             .Authorization(TAG_MAC_LENGTH, 128);
3604     AuthorizationSet begin_out_params;
3605 
3606     auto update_params =
3607         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3);
3608 
3609     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3610 
3611     // No data, AAD only.
3612     string ciphertext;
3613     size_t input_consumed;
3614     AuthorizationSet update_out_params;
3615     EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, "" /* input */, &update_out_params,
3616                                     &ciphertext, &input_consumed));
3617     EXPECT_EQ(0U, input_consumed);
3618     EXPECT_EQ(0U, ciphertext.size());
3619     EXPECT_TRUE(update_out_params.empty());
3620 
3621     // AAD and data.
3622     EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, message, &update_out_params,
3623                                     &ciphertext, &input_consumed));
3624     EXPECT_EQ(message.size(), input_consumed);
3625     EXPECT_EQ(message.size(), ciphertext.size());
3626     EXPECT_TRUE(update_out_params.empty());
3627 
3628     EXPECT_EQ(ErrorCode::OK, Finish("" /* input */, &ciphertext));
3629 
3630     // Grab nonce.
3631     begin_params.push_back(begin_out_params);
3632 
3633     // Decrypt
3634     update_params =
3635         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foofoo", (size_t)6);
3636 
3637     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
3638     string plaintext;
3639     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, update_params, ciphertext, "" /* signature */,
3640                                     &update_out_params, &plaintext));
3641     EXPECT_TRUE(update_out_params.empty());
3642     EXPECT_EQ(message, plaintext);
3643 }
3644 
3645 /*
3646  * EncryptionOperationsTest.AesGcmAadOutOfOrder
3647  *
3648  * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
3649  */
TEST_P(EncryptionOperationsTest,AesGcmAadOutOfOrder)3650 TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
3651     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3652                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3653                                              .AesEncryptionKey(128)
3654                                              .BlockMode(BlockMode::GCM)
3655                                              .Padding(PaddingMode::NONE)
3656                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3657 
3658     string message = "123456789012345678901234567890123456";
3659     auto begin_params = AuthorizationSetBuilder()
3660                             .BlockMode(BlockMode::GCM)
3661                             .Padding(PaddingMode::NONE)
3662                             .Authorization(TAG_MAC_LENGTH, 128);
3663     AuthorizationSet begin_out_params;
3664 
3665     auto update_params =
3666         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foo", (size_t)3);
3667 
3668     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3669 
3670     // No data, AAD only.
3671     string ciphertext;
3672     size_t input_consumed;
3673     AuthorizationSet update_out_params;
3674     EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, "" /* input */, &update_out_params,
3675                                     &ciphertext, &input_consumed));
3676     EXPECT_EQ(0U, input_consumed);
3677     EXPECT_EQ(0U, ciphertext.size());
3678     EXPECT_TRUE(update_out_params.empty());
3679 
3680     // AAD and data.
3681     EXPECT_EQ(ErrorCode::OK, Update(op_handle_, update_params, message, &update_out_params,
3682                                     &ciphertext, &input_consumed));
3683     EXPECT_EQ(message.size(), input_consumed);
3684     EXPECT_EQ(message.size(), ciphertext.size());
3685     EXPECT_TRUE(update_out_params.empty());
3686 
3687     // More AAD
3688     EXPECT_EQ(ErrorCode::INVALID_TAG, Update(op_handle_, update_params, "", &update_out_params,
3689                                              &ciphertext, &input_consumed));
3690 
3691     op_handle_ = kOpHandleSentinel;
3692 }
3693 
3694 /*
3695  * EncryptionOperationsTest.AesGcmBadAad
3696  *
3697  * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
3698  */
TEST_P(EncryptionOperationsTest,AesGcmBadAad)3699 TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
3700     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3701                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3702                                              .AesEncryptionKey(128)
3703                                              .BlockMode(BlockMode::GCM)
3704                                              .Padding(PaddingMode::NONE)
3705                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3706 
3707     string message = "12345678901234567890123456789012";
3708     auto begin_params = AuthorizationSetBuilder()
3709                             .BlockMode(BlockMode::GCM)
3710                             .Padding(PaddingMode::NONE)
3711                             .Authorization(TAG_MAC_LENGTH, 128);
3712 
3713     auto finish_params =
3714         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6);
3715 
3716     // Encrypt
3717     AuthorizationSet begin_out_params;
3718     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3719     string ciphertext;
3720     AuthorizationSet finish_out_params;
3721     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3722                                     &finish_out_params, &ciphertext));
3723 
3724     // Grab nonce
3725     begin_params.push_back(begin_out_params);
3726 
3727     finish_params = AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA,
3728                                                             "barfoo" /* Wrong AAD */, (size_t)6);
3729 
3730     // Decrypt.
3731     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
3732     string plaintext;
3733     EXPECT_EQ(ErrorCode::VERIFICATION_FAILED,
3734               Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params,
3735                      &plaintext));
3736 }
3737 
3738 /*
3739  * EncryptionOperationsTest.AesGcmWrongNonce
3740  *
3741  * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
3742  */
TEST_P(EncryptionOperationsTest,AesGcmWrongNonce)3743 TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
3744     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3745                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3746                                              .AesEncryptionKey(128)
3747                                              .BlockMode(BlockMode::GCM)
3748                                              .Padding(PaddingMode::NONE)
3749                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3750 
3751     string message = "12345678901234567890123456789012";
3752     auto begin_params = AuthorizationSetBuilder()
3753                             .BlockMode(BlockMode::GCM)
3754                             .Padding(PaddingMode::NONE)
3755                             .Authorization(TAG_MAC_LENGTH, 128);
3756 
3757     auto finish_params =
3758         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, "foobar", (size_t)6);
3759 
3760     // Encrypt
3761     AuthorizationSet begin_out_params;
3762     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3763     string ciphertext;
3764     AuthorizationSet finish_out_params;
3765     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3766                                     &finish_out_params, &ciphertext));
3767 
3768     // Wrong nonce
3769     begin_params.push_back(TAG_NONCE, HidlBuf("123456789012"));
3770 
3771     // Decrypt.
3772     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
3773     string plaintext;
3774     EXPECT_EQ(ErrorCode::VERIFICATION_FAILED,
3775               Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params,
3776                      &plaintext));
3777 
3778     // With wrong nonce, should have gotten garbage plaintext (or none).
3779     EXPECT_NE(message, plaintext);
3780 }
3781 
3782 /*
3783  * EncryptionOperationsTest.AesGcmCorruptTag
3784  *
3785  * Verifies that AES GCM decryption fails correctly when the tag is wrong.
3786  */
TEST_P(EncryptionOperationsTest,AesGcmCorruptTag)3787 TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
3788     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3789                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3790                                              .AesEncryptionKey(128)
3791                                              .BlockMode(BlockMode::GCM)
3792                                              .Padding(PaddingMode::NONE)
3793                                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3794 
3795     string aad = "1234567890123456";
3796     string message = "123456789012345678901234567890123456";
3797 
3798     auto params = AuthorizationSetBuilder()
3799                       .BlockMode(BlockMode::GCM)
3800                       .Padding(PaddingMode::NONE)
3801                       .Authorization(TAG_MAC_LENGTH, 128);
3802 
3803     auto finish_params =
3804         AuthorizationSetBuilder().Authorization(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3805 
3806     // Encrypt
3807     AuthorizationSet begin_out_params;
3808     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3809     string ciphertext;
3810     AuthorizationSet finish_out_params;
3811     EXPECT_EQ(ErrorCode::OK, Finish(op_handle_, finish_params, message, "" /* signature */,
3812                                     &finish_out_params, &ciphertext));
3813     EXPECT_TRUE(finish_out_params.empty());
3814 
3815     // Corrupt tag
3816     ++(*ciphertext.rbegin());
3817 
3818     // Grab nonce
3819     params.push_back(begin_out_params);
3820 
3821     // Decrypt.
3822     EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3823     string plaintext;
3824     EXPECT_EQ(ErrorCode::VERIFICATION_FAILED,
3825               Finish(op_handle_, finish_params, ciphertext, "" /* signature */, &finish_out_params,
3826                      &plaintext));
3827     EXPECT_TRUE(finish_out_params.empty());
3828 }
3829 
3830 typedef KeymasterHidlTest MaxOperationsTest;
3831 
3832 /*
3833  * MaxOperationsTest.TestLimitAes
3834  *
3835  * Verifies that the max uses per boot tag works correctly with AES keys.
3836  */
TEST_P(MaxOperationsTest,TestLimitAes)3837 TEST_P(MaxOperationsTest, TestLimitAes) {
3838     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3839                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3840                                              .AesEncryptionKey(128)
3841                                              .EcbMode()
3842                                              .Padding(PaddingMode::NONE)
3843                                              .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3844 
3845     string message = "1234567890123456";
3846 
3847     auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
3848 
3849     EncryptMessage(message, params);
3850     EncryptMessage(message, params);
3851     EncryptMessage(message, params);
3852 
3853     // Fourth time should fail.
3854     EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
3855 }
3856 
3857 /*
3858  * MaxOperationsTest.TestLimitAes
3859  *
3860  * Verifies that the max uses per boot tag works correctly with RSA keys.
3861  */
TEST_P(MaxOperationsTest,TestLimitRsa)3862 TEST_P(MaxOperationsTest, TestLimitRsa) {
3863     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3864                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3865                                              .RsaSigningKey(1024, 3)
3866                                              .NoDigestOrPadding()
3867                                              .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3868 
3869     string message = "1234567890123456";
3870 
3871     auto params = AuthorizationSetBuilder().NoDigestOrPadding();
3872 
3873     SignMessage(message, params);
3874     SignMessage(message, params);
3875     SignMessage(message, params);
3876 
3877     // Fourth time should fail.
3878     EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
3879 }
3880 
3881 typedef KeymasterHidlTest AddEntropyTest;
3882 
3883 /*
3884  * AddEntropyTest.AddEntropy
3885  *
3886  * Verifies that the addRngEntropy method doesn't blow up.  There's no way to test that entropy is
3887  * actually added.
3888  */
TEST_P(AddEntropyTest,AddEntropy)3889 TEST_P(AddEntropyTest, AddEntropy) {
3890     EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf("foo")));
3891 }
3892 
3893 /*
3894  * AddEntropyTest.AddEmptyEntropy
3895  *
3896  * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
3897  */
TEST_P(AddEntropyTest,AddEmptyEntropy)3898 TEST_P(AddEntropyTest, AddEmptyEntropy) {
3899     EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf()));
3900 }
3901 
3902 /*
3903  * AddEntropyTest.AddLargeEntropy
3904  *
3905  * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
3906  */
TEST_P(AddEntropyTest,AddLargeEntropy)3907 TEST_P(AddEntropyTest, AddLargeEntropy) {
3908     EXPECT_EQ(ErrorCode::OK, keymaster().addRngEntropy(HidlBuf(string(2 * 1024, 'a'))));
3909 }
3910 
3911 typedef KeymasterHidlTest AttestationTest;
3912 
3913 /*
3914  * AttestationTest.RsaAttestation
3915  *
3916  * Verifies that attesting to RSA keys works and generates the expected output.
3917  */
TEST_P(AttestationTest,RsaAttestation)3918 TEST_P(AttestationTest, RsaAttestation) {
3919     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3920                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3921                                              .RsaSigningKey(1024, 3)
3922                                              .Digest(Digest::NONE)
3923                                              .Padding(PaddingMode::NONE)
3924                                              .Authorization(TAG_INCLUDE_UNIQUE_ID)));
3925 
3926     hidl_vec<hidl_vec<uint8_t>> cert_chain;
3927     ASSERT_EQ(ErrorCode::OK,
3928               AttestKey(AuthorizationSetBuilder()
3929                             .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
3930                             .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
3931                         &cert_chain));
3932     EXPECT_GE(cert_chain.size(), 2U);
3933     EXPECT_TRUE(verify_chain(cert_chain));
3934     EXPECT_TRUE(
3935         verify_attestation_record("challenge", "foo",                     //
3936                                   key_characteristics_.softwareEnforced,  //
3937                                   key_characteristics_.teeEnforced,       //
3938                                   cert_chain[0]));
3939 }
3940 
3941 /*
3942  * AttestationTest.RsaAttestationRequiresAppId
3943  *
3944  * Verifies that attesting to RSA requires app ID.
3945  */
TEST_P(AttestationTest,RsaAttestationRequiresAppId)3946 TEST_P(AttestationTest, RsaAttestationRequiresAppId) {
3947     ASSERT_EQ(ErrorCode::OK,
3948               GenerateKey(AuthorizationSetBuilder()
3949                               .Authorization(TAG_NO_AUTH_REQUIRED)
3950                               .RsaSigningKey(1024, 3)
3951                               .Digest(Digest::NONE)
3952                               .Padding(PaddingMode::NONE)
3953                               .Authorization(TAG_INCLUDE_UNIQUE_ID)));
3954 
3955     hidl_vec<hidl_vec<uint8_t>> cert_chain;
3956     EXPECT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
3957               AttestKey(AuthorizationSetBuilder().Authorization(
3958                             TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge")),
3959                         &cert_chain));
3960 }
3961 
3962 /*
3963  * AttestationTest.EcAttestation
3964  *
3965  * Verifies that attesting to EC keys works and generates the expected output.
3966  */
TEST_P(AttestationTest,EcAttestation)3967 TEST_P(AttestationTest, EcAttestation) {
3968     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3969                                              .Authorization(TAG_NO_AUTH_REQUIRED)
3970                                              .EcdsaSigningKey(EcCurve::P_256)
3971                                              .Digest(Digest::SHA_2_256)
3972                                              .Authorization(TAG_INCLUDE_UNIQUE_ID)));
3973 
3974     hidl_vec<hidl_vec<uint8_t>> cert_chain;
3975     ASSERT_EQ(ErrorCode::OK,
3976               AttestKey(AuthorizationSetBuilder()
3977                             .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
3978                             .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
3979                         &cert_chain));
3980     EXPECT_GE(cert_chain.size(), 2U);
3981     EXPECT_TRUE(verify_chain(cert_chain));
3982 
3983     EXPECT_TRUE(
3984         verify_attestation_record("challenge", "foo",                     //
3985                                   key_characteristics_.softwareEnforced,  //
3986                                   key_characteristics_.teeEnforced,       //
3987                                   cert_chain[0]));
3988 }
3989 
3990 /*
3991  * AttestationTest.EcAttestationRequiresAttestationAppId
3992  *
3993  * Verifies that attesting to EC keys requires app ID
3994  */
TEST_P(AttestationTest,EcAttestationRequiresAttestationAppId)3995 TEST_P(AttestationTest, EcAttestationRequiresAttestationAppId) {
3996     ASSERT_EQ(ErrorCode::OK,
3997               GenerateKey(AuthorizationSetBuilder()
3998                               .Authorization(TAG_NO_AUTH_REQUIRED)
3999                               .EcdsaSigningKey(EcCurve::P_256)
4000                               .Digest(Digest::SHA_2_256)
4001                               .Authorization(TAG_INCLUDE_UNIQUE_ID)));
4002 
4003     hidl_vec<hidl_vec<uint8_t>> cert_chain;
4004     EXPECT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
4005               AttestKey(AuthorizationSetBuilder().Authorization(
4006                             TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge")),
4007                         &cert_chain));
4008 }
4009 
4010 /*
4011  * AttestationTest.AesAttestation
4012  *
4013  * Verifies that attesting to AES keys fails in the expected way.
4014  */
TEST_P(AttestationTest,AesAttestation)4015 TEST_P(AttestationTest, AesAttestation) {
4016     ASSERT_EQ(ErrorCode::OK,
4017               GenerateKey(AuthorizationSetBuilder()
4018                               .Authorization(TAG_NO_AUTH_REQUIRED)
4019                               .AesEncryptionKey(128)
4020                               .EcbMode()
4021                               .Padding(PaddingMode::PKCS7)));
4022 
4023     hidl_vec<hidl_vec<uint8_t>> cert_chain;
4024     EXPECT_EQ(
4025         ErrorCode::INCOMPATIBLE_ALGORITHM,
4026         AttestKey(
4027             AuthorizationSetBuilder()
4028                 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
4029                 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
4030             &cert_chain));
4031 }
4032 
4033 /*
4034  * AttestationTest.HmacAttestation
4035  *
4036  * Verifies that attesting to HMAC keys fails in the expected way.
4037  */
TEST_P(AttestationTest,HmacAttestation)4038 TEST_P(AttestationTest, HmacAttestation) {
4039     ASSERT_EQ(ErrorCode::OK,
4040               GenerateKey(AuthorizationSetBuilder()
4041                               .Authorization(TAG_NO_AUTH_REQUIRED)
4042                               .HmacKey(128)
4043                               .EcbMode()
4044                               .Digest(Digest::SHA_2_256)
4045                               .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4046 
4047     hidl_vec<hidl_vec<uint8_t>> cert_chain;
4048     EXPECT_EQ(
4049         ErrorCode::INCOMPATIBLE_ALGORITHM,
4050         AttestKey(
4051             AuthorizationSetBuilder()
4052                 .Authorization(TAG_ATTESTATION_CHALLENGE, HidlBuf("challenge"))
4053                 .Authorization(TAG_ATTESTATION_APPLICATION_ID, HidlBuf("foo")),
4054             &cert_chain));
4055 }
4056 
4057 typedef KeymasterHidlTest KeyDeletionTest;
4058 
4059 /**
4060  * KeyDeletionTest.DeleteKey
4061  *
4062  * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
4063  * valid key blob.
4064  */
TEST_P(KeyDeletionTest,DeleteKey)4065 TEST_P(KeyDeletionTest, DeleteKey) {
4066     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4067                                              .RsaSigningKey(1024, 3)
4068                                              .Digest(Digest::NONE)
4069                                              .Padding(PaddingMode::NONE)
4070                                              .Authorization(TAG_NO_AUTH_REQUIRED)));
4071 
4072     // Delete must work if rollback protection is implemented
4073     AuthorizationSet teeEnforced(key_characteristics_.teeEnforced);
4074     bool rollback_protected = teeEnforced.Contains(TAG_ROLLBACK_RESISTANT);
4075 
4076     if (rollback_protected) {
4077         ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
4078     } else {
4079         auto delete_result = DeleteKey(true /* keep key blob */);
4080         ASSERT_TRUE(delete_result == ErrorCode::OK | delete_result == ErrorCode::UNIMPLEMENTED);
4081     }
4082 
4083     string message = "12345678901234567890123456789012";
4084     AuthorizationSet begin_out_params;
4085 
4086     if (rollback_protected) {
4087         EXPECT_EQ(
4088             ErrorCode::INVALID_KEY_BLOB,
4089             Begin(KeyPurpose::SIGN, key_blob_, AuthorizationSetBuilder()
4090                                                    .Digest(Digest::NONE)
4091                                                    .Padding(PaddingMode::NONE),
4092                   &begin_out_params, &op_handle_))
4093             << " (Possibly b/37623742)";
4094     } else {
4095         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_,
4096                                        AuthorizationSetBuilder()
4097                                            .Digest(Digest::NONE)
4098                                            .Padding(PaddingMode::NONE),
4099                                        &begin_out_params, &op_handle_));
4100     }
4101     AbortIfNeeded();
4102     key_blob_ = HidlBuf();
4103 }
4104 
4105 /**
4106  * KeyDeletionTest.DeleteInvalidKey
4107  *
4108  * This test checks that the HAL excepts invalid key blobs.
4109  */
TEST_P(KeyDeletionTest,DeleteInvalidKey)4110 TEST_P(KeyDeletionTest, DeleteInvalidKey) {
4111     // Generate key just to check if rollback protection is implemented
4112     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4113                                              .RsaSigningKey(1024, 3)
4114                                              .Digest(Digest::NONE)
4115                                              .Padding(PaddingMode::NONE)
4116                                              .Authorization(TAG_NO_AUTH_REQUIRED)));
4117 
4118     // Delete must work if rollback protection is implemented
4119     AuthorizationSet teeEnforced(key_characteristics_.teeEnforced);
4120     bool rollback_protected = teeEnforced.Contains(TAG_ROLLBACK_RESISTANT);
4121 
4122     // Delete the key we don't care about the result at this point.
4123     DeleteKey();
4124 
4125     // Now create an invalid key blob and delete it.
4126     key_blob_ = HidlBuf("just some garbage data which is not a valid key blob");
4127 
4128     if (rollback_protected) {
4129         ASSERT_EQ(ErrorCode::OK, DeleteKey());
4130     } else {
4131         auto delete_result = DeleteKey();
4132         ASSERT_TRUE(delete_result == ErrorCode::OK | delete_result == ErrorCode::UNIMPLEMENTED);
4133     }
4134 }
4135 
4136 /**
4137  * KeyDeletionTest.DeleteAllKeys
4138  *
4139  * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
4140  *
4141  * BEWARE: This test has serious side effects. All user keys will be lost! This includes
4142  * FBE/FDE encryption keys, which means that the device will not even boot until after the
4143  * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
4144  * been provisioned. Use this test only on dedicated testing devices that have no valuable
4145  * credentials stored in Keystore/Keymaster.
4146  */
TEST_P(KeyDeletionTest,DeleteAllKeys)4147 TEST_P(KeyDeletionTest, DeleteAllKeys) {
4148     if (!arm_deleteAllKeys) return;
4149     ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4150                                              .RsaSigningKey(1024, 3)
4151                                              .Digest(Digest::NONE)
4152                                              .Padding(PaddingMode::NONE)
4153                                              .Authorization(TAG_NO_AUTH_REQUIRED)));
4154 
4155     // Delete must work if rollback protection is implemented
4156     AuthorizationSet teeEnforced(key_characteristics_.teeEnforced);
4157     bool rollback_protected = teeEnforced.Contains(TAG_ROLLBACK_RESISTANT);
4158 
4159     ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
4160 
4161     string message = "12345678901234567890123456789012";
4162     AuthorizationSet begin_out_params;
4163 
4164     if (rollback_protected) {
4165         EXPECT_EQ(
4166             ErrorCode::INVALID_KEY_BLOB,
4167             Begin(KeyPurpose::SIGN, key_blob_, AuthorizationSetBuilder()
4168                                                    .Digest(Digest::NONE)
4169                                                    .Padding(PaddingMode::NONE),
4170                   &begin_out_params, &op_handle_));
4171     } else {
4172         EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_,
4173                                        AuthorizationSetBuilder()
4174                                            .Digest(Digest::NONE)
4175                                            .Padding(PaddingMode::NONE),
4176                                        &begin_out_params, &op_handle_));
4177     }
4178     AbortIfNeeded();
4179     key_blob_ = HidlBuf();
4180 }
4181 
4182 static const auto kKeymasterDeviceChoices =
4183         testing::ValuesIn(android::hardware::getAllHalInstanceNames(IKeymasterDevice::descriptor));
4184 
4185 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NewKeyGenerationTest);
4186 INSTANTIATE_TEST_SUITE_P(PerInstance, NewKeyGenerationTest, kKeymasterDeviceChoices,
4187                          android::hardware::PrintInstanceNameToString);
4188 
4189 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(KeymasterVersionTest);
4190 INSTANTIATE_TEST_SUITE_P(PerInstance, KeymasterVersionTest, kKeymasterDeviceChoices,
4191                          android::hardware::PrintInstanceNameToString);
4192 
4193 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(GetKeyCharacteristicsTest);
4194 INSTANTIATE_TEST_SUITE_P(PerInstance, GetKeyCharacteristicsTest, kKeymasterDeviceChoices,
4195                          android::hardware::PrintInstanceNameToString);
4196 
4197 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(SigningOperationsTest);
4198 INSTANTIATE_TEST_SUITE_P(PerInstance, SigningOperationsTest, kKeymasterDeviceChoices,
4199                          android::hardware::PrintInstanceNameToString);
4200 
4201 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(VerificationOperationsTest);
4202 INSTANTIATE_TEST_SUITE_P(PerInstance, VerificationOperationsTest, kKeymasterDeviceChoices,
4203                          android::hardware::PrintInstanceNameToString);
4204 
4205 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(ExportKeyTest);
4206 INSTANTIATE_TEST_SUITE_P(PerInstance, ExportKeyTest, kKeymasterDeviceChoices,
4207                          android::hardware::PrintInstanceNameToString);
4208 
4209 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(ImportKeyTest);
4210 INSTANTIATE_TEST_SUITE_P(PerInstance, ImportKeyTest, kKeymasterDeviceChoices,
4211                          android::hardware::PrintInstanceNameToString);
4212 
4213 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(EncryptionOperationsTest);
4214 INSTANTIATE_TEST_SUITE_P(PerInstance, EncryptionOperationsTest, kKeymasterDeviceChoices,
4215                          android::hardware::PrintInstanceNameToString);
4216 
4217 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(MaxOperationsTest);
4218 INSTANTIATE_TEST_SUITE_P(PerInstance, MaxOperationsTest, kKeymasterDeviceChoices,
4219                          android::hardware::PrintInstanceNameToString);
4220 
4221 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(AddEntropyTest);
4222 INSTANTIATE_TEST_SUITE_P(PerInstance, AddEntropyTest, kKeymasterDeviceChoices,
4223                          android::hardware::PrintInstanceNameToString);
4224 
4225 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(AttestationTest);
4226 INSTANTIATE_TEST_SUITE_P(PerInstance, AttestationTest, kKeymasterDeviceChoices,
4227                          android::hardware::PrintInstanceNameToString);
4228 
4229 GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(KeyDeletionTest);
4230 INSTANTIATE_TEST_SUITE_P(PerInstance, KeyDeletionTest, kKeymasterDeviceChoices,
4231                          android::hardware::PrintInstanceNameToString);
4232 
4233 }  // namespace test
4234 }  // namespace V3_0
4235 }  // namespace keymaster
4236 }  // namespace hardware
4237 }  // namespace android
4238 
main(int argc,char ** argv)4239 int main(int argc, char** argv) {
4240     ::testing::InitGoogleTest(&argc, argv);
4241     for (int i = 1; i < argc; ++i) {
4242         if (argv[i][0] == '-') {
4243             if (std::string(argv[i]) == "--arm_deleteAllKeys") {
4244                 arm_deleteAllKeys = true;
4245             }
4246             if (std::string(argv[i]) == "--dump_attestations") {
4247                 dump_Attestations = true;
4248             }
4249         }
4250     }
4251     int status = RUN_ALL_TESTS();
4252     ALOGI("Test result = %d", status);
4253     return status;
4254 }
4255