Home | History | Annotate | Download | only in keymaster
      1 /*
      2  * Copyright (C) 2014 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 #include <fstream>
     18 #include <string>
     19 #include <vector>
     20 
     21 #include <openssl/evp.h>
     22 #include <openssl/x509.h>
     23 
     24 #include <hardware/keymaster0.h>
     25 #include <keymaster/key_factory.h>
     26 #include <keymaster/soft_keymaster_context.h>
     27 #include <keymaster/soft_keymaster_device.h>
     28 #include <keymaster/softkeymaster.h>
     29 
     30 #include "android_keymaster_test_utils.h"
     31 #include "attestation_record.h"
     32 #include "keymaster0_engine.h"
     33 #include "openssl_utils.h"
     34 
     35 using std::ifstream;
     36 using std::istreambuf_iterator;
     37 using std::ofstream;
     38 using std::string;
     39 using std::unique_ptr;
     40 using std::vector;
     41 
     42 extern "C" {
     43 int __android_log_print(int prio, const char* tag, const char* fmt);
     44 int __android_log_print(int prio, const char* tag, const char* fmt) {
     45     (void)prio, (void)tag, (void)fmt;
     46     return 0;
     47 }
     48 }  // extern "C"
     49 
     50 namespace keymaster {
     51 namespace test {
     52 
     53 const uint32_t kOsVersion = 060000;
     54 const uint32_t kOsPatchLevel = 201603;
     55 
     56 StdoutLogger logger;
     57 
     58 template <typename T> vector<T> make_vector(const T* array, size_t len) {
     59     return vector<T>(array, array + len);
     60 }
     61 
     62 /**
     63  * KeymasterEnforcement class for use in testing.  It's permissive in the sense that it doesn't
     64  * check cryptoperiods, but restrictive in the sense that the clock never advances (so rate-limited
     65  * keys will only work once).
     66  */
     67 class TestKeymasterEnforcement : public KeymasterEnforcement {
     68   public:
     69     TestKeymasterEnforcement() : KeymasterEnforcement(3, 3) {}
     70 
     71     virtual bool activation_date_valid(uint64_t /* activation_date */) const { return true; }
     72     virtual bool expiration_date_passed(uint64_t /* expiration_date */) const { return false; }
     73     virtual bool auth_token_timed_out(const hw_auth_token_t& /* token */,
     74                                       uint32_t /* timeout */) const {
     75         return false;
     76     }
     77     virtual uint32_t get_current_time() const { return 0; }
     78     virtual bool ValidateTokenSignature(const hw_auth_token_t& /* token */) const { return true; }
     79 };
     80 
     81 /**
     82  * Variant of SoftKeymasterContext that provides a TestKeymasterEnforcement.
     83  */
     84 class TestKeymasterContext : public SoftKeymasterContext {
     85   public:
     86     TestKeymasterContext() {}
     87     TestKeymasterContext(const string& root_of_trust) : SoftKeymasterContext(root_of_trust) {}
     88 
     89     KeymasterEnforcement* enforcement_policy() override { return &test_policy_; }
     90 
     91   private:
     92     TestKeymasterEnforcement test_policy_;
     93 };
     94 
     95 /**
     96  * Test instance creator that builds a pure software keymaster2 implementation.
     97  */
     98 class SoftKeymasterTestInstanceCreator : public Keymaster2TestInstanceCreator {
     99   public:
    100     keymaster2_device_t* CreateDevice() const override {
    101         std::cerr << "Creating software-only device" << std::endl;
    102         context_ = new TestKeymasterContext;
    103         SoftKeymasterDevice* device = new SoftKeymasterDevice(context_);
    104         AuthorizationSet version_info(AuthorizationSetBuilder()
    105                                           .Authorization(TAG_OS_VERSION, kOsVersion)
    106                                           .Authorization(TAG_OS_PATCHLEVEL, kOsPatchLevel));
    107         device->keymaster2_device()->configure(device->keymaster2_device(), &version_info);
    108         return device->keymaster2_device();
    109     }
    110 
    111     bool algorithm_in_km0_hardware(keymaster_algorithm_t) const override { return false; }
    112     int keymaster0_calls() const override { return 0; }
    113     bool is_keymaster1_hw() const override { return false; }
    114     KeymasterContext* keymaster_context() const override { return context_; }
    115 
    116   private:
    117     mutable TestKeymasterContext* context_;
    118 };
    119 
    120 /**
    121  * Test instance creator that builds keymaster1 instances which wrap a faked hardware keymaster0
    122  * instance, with or without EC support.
    123  */
    124 class Keymaster0AdapterTestInstanceCreator : public Keymaster2TestInstanceCreator {
    125   public:
    126     Keymaster0AdapterTestInstanceCreator(bool support_ec) : support_ec_(support_ec) {}
    127 
    128     keymaster2_device_t* CreateDevice() const {
    129         std::cerr << "Creating keymaster0-backed device (with ec: " << std::boolalpha << support_ec_
    130                   << ")." << std::endl;
    131         hw_device_t* softkeymaster_device;
    132         EXPECT_EQ(0, openssl_open(&softkeymaster_module.common, KEYSTORE_KEYMASTER,
    133                                   &softkeymaster_device));
    134         // Make the software device pretend to be hardware
    135         keymaster0_device_t* keymaster0_device =
    136             reinterpret_cast<keymaster0_device_t*>(softkeymaster_device);
    137         keymaster0_device->flags &= ~KEYMASTER_SOFTWARE_ONLY;
    138 
    139         if (!support_ec_) {
    140             // Make the software device pretend not to support EC
    141             keymaster0_device->flags &= ~KEYMASTER_SUPPORTS_EC;
    142         }
    143 
    144         counting_keymaster0_device_ = new Keymaster0CountingWrapper(keymaster0_device);
    145 
    146         context_ = new TestKeymasterContext;
    147         SoftKeymasterDevice* keymaster = new SoftKeymasterDevice(context_);
    148         keymaster->SetHardwareDevice(counting_keymaster0_device_);
    149         AuthorizationSet version_info(AuthorizationSetBuilder()
    150                                           .Authorization(TAG_OS_VERSION, kOsVersion)
    151                                           .Authorization(TAG_OS_PATCHLEVEL, kOsPatchLevel));
    152         keymaster->keymaster2_device()->configure(keymaster->keymaster2_device(), &version_info);
    153         return keymaster->keymaster2_device();
    154     }
    155 
    156     bool algorithm_in_km0_hardware(keymaster_algorithm_t algorithm) const override {
    157         switch (algorithm) {
    158         case KM_ALGORITHM_RSA:
    159             return true;
    160         case KM_ALGORITHM_EC:
    161             return support_ec_;
    162         default:
    163             return false;
    164         }
    165     }
    166     int keymaster0_calls() const override { return counting_keymaster0_device_->count(); }
    167     bool is_keymaster1_hw() const override { return false; }
    168     KeymasterContext* keymaster_context() const override { return context_; }
    169 
    170   private:
    171     mutable TestKeymasterContext* context_;
    172     mutable Keymaster0CountingWrapper* counting_keymaster0_device_;
    173     bool support_ec_;
    174 };
    175 
    176 /**
    177  * Test instance creator that builds a SoftKeymasterDevice which wraps a fake hardware keymaster1
    178  * instance, with minimal digest support.
    179  */
    180 class Sha256OnlyKeymaster2TestInstanceCreator : public Keymaster2TestInstanceCreator {
    181     keymaster2_device_t* CreateDevice() const {
    182         std::cerr << "Creating keymaster1-backed device that supports only SHA256";
    183 
    184         // fake_device doesn't leak because device (below) takes ownership of it.
    185         keymaster1_device_t* fake_device = make_device_sha256_only(
    186             (new SoftKeymasterDevice(new TestKeymasterContext("PseudoHW")))->keymaster_device());
    187 
    188         // device doesn't leak; it's cleaned up by device->keymaster_device()->common.close().
    189         context_ = new TestKeymasterContext;
    190         SoftKeymasterDevice* device = new SoftKeymasterDevice(context_);
    191         device->SetHardwareDevice(fake_device);
    192 
    193         AuthorizationSet version_info(AuthorizationSetBuilder()
    194                                           .Authorization(TAG_OS_VERSION, kOsVersion)
    195                                           .Authorization(TAG_OS_PATCHLEVEL, kOsPatchLevel));
    196         device->keymaster2_device()->configure(device->keymaster2_device(), &version_info);
    197         return device->keymaster2_device();
    198     }
    199 
    200     bool algorithm_in_km0_hardware(keymaster_algorithm_t) const override { return false; }
    201     int keymaster0_calls() const override { return 0; }
    202     int minimal_digest_set() const override { return true; }
    203     bool is_keymaster1_hw() const override { return true; }
    204     KeymasterContext* keymaster_context() const override { return context_; }
    205 
    206   private:
    207     mutable TestKeymasterContext* context_;
    208 };
    209 
    210 static auto test_params = testing::Values(
    211     InstanceCreatorPtr(new SoftKeymasterTestInstanceCreator),
    212     InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(true /* support_ec */)),
    213     InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(false /* support_ec */)),
    214     InstanceCreatorPtr(new Sha256OnlyKeymaster2TestInstanceCreator));
    215 
    216 class NewKeyGeneration : public Keymaster2Test {
    217   protected:
    218     void CheckBaseParams() {
    219         AuthorizationSet auths = sw_enforced();
    220         EXPECT_GT(auths.SerializedSize(), 12U);
    221 
    222         EXPECT_TRUE(contains(auths, TAG_PURPOSE, KM_PURPOSE_SIGN));
    223         EXPECT_TRUE(contains(auths, TAG_PURPOSE, KM_PURPOSE_VERIFY));
    224         EXPECT_TRUE(contains(auths, TAG_USER_ID, 7));
    225         EXPECT_TRUE(contains(auths, TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD));
    226         EXPECT_TRUE(contains(auths, TAG_AUTH_TIMEOUT, 300));
    227 
    228         // Verify that App ID, App data and ROT are NOT included.
    229         EXPECT_FALSE(contains(auths, TAG_ROOT_OF_TRUST));
    230         EXPECT_FALSE(contains(auths, TAG_APPLICATION_ID));
    231         EXPECT_FALSE(contains(auths, TAG_APPLICATION_DATA));
    232 
    233         // Just for giggles, check that some unexpected tags/values are NOT present.
    234         EXPECT_FALSE(contains(auths, TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
    235         EXPECT_FALSE(contains(auths, TAG_PURPOSE, KM_PURPOSE_DECRYPT));
    236         EXPECT_FALSE(contains(auths, TAG_AUTH_TIMEOUT, 301));
    237 
    238         // Now check that unspecified, defaulted tags are correct.
    239         EXPECT_TRUE(contains(auths, KM_TAG_CREATION_DATETIME));
    240         if (GetParam()->is_keymaster1_hw()) {
    241             // If the underlying (faked) HW is KM1, it will not have version info.
    242             EXPECT_FALSE(auths.Contains(TAG_OS_VERSION));
    243             EXPECT_FALSE(auths.Contains(TAG_OS_PATCHLEVEL));
    244         } else {
    245             // In all othe cases; SoftKeymasterDevice keys, or keymaster0 keys wrapped by
    246             // SoftKeymasterDevice, version information will be present and up to date.
    247             EXPECT_TRUE(contains(auths, TAG_OS_VERSION, kOsVersion));
    248             EXPECT_TRUE(contains(auths, TAG_OS_PATCHLEVEL, kOsPatchLevel));
    249         }
    250     }
    251 };
    252 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, NewKeyGeneration, test_params);
    253 
    254 TEST_P(NewKeyGeneration, Rsa) {
    255     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    256                                            .RsaSigningKey(256, 3)
    257                                            .Digest(KM_DIGEST_NONE)
    258                                            .Padding(KM_PAD_NONE)));
    259     CheckBaseParams();
    260 
    261     // Check specified tags are all present, and in the right set.
    262     AuthorizationSet crypto_params;
    263     AuthorizationSet non_crypto_params;
    264     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA)) {
    265         EXPECT_NE(0U, hw_enforced().size());
    266         EXPECT_NE(0U, sw_enforced().size());
    267         crypto_params.push_back(hw_enforced());
    268         non_crypto_params.push_back(sw_enforced());
    269     } else {
    270         EXPECT_EQ(0U, hw_enforced().size());
    271         EXPECT_NE(0U, sw_enforced().size());
    272         crypto_params.push_back(sw_enforced());
    273     }
    274 
    275     EXPECT_TRUE(contains(crypto_params, TAG_ALGORITHM, KM_ALGORITHM_RSA));
    276     EXPECT_FALSE(contains(non_crypto_params, TAG_ALGORITHM, KM_ALGORITHM_RSA));
    277     EXPECT_TRUE(contains(crypto_params, TAG_KEY_SIZE, 256));
    278     EXPECT_FALSE(contains(non_crypto_params, TAG_KEY_SIZE, 256));
    279     EXPECT_TRUE(contains(crypto_params, TAG_RSA_PUBLIC_EXPONENT, 3));
    280     EXPECT_FALSE(contains(non_crypto_params, TAG_RSA_PUBLIC_EXPONENT, 3));
    281 
    282     EXPECT_EQ(KM_ERROR_OK, DeleteKey());
    283 
    284     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    285         EXPECT_EQ(2, GetParam()->keymaster0_calls());
    286 }
    287 
    288 TEST_P(NewKeyGeneration, RsaDefaultSize) {
    289     ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
    290               GenerateKey(AuthorizationSetBuilder()
    291                               .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA)
    292                               .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3)
    293                               .SigningKey()));
    294 
    295     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    296 }
    297 
    298 TEST_P(NewKeyGeneration, Ecdsa) {
    299     ASSERT_EQ(KM_ERROR_OK,
    300               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
    301     CheckBaseParams();
    302 
    303     // Check specified tags are all present, and in the right set.
    304     AuthorizationSet crypto_params;
    305     AuthorizationSet non_crypto_params;
    306     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC)) {
    307         EXPECT_NE(0U, hw_enforced().size());
    308         EXPECT_NE(0U, sw_enforced().size());
    309         crypto_params.push_back(hw_enforced());
    310         non_crypto_params.push_back(sw_enforced());
    311     } else {
    312         EXPECT_EQ(0U, hw_enforced().size());
    313         EXPECT_NE(0U, sw_enforced().size());
    314         crypto_params.push_back(sw_enforced());
    315     }
    316 
    317     EXPECT_TRUE(contains(crypto_params, TAG_ALGORITHM, KM_ALGORITHM_EC));
    318     EXPECT_FALSE(contains(non_crypto_params, TAG_ALGORITHM, KM_ALGORITHM_EC));
    319     EXPECT_TRUE(contains(crypto_params, TAG_KEY_SIZE, 224));
    320     EXPECT_FALSE(contains(non_crypto_params, TAG_KEY_SIZE, 224));
    321 
    322     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
    323         EXPECT_EQ(1, GetParam()->keymaster0_calls());
    324 }
    325 
    326 TEST_P(NewKeyGeneration, EcdsaDefaultSize) {
    327     ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
    328               GenerateKey(AuthorizationSetBuilder()
    329                               .Authorization(TAG_ALGORITHM, KM_ALGORITHM_EC)
    330                               .SigningKey()
    331                               .Digest(KM_DIGEST_NONE)));
    332 
    333     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    334 }
    335 
    336 TEST_P(NewKeyGeneration, EcdsaInvalidSize) {
    337     ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
    338               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(KM_DIGEST_NONE)));
    339     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    340 }
    341 
    342 TEST_P(NewKeyGeneration, EcdsaMismatchKeySize) {
    343     ASSERT_EQ(KM_ERROR_INVALID_ARGUMENT,
    344               GenerateKey(AuthorizationSetBuilder()
    345                               .EcdsaSigningKey(224)
    346                               .Authorization(TAG_EC_CURVE, KM_EC_CURVE_P_256)
    347                               .Digest(KM_DIGEST_NONE)));
    348 }
    349 
    350 TEST_P(NewKeyGeneration, EcdsaAllValidSizes) {
    351     size_t valid_sizes[] = {224, 256, 384, 521};
    352     for (size_t size : valid_sizes) {
    353         EXPECT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(size).Digest(
    354                                    KM_DIGEST_NONE)))
    355             << "Failed to generate size: " << size;
    356     }
    357 
    358     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
    359         EXPECT_EQ(4, GetParam()->keymaster0_calls());
    360 }
    361 
    362 TEST_P(NewKeyGeneration, HmacSha256) {
    363     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    364                                            .HmacKey(128)
    365                                            .Digest(KM_DIGEST_SHA_2_256)
    366                                            .Authorization(TAG_MIN_MAC_LENGTH, 256)));
    367 
    368     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    369 }
    370 
    371 TEST_P(NewKeyGeneration, HmacMultipleDigests) {
    372     ASSERT_EQ(KM_ERROR_UNSUPPORTED_DIGEST,
    373               GenerateKey(AuthorizationSetBuilder()
    374                               .HmacKey(128)
    375                               .Digest(KM_DIGEST_SHA1)
    376                               .Digest(KM_DIGEST_SHA_2_256)
    377                               .Authorization(TAG_MIN_MAC_LENGTH, 128)));
    378 
    379     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    380 }
    381 
    382 TEST_P(NewKeyGeneration, HmacDigestNone) {
    383     ASSERT_EQ(KM_ERROR_UNSUPPORTED_DIGEST,
    384               GenerateKey(AuthorizationSetBuilder()
    385                               .HmacKey(128)
    386                               .Digest(KM_DIGEST_NONE)
    387                               .Authorization(TAG_MIN_MAC_LENGTH, 128)));
    388 
    389     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    390 }
    391 
    392 TEST_P(NewKeyGeneration, HmacSha256TooShortMacLength) {
    393     ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
    394               GenerateKey(AuthorizationSetBuilder()
    395                               .HmacKey(128)
    396                               .Digest(KM_DIGEST_SHA_2_256)
    397                               .Authorization(TAG_MIN_MAC_LENGTH, 48)));
    398 
    399     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    400 }
    401 
    402 TEST_P(NewKeyGeneration, HmacSha256NonIntegralOctetMacLength) {
    403     ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
    404               GenerateKey(AuthorizationSetBuilder()
    405                               .HmacKey(128)
    406                               .Digest(KM_DIGEST_SHA_2_256)
    407                               .Authorization(TAG_MIN_MAC_LENGTH, 130)));
    408 
    409     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    410 }
    411 
    412 TEST_P(NewKeyGeneration, HmacSha256TooLongMacLength) {
    413     ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
    414               GenerateKey(AuthorizationSetBuilder()
    415                               .HmacKey(128)
    416                               .Digest(KM_DIGEST_SHA_2_256)
    417                               .Authorization(TAG_MIN_MAC_LENGTH, 384)));
    418 
    419     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    420 }
    421 
    422 typedef Keymaster2Test GetKeyCharacteristics;
    423 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, GetKeyCharacteristics, test_params);
    424 
    425 TEST_P(GetKeyCharacteristics, SimpleRsa) {
    426     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    427                                            .RsaSigningKey(256, 3)
    428                                            .Digest(KM_DIGEST_NONE)
    429                                            .Padding(KM_PAD_NONE)));
    430     AuthorizationSet original(sw_enforced());
    431 
    432     ASSERT_EQ(KM_ERROR_OK, GetCharacteristics());
    433     EXPECT_EQ(original, sw_enforced());
    434 
    435     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    436         EXPECT_EQ(1, GetParam()->keymaster0_calls());
    437 }
    438 
    439 typedef Keymaster2Test SigningOperationsTest;
    440 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, SigningOperationsTest, test_params);
    441 
    442 TEST_P(SigningOperationsTest, RsaSuccess) {
    443     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    444                                            .RsaSigningKey(256, 3)
    445                                            .Digest(KM_DIGEST_NONE)
    446                                            .Padding(KM_PAD_NONE)));
    447     string message = "12345678901234567890123456789012";
    448     string signature;
    449     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
    450 
    451     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    452         EXPECT_EQ(3, GetParam()->keymaster0_calls());
    453 }
    454 
    455 TEST_P(SigningOperationsTest, RsaPssSha256Success) {
    456     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    457                                            .RsaSigningKey(768, 3)
    458                                            .Digest(KM_DIGEST_SHA_2_256)
    459                                            .Padding(KM_PAD_RSA_PSS)));
    460     // Use large message, which won't work without digesting.
    461     string message(1024, 'a');
    462     string signature;
    463     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
    464 
    465     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    466         EXPECT_EQ(3, GetParam()->keymaster0_calls());
    467 }
    468 
    469 TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
    470     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    471                                            .RsaSigningKey(512, 3)
    472                                            .Digest(KM_DIGEST_NONE)
    473                                            .Padding(KM_PAD_NONE)));
    474     string message = "12345678901234567890123456789012";
    475     string signature;
    476 
    477     AuthorizationSet begin_params(client_params());
    478     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
    479     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
    480     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
    481 
    482     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    483         EXPECT_EQ(2, GetParam()->keymaster0_calls());
    484 }
    485 
    486 TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
    487     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    488                                            .RsaSigningKey(512, 3)
    489                                            .Digest(KM_DIGEST_SHA_2_256)
    490                                            .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
    491     string message(1024, 'a');
    492     string signature;
    493     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
    494 
    495     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    496         EXPECT_EQ(3, GetParam()->keymaster0_calls());
    497 }
    498 
    499 TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
    500     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    501                                            .RsaSigningKey(512, 3)
    502                                            .Digest(KM_DIGEST_NONE)
    503                                            .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
    504     string message(53, 'a');
    505     string signature;
    506     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN);
    507 
    508     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    509         EXPECT_EQ(3, GetParam()->keymaster0_calls());
    510 }
    511 
    512 TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLarge) {
    513     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    514                                            .RsaSigningKey(512, 3)
    515                                            .Digest(KM_DIGEST_NONE)
    516                                            .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
    517     string message(54, 'a');
    518 
    519     AuthorizationSet begin_params(client_params());
    520     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
    521     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
    522     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
    523     string result;
    524     size_t input_consumed;
    525     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
    526     string signature;
    527     EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&signature));
    528 
    529     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    530         EXPECT_EQ(2, GetParam()->keymaster0_calls());
    531 }
    532 
    533 TEST_P(SigningOperationsTest, RsaPssSha256TooSmallKey) {
    534     // Key must be at least 10 bytes larger than hash, to provide eight bytes of random salt, so
    535     // verify that nine bytes larger than hash won't work.
    536     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    537                                            .RsaSigningKey(256 + 9 * 8, 3)
    538                                            .Digest(KM_DIGEST_SHA_2_256)
    539                                            .Padding(KM_PAD_RSA_PSS)));
    540     string message(1024, 'a');
    541     string signature;
    542 
    543     AuthorizationSet begin_params(client_params());
    544     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
    545     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
    546     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_SIGN, begin_params));
    547 }
    548 
    549 TEST_P(SigningOperationsTest, RsaNoPaddingHugeData) {
    550     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    551                                            .RsaSigningKey(256, 3)
    552                                            .Digest(KM_DIGEST_NONE)
    553                                            .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
    554     string message(64 * 1024, 'a');
    555     string signature;
    556     AuthorizationSet begin_params(client_params());
    557     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
    558     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
    559     ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
    560     string result;
    561     size_t input_consumed;
    562     EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &result, &input_consumed));
    563 
    564     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    565         EXPECT_EQ(2, GetParam()->keymaster0_calls());
    566 }
    567 
    568 TEST_P(SigningOperationsTest, RsaAbort) {
    569     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    570                                            .RsaSigningKey(256, 3)
    571                                            .Digest(KM_DIGEST_NONE)
    572                                            .Padding(KM_PAD_NONE)));
    573     AuthorizationSet begin_params(client_params());
    574     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
    575     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
    576     ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
    577     EXPECT_EQ(KM_ERROR_OK, AbortOperation());
    578     // Another abort should fail
    579     EXPECT_EQ(KM_ERROR_INVALID_OPERATION_HANDLE, AbortOperation());
    580 
    581     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    582         EXPECT_EQ(2, GetParam()->keymaster0_calls());
    583 }
    584 
    585 TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
    586     GenerateKey(AuthorizationSetBuilder()
    587                     .RsaSigningKey(256, 3)
    588                     .Digest(KM_DIGEST_SHA_2_256 /* supported digest */)
    589                     .Padding(KM_PAD_PKCS7));
    590     AuthorizationSet begin_params(client_params());
    591     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
    592     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
    593 
    594     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    595         EXPECT_EQ(2, GetParam()->keymaster0_calls());
    596 }
    597 
    598 TEST_P(SigningOperationsTest, RsaNoDigest) {
    599     // PSS requires a digest.
    600     GenerateKey(AuthorizationSetBuilder()
    601                     .RsaSigningKey(256, 3)
    602                     .Digest(KM_DIGEST_NONE)
    603                     .Padding(KM_PAD_RSA_PSS));
    604     AuthorizationSet begin_params(client_params());
    605     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
    606     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
    607     ASSERT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_SIGN, begin_params));
    608 
    609     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    610         EXPECT_EQ(2, GetParam()->keymaster0_calls());
    611 }
    612 
    613 TEST_P(SigningOperationsTest, RsaNoPadding) {
    614     // Padding must be specified
    615     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaKey(256, 3).SigningKey().Digest(
    616                                KM_DIGEST_NONE)));
    617     AuthorizationSet begin_params(client_params());
    618     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
    619     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
    620 
    621     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    622         EXPECT_EQ(2, GetParam()->keymaster0_calls());
    623 }
    624 
    625 TEST_P(SigningOperationsTest, RsaTooShortMessage) {
    626     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    627                                            .RsaSigningKey(256, 3)
    628                                            .Digest(KM_DIGEST_NONE)
    629                                            .Padding(KM_PAD_NONE)));
    630     string message = "1234567890123456789012345678901";
    631     string signature;
    632     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
    633 
    634     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    635         EXPECT_EQ(3, GetParam()->keymaster0_calls());
    636 }
    637 
    638 TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
    639     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    640                                            .RsaEncryptionKey(256, 3)
    641                                            .Digest(KM_DIGEST_NONE)
    642                                            .Padding(KM_PAD_NONE)));
    643     AuthorizationSet begin_params(client_params());
    644     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
    645     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
    646     ASSERT_EQ(KM_ERROR_INCOMPATIBLE_PURPOSE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
    647 
    648     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    649         EXPECT_EQ(2, GetParam()->keymaster0_calls());
    650 }
    651 
    652 TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
    653     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    654                                            .RsaSigningKey(256, 3)
    655                                            .Digest(KM_DIGEST_NONE)
    656                                            .Padding(KM_PAD_NONE)));
    657     string message(256 / 8, static_cast<char>(0xff));
    658     string signature;
    659     AuthorizationSet begin_params(client_params());
    660     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
    661     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
    662     ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
    663     string result;
    664     size_t input_consumed;
    665     ASSERT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
    666     ASSERT_EQ(message.size(), input_consumed);
    667     string output;
    668     ASSERT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&output));
    669 
    670     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
    671         EXPECT_EQ(3, GetParam()->keymaster0_calls());
    672 }
    673 
    674 TEST_P(SigningOperationsTest, EcdsaSuccess) {
    675     ASSERT_EQ(KM_ERROR_OK,
    676               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
    677     string message(224 / 8, 'a');
    678     string signature;
    679     SignMessage(message, &signature, KM_DIGEST_NONE);
    680 
    681     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
    682         EXPECT_EQ(3, GetParam()->keymaster0_calls());
    683 }
    684 
    685 TEST_P(SigningOperationsTest, EcdsaSha256Success) {
    686     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(
    687                                KM_DIGEST_SHA_2_256)));
    688     string message(1024, 'a');
    689     string signature;
    690     SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
    691 
    692     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
    693         EXPECT_EQ(3, GetParam()->keymaster0_calls());
    694 }
    695 
    696 TEST_P(SigningOperationsTest, EcdsaSha384Success) {
    697     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(
    698                                KM_DIGEST_SHA_2_384)));
    699     string message(1024, 'a');
    700     string signature;
    701     SignMessage(message, &signature, KM_DIGEST_SHA_2_384);
    702 
    703     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
    704         EXPECT_EQ(3, GetParam()->keymaster0_calls());
    705 }
    706 
    707 TEST_P(SigningOperationsTest, EcdsaNoPaddingHugeData) {
    708     ASSERT_EQ(KM_ERROR_OK,
    709               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
    710     string message(64 * 1024, 'a');
    711     string signature;
    712     AuthorizationSet begin_params(client_params());
    713     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
    714     ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
    715     string result;
    716     size_t input_consumed;
    717     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
    718 
    719     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
    720         EXPECT_EQ(2, GetParam()->keymaster0_calls());
    721 }
    722 
    723 TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
    724     vector<int> key_sizes = {224, 256, 384, 521};
    725     vector<keymaster_digest_t> digests = {
    726         KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224, KM_DIGEST_SHA_2_256,
    727         KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
    728     };
    729 
    730     for (int key_size : key_sizes) {
    731         for (keymaster_digest_t digest : digests) {
    732             ASSERT_EQ(
    733                 KM_ERROR_OK,
    734                 GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(key_size).Digest(digest)));
    735 
    736             string message(1024, 'a');
    737             string signature;
    738             if (digest == KM_DIGEST_NONE)
    739                 message.resize(key_size / 8);
    740             SignMessage(message, &signature, digest);
    741         }
    742     }
    743 
    744     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
    745         EXPECT_EQ(digests.size() * key_sizes.size() * 3,
    746                   static_cast<size_t>(GetParam()->keymaster0_calls()));
    747 }
    748 
    749 TEST_P(SigningOperationsTest, AesEcbSign) {
    750     ASSERT_EQ(KM_ERROR_OK,
    751               GenerateKey(AuthorizationSetBuilder().AesEncryptionKey(128).Authorization(
    752                   TAG_BLOCK_MODE, KM_MODE_ECB)));
    753     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_SIGN));
    754     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_VERIFY));
    755 
    756     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    757 }
    758 
    759 TEST_P(SigningOperationsTest, HmacSha1Success) {
    760     if (GetParam()->minimal_digest_set())
    761         // Can't emulate other digests for HMAC.
    762         return;
    763 
    764     GenerateKey(AuthorizationSetBuilder()
    765                     .HmacKey(128)
    766                     .Digest(KM_DIGEST_SHA1)
    767                     .Authorization(TAG_MIN_MAC_LENGTH, 160));
    768     string message = "12345678901234567890123456789012";
    769     string signature;
    770     MacMessage(message, &signature, 160);
    771     ASSERT_EQ(20U, signature.size());
    772 
    773     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    774 }
    775 
    776 TEST_P(SigningOperationsTest, HmacSha224Success) {
    777     if (GetParam()->minimal_digest_set())
    778         // Can't emulate other digests for HMAC.
    779         return;
    780 
    781     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    782                                            .HmacKey(128)
    783                                            .Digest(KM_DIGEST_SHA_2_224)
    784                                            .Authorization(TAG_MIN_MAC_LENGTH, 160)));
    785     string message = "12345678901234567890123456789012";
    786     string signature;
    787     MacMessage(message, &signature, 224);
    788     ASSERT_EQ(28U, signature.size());
    789 
    790     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    791 }
    792 
    793 TEST_P(SigningOperationsTest, HmacSha256Success) {
    794     if (GetParam()->minimal_digest_set())
    795         // Can't emulate other digests for HMAC.
    796         return;
    797 
    798     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    799                                            .HmacKey(128)
    800                                            .Digest(KM_DIGEST_SHA_2_256)
    801                                            .Authorization(TAG_MIN_MAC_LENGTH, 256)));
    802     string message = "12345678901234567890123456789012";
    803     string signature;
    804     MacMessage(message, &signature, 256);
    805     ASSERT_EQ(32U, signature.size());
    806 
    807     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    808 }
    809 
    810 TEST_P(SigningOperationsTest, HmacSha384Success) {
    811     if (GetParam()->minimal_digest_set())
    812         // Can't emulate other digests for HMAC.
    813         return;
    814 
    815     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    816                                            .HmacKey(128)
    817                                            .Digest(KM_DIGEST_SHA_2_384)
    818                                            .Authorization(TAG_MIN_MAC_LENGTH, 384)));
    819 
    820     string message = "12345678901234567890123456789012";
    821     string signature;
    822     MacMessage(message, &signature, 384);
    823     ASSERT_EQ(48U, signature.size());
    824 
    825     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    826 }
    827 
    828 TEST_P(SigningOperationsTest, HmacSha512Success) {
    829     if (GetParam()->minimal_digest_set())
    830         // Can't emulate other digests for HMAC.
    831         return;
    832 
    833     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    834                                            .HmacKey(128)
    835                                            .Digest(KM_DIGEST_SHA_2_512)
    836                                            .Authorization(TAG_MIN_MAC_LENGTH, 384)));
    837     string message = "12345678901234567890123456789012";
    838     string signature;
    839     MacMessage(message, &signature, 512);
    840     ASSERT_EQ(64U, signature.size());
    841 
    842     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    843 }
    844 
    845 TEST_P(SigningOperationsTest, HmacLengthInKey) {
    846     // TODO(swillden): unified API should generate an error on key generation.
    847     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
    848                                            .HmacKey(128)
    849                                            .Digest(KM_DIGEST_SHA_2_256)
    850                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
    851     string message = "12345678901234567890123456789012";
    852     string signature;
    853     MacMessage(message, &signature, 160);
    854     ASSERT_EQ(20U, signature.size());
    855 
    856     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    857 }
    858 
    859 TEST_P(SigningOperationsTest, HmacRfc4231TestCase1) {
    860     uint8_t key_data[] = {
    861         0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
    862         0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
    863     };
    864     string message = "Hi There";
    865     uint8_t sha_224_expected[] = {
    866         0x89, 0x6f, 0xb1, 0x12, 0x8a, 0xbb, 0xdf, 0x19, 0x68, 0x32, 0x10, 0x7c, 0xd4, 0x9d,
    867         0xf3, 0x3f, 0x47, 0xb4, 0xb1, 0x16, 0x99, 0x12, 0xba, 0x4f, 0x53, 0x68, 0x4b, 0x22,
    868     };
    869     uint8_t sha_256_expected[] = {
    870         0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf,
    871         0xce, 0xaf, 0x0b, 0xf1, 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83,
    872         0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7,
    873     };
    874     uint8_t sha_384_expected[] = {
    875         0xaf, 0xd0, 0x39, 0x44, 0xd8, 0x48, 0x95, 0x62, 0x6b, 0x08, 0x25, 0xf4,
    876         0xab, 0x46, 0x90, 0x7f, 0x15, 0xf9, 0xda, 0xdb, 0xe4, 0x10, 0x1e, 0xc6,
    877         0x82, 0xaa, 0x03, 0x4c, 0x7c, 0xeb, 0xc5, 0x9c, 0xfa, 0xea, 0x9e, 0xa9,
    878         0x07, 0x6e, 0xde, 0x7f, 0x4a, 0xf1, 0x52, 0xe8, 0xb2, 0xfa, 0x9c, 0xb6,
    879     };
    880     uint8_t sha_512_expected[] = {
    881         0x87, 0xaa, 0x7c, 0xde, 0xa5, 0xef, 0x61, 0x9d, 0x4f, 0xf0, 0xb4, 0x24, 0x1a,
    882         0x1d, 0x6c, 0xb0, 0x23, 0x79, 0xf4, 0xe2, 0xce, 0x4e, 0xc2, 0x78, 0x7a, 0xd0,
    883         0xb3, 0x05, 0x45, 0xe1, 0x7c, 0xde, 0xda, 0xa8, 0x33, 0xb7, 0xd6, 0xb8, 0xa7,
    884         0x02, 0x03, 0x8b, 0x27, 0x4e, 0xae, 0xa3, 0xf4, 0xe4, 0xbe, 0x9d, 0x91, 0x4e,
    885         0xeb, 0x61, 0xf1, 0x70, 0x2e, 0x69, 0x6c, 0x20, 0x3a, 0x12, 0x68, 0x54,
    886     };
    887 
    888     string key = make_string(key_data);
    889 
    890     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
    891     if (!GetParam()->minimal_digest_set()) {
    892         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
    893         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
    894         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
    895     }
    896 
    897     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    898 }
    899 
    900 TEST_P(SigningOperationsTest, HmacRfc4231TestCase2) {
    901     string key = "Jefe";
    902     string message = "what do ya want for nothing?";
    903     uint8_t sha_224_expected[] = {
    904         0xa3, 0x0e, 0x01, 0x09, 0x8b, 0xc6, 0xdb, 0xbf, 0x45, 0x69, 0x0f, 0x3a, 0x7e, 0x9e,
    905         0x6d, 0x0f, 0x8b, 0xbe, 0xa2, 0xa3, 0x9e, 0x61, 0x48, 0x00, 0x8f, 0xd0, 0x5e, 0x44,
    906     };
    907     uint8_t sha_256_expected[] = {
    908         0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24,
    909         0x26, 0x08, 0x95, 0x75, 0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27,
    910         0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, 0x64, 0xec, 0x38, 0x43,
    911     };
    912     uint8_t sha_384_expected[] = {
    913         0xaf, 0x45, 0xd2, 0xe3, 0x76, 0x48, 0x40, 0x31, 0x61, 0x7f, 0x78, 0xd2,
    914         0xb5, 0x8a, 0x6b, 0x1b, 0x9c, 0x7e, 0xf4, 0x64, 0xf5, 0xa0, 0x1b, 0x47,
    915         0xe4, 0x2e, 0xc3, 0x73, 0x63, 0x22, 0x44, 0x5e, 0x8e, 0x22, 0x40, 0xca,
    916         0x5e, 0x69, 0xe2, 0xc7, 0x8b, 0x32, 0x39, 0xec, 0xfa, 0xb2, 0x16, 0x49,
    917     };
    918     uint8_t sha_512_expected[] = {
    919         0x16, 0x4b, 0x7a, 0x7b, 0xfc, 0xf8, 0x19, 0xe2, 0xe3, 0x95, 0xfb, 0xe7, 0x3b,
    920         0x56, 0xe0, 0xa3, 0x87, 0xbd, 0x64, 0x22, 0x2e, 0x83, 0x1f, 0xd6, 0x10, 0x27,
    921         0x0c, 0xd7, 0xea, 0x25, 0x05, 0x54, 0x97, 0x58, 0xbf, 0x75, 0xc0, 0x5a, 0x99,
    922         0x4a, 0x6d, 0x03, 0x4f, 0x65, 0xf8, 0xf0, 0xe6, 0xfd, 0xca, 0xea, 0xb1, 0xa3,
    923         0x4d, 0x4a, 0x6b, 0x4b, 0x63, 0x6e, 0x07, 0x0a, 0x38, 0xbc, 0xe7, 0x37,
    924     };
    925 
    926     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
    927     if (!GetParam()->minimal_digest_set()) {
    928         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
    929         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
    930         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
    931         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
    932     }
    933 
    934     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    935 }
    936 
    937 TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
    938     string key(20, 0xaa);
    939     string message(50, 0xdd);
    940     uint8_t sha_224_expected[] = {
    941         0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
    942         0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
    943     };
    944     uint8_t sha_256_expected[] = {
    945         0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
    946         0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
    947         0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
    948     };
    949     uint8_t sha_384_expected[] = {
    950         0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
    951         0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
    952         0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
    953         0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
    954     };
    955     uint8_t sha_512_expected[] = {
    956         0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
    957         0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
    958         0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
    959         0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
    960         0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
    961     };
    962 
    963     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
    964     if (!GetParam()->minimal_digest_set()) {
    965         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
    966         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
    967         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
    968         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
    969     }
    970 
    971     EXPECT_EQ(0, GetParam()->keymaster0_calls());
    972 }
    973 
    974 TEST_P(SigningOperationsTest, HmacRfc4231TestCase4) {
    975     uint8_t key_data[25] = {
    976         0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
    977         0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
    978     };
    979     string key = make_string(key_data);
    980     string message(50, 0xcd);
    981     uint8_t sha_224_expected[] = {
    982         0x6c, 0x11, 0x50, 0x68, 0x74, 0x01, 0x3c, 0xac, 0x6a, 0x2a, 0xbc, 0x1b, 0xb3, 0x82,
    983         0x62, 0x7c, 0xec, 0x6a, 0x90, 0xd8, 0x6e, 0xfc, 0x01, 0x2d, 0xe7, 0xaf, 0xec, 0x5a,
    984     };
    985     uint8_t sha_256_expected[] = {
    986         0x82, 0x55, 0x8a, 0x38, 0x9a, 0x44, 0x3c, 0x0e, 0xa4, 0xcc, 0x81,
    987         0x98, 0x99, 0xf2, 0x08, 0x3a, 0x85, 0xf0, 0xfa, 0xa3, 0xe5, 0x78,
    988         0xf8, 0x07, 0x7a, 0x2e, 0x3f, 0xf4, 0x67, 0x29, 0x66, 0x5b,
    989     };
    990     uint8_t sha_384_expected[] = {
    991         0x3e, 0x8a, 0x69, 0xb7, 0x78, 0x3c, 0x25, 0x85, 0x19, 0x33, 0xab, 0x62,
    992         0x90, 0xaf, 0x6c, 0xa7, 0x7a, 0x99, 0x81, 0x48, 0x08, 0x50, 0x00, 0x9c,
    993         0xc5, 0x57, 0x7c, 0x6e, 0x1f, 0x57, 0x3b, 0x4e, 0x68, 0x01, 0xdd, 0x23,
    994         0xc4, 0xa7, 0xd6, 0x79, 0xcc, 0xf8, 0xa3, 0x86, 0xc6, 0x74, 0xcf, 0xfb,
    995     };
    996     uint8_t sha_512_expected[] = {
    997         0xb0, 0xba, 0x46, 0x56, 0x37, 0x45, 0x8c, 0x69, 0x90, 0xe5, 0xa8, 0xc5, 0xf6,
    998         0x1d, 0x4a, 0xf7, 0xe5, 0x76, 0xd9, 0x7f, 0xf9, 0x4b, 0x87, 0x2d, 0xe7, 0x6f,
    999         0x80, 0x50, 0x36, 0x1e, 0xe3, 0xdb, 0xa9, 0x1c, 0xa5, 0xc1, 0x1a, 0xa2, 0x5e,
   1000         0xb4, 0xd6, 0x79, 0x27, 0x5c, 0xc5, 0x78, 0x80, 0x63, 0xa5, 0xf1, 0x97, 0x41,
   1001         0x12, 0x0c, 0x4f, 0x2d, 0xe2, 0xad, 0xeb, 0xeb, 0x10, 0xa2, 0x98, 0xdd,
   1002     };
   1003 
   1004     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
   1005     if (!GetParam()->minimal_digest_set()) {
   1006         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
   1007         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
   1008         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
   1009         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
   1010     }
   1011 
   1012     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1013 }
   1014 
   1015 TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
   1016     string key(20, 0x0c);
   1017     string message = "Test With Truncation";
   1018 
   1019     uint8_t sha_224_expected[] = {
   1020         0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
   1021         0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
   1022     };
   1023     uint8_t sha_256_expected[] = {
   1024         0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
   1025         0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
   1026     };
   1027     uint8_t sha_384_expected[] = {
   1028         0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
   1029         0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
   1030     };
   1031     uint8_t sha_512_expected[] = {
   1032         0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
   1033         0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
   1034     };
   1035 
   1036     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
   1037     if (!GetParam()->minimal_digest_set()) {
   1038         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
   1039         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
   1040         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
   1041     }
   1042 
   1043     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1044 }
   1045 
   1046 TEST_P(SigningOperationsTest, HmacRfc4231TestCase6) {
   1047     string key(131, 0xaa);
   1048     string message = "Test Using Larger Than Block-Size Key - Hash Key First";
   1049 
   1050     uint8_t sha_224_expected[] = {
   1051         0x95, 0xe9, 0xa0, 0xdb, 0x96, 0x20, 0x95, 0xad, 0xae, 0xbe, 0x9b, 0x2d, 0x6f, 0x0d,
   1052         0xbc, 0xe2, 0xd4, 0x99, 0xf1, 0x12, 0xf2, 0xd2, 0xb7, 0x27, 0x3f, 0xa6, 0x87, 0x0e,
   1053     };
   1054     uint8_t sha_256_expected[] = {
   1055         0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26,
   1056         0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28,
   1057         0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54,
   1058     };
   1059     uint8_t sha_384_expected[] = {
   1060         0x4e, 0xce, 0x08, 0x44, 0x85, 0x81, 0x3e, 0x90, 0x88, 0xd2, 0xc6, 0x3a,
   1061         0x04, 0x1b, 0xc5, 0xb4, 0x4f, 0x9e, 0xf1, 0x01, 0x2a, 0x2b, 0x58, 0x8f,
   1062         0x3c, 0xd1, 0x1f, 0x05, 0x03, 0x3a, 0xc4, 0xc6, 0x0c, 0x2e, 0xf6, 0xab,
   1063         0x40, 0x30, 0xfe, 0x82, 0x96, 0x24, 0x8d, 0xf1, 0x63, 0xf4, 0x49, 0x52,
   1064     };
   1065     uint8_t sha_512_expected[] = {
   1066         0x80, 0xb2, 0x42, 0x63, 0xc7, 0xc1, 0xa3, 0xeb, 0xb7, 0x14, 0x93, 0xc1, 0xdd,
   1067         0x7b, 0xe8, 0xb4, 0x9b, 0x46, 0xd1, 0xf4, 0x1b, 0x4a, 0xee, 0xc1, 0x12, 0x1b,
   1068         0x01, 0x37, 0x83, 0xf8, 0xf3, 0x52, 0x6b, 0x56, 0xd0, 0x37, 0xe0, 0x5f, 0x25,
   1069         0x98, 0xbd, 0x0f, 0xd2, 0x21, 0x5d, 0x6a, 0x1e, 0x52, 0x95, 0xe6, 0x4f, 0x73,
   1070         0xf6, 0x3f, 0x0a, 0xec, 0x8b, 0x91, 0x5a, 0x98, 0x5d, 0x78, 0x65, 0x98,
   1071     };
   1072 
   1073     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
   1074     if (!GetParam()->minimal_digest_set()) {
   1075         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
   1076         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
   1077         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
   1078     }
   1079 
   1080     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1081 }
   1082 
   1083 TEST_P(SigningOperationsTest, HmacRfc4231TestCase7) {
   1084     string key(131, 0xaa);
   1085     string message = "This is a test using a larger than block-size key and a larger than "
   1086                      "block-size data. The key needs to be hashed before being used by the HMAC "
   1087                      "algorithm.";
   1088 
   1089     uint8_t sha_224_expected[] = {
   1090         0x3a, 0x85, 0x41, 0x66, 0xac, 0x5d, 0x9f, 0x02, 0x3f, 0x54, 0xd5, 0x17, 0xd0, 0xb3,
   1091         0x9d, 0xbd, 0x94, 0x67, 0x70, 0xdb, 0x9c, 0x2b, 0x95, 0xc9, 0xf6, 0xf5, 0x65, 0xd1,
   1092     };
   1093     uint8_t sha_256_expected[] = {
   1094         0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f,
   1095         0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07,
   1096         0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2,
   1097     };
   1098     uint8_t sha_384_expected[] = {
   1099         0x66, 0x17, 0x17, 0x8e, 0x94, 0x1f, 0x02, 0x0d, 0x35, 0x1e, 0x2f, 0x25,
   1100         0x4e, 0x8f, 0xd3, 0x2c, 0x60, 0x24, 0x20, 0xfe, 0xb0, 0xb8, 0xfb, 0x9a,
   1101         0xdc, 0xce, 0xbb, 0x82, 0x46, 0x1e, 0x99, 0xc5, 0xa6, 0x78, 0xcc, 0x31,
   1102         0xe7, 0x99, 0x17, 0x6d, 0x38, 0x60, 0xe6, 0x11, 0x0c, 0x46, 0x52, 0x3e,
   1103     };
   1104     uint8_t sha_512_expected[] = {
   1105         0xe3, 0x7b, 0x6a, 0x77, 0x5d, 0xc8, 0x7d, 0xba, 0xa4, 0xdf, 0xa9, 0xf9, 0x6e,
   1106         0x5e, 0x3f, 0xfd, 0xde, 0xbd, 0x71, 0xf8, 0x86, 0x72, 0x89, 0x86, 0x5d, 0xf5,
   1107         0xa3, 0x2d, 0x20, 0xcd, 0xc9, 0x44, 0xb6, 0x02, 0x2c, 0xac, 0x3c, 0x49, 0x82,
   1108         0xb1, 0x0d, 0x5e, 0xeb, 0x55, 0xc3, 0xe4, 0xde, 0x15, 0x13, 0x46, 0x76, 0xfb,
   1109         0x6d, 0xe0, 0x44, 0x60, 0x65, 0xc9, 0x74, 0x40, 0xfa, 0x8c, 0x6a, 0x58,
   1110     };
   1111 
   1112     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
   1113     if (!GetParam()->minimal_digest_set()) {
   1114         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
   1115         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
   1116         CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
   1117     }
   1118 
   1119     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1120 }
   1121 
   1122 TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
   1123     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   1124                                            .HmacKey(128)
   1125                                            .Digest(KM_DIGEST_SHA_2_256)
   1126                                            .Authorization(TAG_MIN_MAC_LENGTH, 256)));
   1127     AuthorizationSet begin_params(client_params());
   1128     begin_params.push_back(TAG_MAC_LENGTH, 264);
   1129     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
   1130     ASSERT_EQ(KM_ERROR_UNSUPPORTED_MAC_LENGTH,
   1131               BeginOperation(KM_PURPOSE_SIGN, begin_params, nullptr /* output_params */));
   1132 
   1133     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1134 }
   1135 
   1136 TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
   1137     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   1138                                            .HmacKey(128)
   1139                                            .Digest(KM_DIGEST_SHA_2_256)
   1140                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
   1141     AuthorizationSet begin_params(client_params());
   1142     begin_params.push_back(TAG_MAC_LENGTH, 120);
   1143     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
   1144     ASSERT_EQ(KM_ERROR_INVALID_MAC_LENGTH,
   1145               BeginOperation(KM_PURPOSE_SIGN, begin_params, nullptr /* output_params */));
   1146 
   1147     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1148 }
   1149 
   1150 // TODO(swillden): Add more verification failure tests.
   1151 
   1152 typedef Keymaster2Test VerificationOperationsTest;
   1153 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, VerificationOperationsTest, test_params);
   1154 
   1155 TEST_P(VerificationOperationsTest, RsaSuccess) {
   1156     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   1157                                            .RsaSigningKey(256, 3)
   1158                                            .Digest(KM_DIGEST_NONE)
   1159                                            .Padding(KM_PAD_NONE)));
   1160     string message = "12345678901234567890123456789012";
   1161     string signature;
   1162     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
   1163     VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
   1164 
   1165     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1166         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1167 }
   1168 
   1169 TEST_P(VerificationOperationsTest, RsaPssSha256Success) {
   1170     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   1171                                            .RsaSigningKey(768, 3)
   1172                                            .Digest(KM_DIGEST_SHA_2_256)
   1173                                            .Padding(KM_PAD_RSA_PSS)));
   1174     // Use large message, which won't work without digesting.
   1175     string message(1024, 'a');
   1176     string signature;
   1177     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
   1178     VerifyMessage(message, signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
   1179 
   1180     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1181         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1182 }
   1183 
   1184 TEST_P(VerificationOperationsTest, RsaPssSha224Success) {
   1185     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   1186                                            .RsaSigningKey(512, 3)
   1187                                            .Digest(KM_DIGEST_SHA_2_224)
   1188                                            .Padding(KM_PAD_RSA_PSS)));
   1189     // Use large message, which won't work without digesting.
   1190     string message(1024, 'a');
   1191     string signature;
   1192     SignMessage(message, &signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PSS);
   1193     VerifyMessage(message, signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PSS);
   1194 
   1195     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1196         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1197 
   1198     // Verify with OpenSSL.
   1199     string pubkey;
   1200     EXPECT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &pubkey));
   1201 
   1202     const uint8_t* p = reinterpret_cast<const uint8_t*>(pubkey.data());
   1203     unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
   1204         d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
   1205     ASSERT_TRUE(pkey.get());
   1206 
   1207     EVP_MD_CTX digest_ctx;
   1208     EVP_MD_CTX_init(&digest_ctx);
   1209     EVP_PKEY_CTX* pkey_ctx;
   1210     EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, EVP_sha224(), nullptr /* engine */,
   1211                                       pkey.get()));
   1212     EXPECT_EQ(1, EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING));
   1213     EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()));
   1214     EXPECT_EQ(1,
   1215               EVP_DigestVerifyFinal(&digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
   1216                                     signature.size()));
   1217     EVP_MD_CTX_cleanup(&digest_ctx);
   1218 }
   1219 
   1220 TEST_P(VerificationOperationsTest, RsaPssSha256CorruptSignature) {
   1221     GenerateKey(AuthorizationSetBuilder()
   1222                     .RsaSigningKey(768, 3)
   1223                     .Digest(KM_DIGEST_SHA_2_256)
   1224                     .Padding(KM_PAD_RSA_PSS));
   1225     string message(1024, 'a');
   1226     string signature;
   1227     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
   1228     ++signature[signature.size() / 2];
   1229 
   1230     AuthorizationSet begin_params(client_params());
   1231     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
   1232     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
   1233     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
   1234 
   1235     string result;
   1236     size_t input_consumed;
   1237     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
   1238     EXPECT_EQ(message.size(), input_consumed);
   1239     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
   1240 
   1241     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1242         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1243 }
   1244 
   1245 TEST_P(VerificationOperationsTest, RsaPssSha256CorruptInput) {
   1246     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   1247                                            .RsaSigningKey(768, 3)
   1248                                            .Digest(KM_DIGEST_SHA_2_256)
   1249                                            .Padding(KM_PAD_RSA_PSS)));
   1250     // Use large message, which won't work without digesting.
   1251     string message(1024, 'a');
   1252     string signature;
   1253     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
   1254     ++message[message.size() / 2];
   1255 
   1256     AuthorizationSet begin_params(client_params());
   1257     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
   1258     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
   1259     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
   1260 
   1261     string result;
   1262     size_t input_consumed;
   1263     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
   1264     EXPECT_EQ(message.size(), input_consumed);
   1265     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
   1266 
   1267     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1268         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1269 }
   1270 
   1271 TEST_P(VerificationOperationsTest, RsaPkcs1Sha256Success) {
   1272     GenerateKey(AuthorizationSetBuilder()
   1273                     .RsaSigningKey(512, 3)
   1274                     .Digest(KM_DIGEST_SHA_2_256)
   1275                     .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN));
   1276     string message(1024, 'a');
   1277     string signature;
   1278     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
   1279     VerifyMessage(message, signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
   1280 
   1281     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1282         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1283 }
   1284 
   1285 TEST_P(VerificationOperationsTest, RsaPks1Sha224Success) {
   1286     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   1287                                            .RsaSigningKey(512, 3)
   1288                                            .Digest(KM_DIGEST_SHA_2_224)
   1289                                            .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
   1290     // Use large message, which won't work without digesting.
   1291     string message(1024, 'a');
   1292     string signature;
   1293     SignMessage(message, &signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PKCS1_1_5_SIGN);
   1294     VerifyMessage(message, signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PKCS1_1_5_SIGN);
   1295 
   1296     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1297         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1298 
   1299     // Verify with OpenSSL.
   1300     string pubkey;
   1301     EXPECT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &pubkey));
   1302 
   1303     const uint8_t* p = reinterpret_cast<const uint8_t*>(pubkey.data());
   1304     unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
   1305         d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
   1306     ASSERT_TRUE(pkey.get());
   1307 
   1308     EVP_MD_CTX digest_ctx;
   1309     EVP_MD_CTX_init(&digest_ctx);
   1310     EVP_PKEY_CTX* pkey_ctx;
   1311     EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, EVP_sha224(), nullptr /* engine */,
   1312                                       pkey.get()));
   1313     EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()));
   1314     EXPECT_EQ(1,
   1315               EVP_DigestVerifyFinal(&digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
   1316                                     signature.size()));
   1317     EVP_MD_CTX_cleanup(&digest_ctx);
   1318 }
   1319 
   1320 TEST_P(VerificationOperationsTest, RsaPkcs1Sha256CorruptSignature) {
   1321     GenerateKey(AuthorizationSetBuilder()
   1322                     .RsaSigningKey(512, 3)
   1323                     .Digest(KM_DIGEST_SHA_2_256)
   1324                     .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN));
   1325     string message(1024, 'a');
   1326     string signature;
   1327     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
   1328     ++signature[signature.size() / 2];
   1329 
   1330     AuthorizationSet begin_params(client_params());
   1331     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
   1332     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
   1333     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
   1334 
   1335     string result;
   1336     size_t input_consumed;
   1337     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
   1338     EXPECT_EQ(message.size(), input_consumed);
   1339     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
   1340 
   1341     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1342         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1343 }
   1344 
   1345 TEST_P(VerificationOperationsTest, RsaPkcs1Sha256CorruptInput) {
   1346     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   1347                                            .RsaSigningKey(512, 3)
   1348                                            .Digest(KM_DIGEST_SHA_2_256)
   1349                                            .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
   1350     // Use large message, which won't work without digesting.
   1351     string message(1024, 'a');
   1352     string signature;
   1353     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
   1354     ++message[message.size() / 2];
   1355 
   1356     AuthorizationSet begin_params(client_params());
   1357     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
   1358     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
   1359     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
   1360 
   1361     string result;
   1362     size_t input_consumed;
   1363     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
   1364     EXPECT_EQ(message.size(), input_consumed);
   1365     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
   1366 
   1367     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1368         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1369 }
   1370 
   1371 TEST_P(VerificationOperationsTest, RsaAllDigestAndPadCombinations) {
   1372     vector<keymaster_digest_t> digests = {
   1373         KM_DIGEST_NONE,      KM_DIGEST_MD5,       KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
   1374         KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
   1375     };
   1376 
   1377     vector<keymaster_padding_t> padding_modes{
   1378         KM_PAD_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN, KM_PAD_RSA_PSS,
   1379     };
   1380 
   1381     int trial_count = 0;
   1382     for (keymaster_padding_t padding_mode : padding_modes) {
   1383         for (keymaster_digest_t digest : digests) {
   1384             if (digest != KM_DIGEST_NONE && padding_mode == KM_PAD_NONE)
   1385                 // Digesting requires padding
   1386                 continue;
   1387 
   1388             // Compute key & message size that will work.
   1389             size_t key_bits = 0;
   1390             size_t message_len = 1000;
   1391 
   1392             if (digest == KM_DIGEST_NONE) {
   1393                 key_bits = 256;
   1394                 switch (padding_mode) {
   1395                 case KM_PAD_NONE:
   1396                     // Match key size.
   1397                     message_len = key_bits / 8;
   1398                     break;
   1399                 case KM_PAD_RSA_PKCS1_1_5_SIGN:
   1400                     message_len = key_bits / 8 - 11;
   1401                     break;
   1402                 case KM_PAD_RSA_PSS:
   1403                     // PSS requires a digest.
   1404                     continue;
   1405                 default:
   1406                     FAIL() << "Missing padding";
   1407                     break;
   1408                 }
   1409             } else {
   1410                 size_t digest_bits;
   1411                 switch (digest) {
   1412                 case KM_DIGEST_MD5:
   1413                     digest_bits = 128;
   1414                     break;
   1415                 case KM_DIGEST_SHA1:
   1416                     digest_bits = 160;
   1417                     break;
   1418                 case KM_DIGEST_SHA_2_224:
   1419                     digest_bits = 224;
   1420                     break;
   1421                 case KM_DIGEST_SHA_2_256:
   1422                     digest_bits = 256;
   1423                     break;
   1424                 case KM_DIGEST_SHA_2_384:
   1425                     digest_bits = 384;
   1426                     break;
   1427                 case KM_DIGEST_SHA_2_512:
   1428                     digest_bits = 512;
   1429                     break;
   1430                 default:
   1431                     FAIL() << "Missing digest";
   1432                 }
   1433 
   1434                 switch (padding_mode) {
   1435                 case KM_PAD_RSA_PKCS1_1_5_SIGN:
   1436                     key_bits = digest_bits + 8 * (11 + 19);
   1437                     break;
   1438                 case KM_PAD_RSA_PSS:
   1439                     key_bits = digest_bits * 2 + 2 * 8;
   1440                     break;
   1441                 default:
   1442                     FAIL() << "Missing padding";
   1443                     break;
   1444                 }
   1445             }
   1446 
   1447             GenerateKey(AuthorizationSetBuilder()
   1448                             .RsaSigningKey(key_bits, 3)
   1449                             .Digest(digest)
   1450                             .Padding(padding_mode));
   1451             string message(message_len, 'a');
   1452             string signature;
   1453             SignMessage(message, &signature, digest, padding_mode);
   1454             VerifyMessage(message, signature, digest, padding_mode);
   1455             ++trial_count;
   1456         }
   1457     }
   1458 
   1459     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1460         EXPECT_EQ(trial_count * 4, GetParam()->keymaster0_calls());
   1461 }
   1462 
   1463 TEST_P(VerificationOperationsTest, EcdsaSuccess) {
   1464     ASSERT_EQ(KM_ERROR_OK,
   1465               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE)));
   1466     string message = "12345678901234567890123456789012";
   1467     string signature;
   1468     SignMessage(message, &signature, KM_DIGEST_NONE);
   1469     VerifyMessage(message, signature, KM_DIGEST_NONE);
   1470 
   1471     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
   1472         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1473 }
   1474 
   1475 TEST_P(VerificationOperationsTest, EcdsaTooShort) {
   1476     ASSERT_EQ(KM_ERROR_OK,
   1477               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE)));
   1478     string message = "12345678901234567890";
   1479     string signature;
   1480     SignMessage(message, &signature, KM_DIGEST_NONE);
   1481     VerifyMessage(message, signature, KM_DIGEST_NONE);
   1482 
   1483     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
   1484         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1485 }
   1486 
   1487 TEST_P(VerificationOperationsTest, EcdsaSlightlyTooLong) {
   1488     ASSERT_EQ(KM_ERROR_OK,
   1489               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(521).Digest(KM_DIGEST_NONE)));
   1490 
   1491     string message(66, 'a');
   1492     string signature;
   1493     SignMessage(message, &signature, KM_DIGEST_NONE);
   1494     VerifyMessage(message, signature, KM_DIGEST_NONE);
   1495 
   1496     // Modifying low-order bits doesn't matter, because they didn't get signed.  Ugh.
   1497     message[65] ^= 7;
   1498     VerifyMessage(message, signature, KM_DIGEST_NONE);
   1499 
   1500     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
   1501         EXPECT_EQ(5, GetParam()->keymaster0_calls());
   1502 }
   1503 
   1504 TEST_P(VerificationOperationsTest, EcdsaSha256Success) {
   1505     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   1506                                            .EcdsaSigningKey(256)
   1507                                            .Digest(KM_DIGEST_SHA_2_256)
   1508                                            .Digest(KM_DIGEST_NONE)));
   1509     string message = "12345678901234567890123456789012";
   1510     string signature;
   1511     SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
   1512     VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
   1513 
   1514     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
   1515         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1516 
   1517     // Just for giggles, try verifying with the wrong digest.
   1518     AuthorizationSet begin_params(client_params());
   1519     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
   1520     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
   1521 
   1522     string result;
   1523     size_t input_consumed;
   1524     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
   1525     EXPECT_EQ(message.size(), input_consumed);
   1526     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
   1527 }
   1528 
   1529 TEST_P(VerificationOperationsTest, EcdsaSha224Success) {
   1530     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(
   1531                                KM_DIGEST_SHA_2_224)));
   1532 
   1533     string message = "12345678901234567890123456789012";
   1534     string signature;
   1535     SignMessage(message, &signature, KM_DIGEST_SHA_2_224);
   1536     VerifyMessage(message, signature, KM_DIGEST_SHA_2_224);
   1537 
   1538     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
   1539         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1540 
   1541     // Just for giggles, try verifying with the wrong digest.
   1542     AuthorizationSet begin_params(client_params());
   1543     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
   1544     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
   1545 
   1546     string result;
   1547     size_t input_consumed;
   1548     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
   1549     EXPECT_EQ(message.size(), input_consumed);
   1550     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
   1551 }
   1552 
   1553 TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndKeySizes) {
   1554     keymaster_digest_t digests[] = {
   1555         KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224, KM_DIGEST_SHA_2_256,
   1556         KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
   1557     };
   1558     size_t key_sizes[] = {224, 256, 384, 521};
   1559 
   1560     string message = "1234567890";
   1561     string signature;
   1562 
   1563     for (auto key_size : key_sizes) {
   1564         AuthorizationSetBuilder builder;
   1565         builder.EcdsaSigningKey(key_size);
   1566         for (auto digest : digests)
   1567             builder.Digest(digest);
   1568         ASSERT_EQ(KM_ERROR_OK, GenerateKey(builder));
   1569 
   1570         for (auto digest : digests) {
   1571             SignMessage(message, &signature, digest);
   1572             VerifyMessage(message, signature, digest);
   1573         }
   1574     }
   1575 
   1576     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
   1577         EXPECT_EQ(static_cast<int>(array_length(key_sizes) * (1 + 3 * array_length(digests))),
   1578                   GetParam()->keymaster0_calls());
   1579 }
   1580 
   1581 TEST_P(VerificationOperationsTest, HmacSha1Success) {
   1582     if (GetParam()->minimal_digest_set())
   1583         // Can't emulate missing digests for HMAC.
   1584         return;
   1585 
   1586     GenerateKey(AuthorizationSetBuilder()
   1587                     .HmacKey(128)
   1588                     .Digest(KM_DIGEST_SHA1)
   1589                     .Authorization(TAG_MIN_MAC_LENGTH, 128));
   1590     string message = "123456789012345678901234567890123456789012345678";
   1591     string signature;
   1592     MacMessage(message, &signature, 160);
   1593     VerifyMac(message, signature);
   1594 
   1595     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1596 }
   1597 
   1598 TEST_P(VerificationOperationsTest, HmacSha224Success) {
   1599     if (GetParam()->minimal_digest_set())
   1600         // Can't emulate missing digests for HMAC.
   1601         return;
   1602 
   1603     GenerateKey(AuthorizationSetBuilder()
   1604                     .HmacKey(128)
   1605                     .Digest(KM_DIGEST_SHA_2_224)
   1606                     .Authorization(TAG_MIN_MAC_LENGTH, 128));
   1607     string message = "123456789012345678901234567890123456789012345678";
   1608     string signature;
   1609     MacMessage(message, &signature, 224);
   1610     VerifyMac(message, signature);
   1611 
   1612     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1613 }
   1614 
   1615 TEST_P(VerificationOperationsTest, HmacSha256Success) {
   1616     GenerateKey(AuthorizationSetBuilder()
   1617                     .HmacKey(128)
   1618                     .Digest(KM_DIGEST_SHA_2_256)
   1619                     .Authorization(TAG_MIN_MAC_LENGTH, 128));
   1620     string message = "123456789012345678901234567890123456789012345678";
   1621     string signature;
   1622     MacMessage(message, &signature, 256);
   1623     VerifyMac(message, signature);
   1624 
   1625     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1626 }
   1627 
   1628 TEST_P(VerificationOperationsTest, HmacSha256TooShortMac) {
   1629     GenerateKey(AuthorizationSetBuilder()
   1630                     .HmacKey(128)
   1631                     .Digest(KM_DIGEST_SHA_2_256)
   1632                     .Authorization(TAG_MIN_MAC_LENGTH, 128));
   1633     string message = "123456789012345678901234567890123456789012345678";
   1634     string signature;
   1635     MacMessage(message, &signature, 256);
   1636 
   1637     // Shorten to 128 bits, should still work.
   1638     signature.resize(128 / 8);
   1639     VerifyMac(message, signature);
   1640 
   1641     // Drop one more byte.
   1642     signature.resize(signature.length() - 1);
   1643 
   1644     AuthorizationSet begin_params(client_params());
   1645     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
   1646     string result;
   1647     size_t input_consumed;
   1648     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
   1649     EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH, FinishOperation(signature, &result));
   1650 
   1651     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1652 }
   1653 
   1654 TEST_P(VerificationOperationsTest, HmacSha384Success) {
   1655     if (GetParam()->minimal_digest_set())
   1656         // Can't emulate missing digests for HMAC.
   1657         return;
   1658 
   1659     GenerateKey(AuthorizationSetBuilder()
   1660                     .HmacKey(128)
   1661                     .Digest(KM_DIGEST_SHA_2_384)
   1662                     .Authorization(TAG_MIN_MAC_LENGTH, 128));
   1663     string message = "123456789012345678901234567890123456789012345678";
   1664     string signature;
   1665     MacMessage(message, &signature, 384);
   1666     VerifyMac(message, signature);
   1667 
   1668     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1669 }
   1670 
   1671 TEST_P(VerificationOperationsTest, HmacSha512Success) {
   1672     if (GetParam()->minimal_digest_set())
   1673         // Can't emulate missing digests for HMAC.
   1674         return;
   1675 
   1676     GenerateKey(AuthorizationSetBuilder()
   1677                     .HmacKey(128)
   1678                     .Digest(KM_DIGEST_SHA_2_512)
   1679                     .Authorization(TAG_MIN_MAC_LENGTH, 128));
   1680     string message = "123456789012345678901234567890123456789012345678";
   1681     string signature;
   1682     MacMessage(message, &signature, 512);
   1683     VerifyMac(message, signature);
   1684 
   1685     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1686 }
   1687 
   1688 typedef Keymaster2Test ExportKeyTest;
   1689 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, ExportKeyTest, test_params);
   1690 
   1691 TEST_P(ExportKeyTest, RsaSuccess) {
   1692     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   1693                                            .RsaSigningKey(256, 3)
   1694                                            .Digest(KM_DIGEST_NONE)
   1695                                            .Padding(KM_PAD_NONE)));
   1696     string export_data;
   1697     ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &export_data));
   1698     EXPECT_GT(export_data.length(), 0U);
   1699 
   1700     // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
   1701 
   1702     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1703         EXPECT_EQ(2, GetParam()->keymaster0_calls());
   1704 }
   1705 
   1706 TEST_P(ExportKeyTest, EcdsaSuccess) {
   1707     ASSERT_EQ(KM_ERROR_OK,
   1708               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
   1709     string export_data;
   1710     ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &export_data));
   1711     EXPECT_GT(export_data.length(), 0U);
   1712 
   1713     // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
   1714 
   1715     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
   1716         EXPECT_EQ(2, GetParam()->keymaster0_calls());
   1717 }
   1718 
   1719 TEST_P(ExportKeyTest, RsaUnsupportedKeyFormat) {
   1720     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   1721                                            .RsaSigningKey(256, 3)
   1722                                            .Digest(KM_DIGEST_NONE)
   1723                                            .Padding(KM_PAD_NONE)));
   1724     string export_data;
   1725     ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_PKCS8, &export_data));
   1726 
   1727     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1728         EXPECT_EQ(2, GetParam()->keymaster0_calls());
   1729 }
   1730 
   1731 TEST_P(ExportKeyTest, RsaCorruptedKeyBlob) {
   1732     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   1733                                            .RsaSigningKey(256, 3)
   1734                                            .Digest(KM_DIGEST_NONE)
   1735                                            .Padding(KM_PAD_NONE)));
   1736     corrupt_key_blob();
   1737     string export_data;
   1738     ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, ExportKey(KM_KEY_FORMAT_X509, &export_data));
   1739 
   1740     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1741         EXPECT_EQ(2, GetParam()->keymaster0_calls());
   1742 }
   1743 
   1744 TEST_P(ExportKeyTest, AesKeyExportFails) {
   1745     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().AesEncryptionKey(128)));
   1746     string export_data;
   1747 
   1748     EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_X509, &export_data));
   1749     EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_PKCS8, &export_data));
   1750     EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_RAW, &export_data));
   1751 
   1752     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1753 }
   1754 
   1755 static string read_file(const string& file_name) {
   1756     ifstream file_stream(file_name, std::ios::binary);
   1757     istreambuf_iterator<char> file_begin(file_stream);
   1758     istreambuf_iterator<char> file_end;
   1759     return string(file_begin, file_end);
   1760 }
   1761 
   1762 typedef Keymaster2Test ImportKeyTest;
   1763 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, ImportKeyTest, test_params);
   1764 
   1765 TEST_P(ImportKeyTest, RsaSuccess) {
   1766     string pk8_key = read_file("rsa_privkey_pk8.der");
   1767     ASSERT_EQ(633U, pk8_key.size());
   1768 
   1769     ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
   1770                                          .RsaSigningKey(1024, 65537)
   1771                                          .Digest(KM_DIGEST_NONE)
   1772                                          .Padding(KM_PAD_NONE),
   1773                                      KM_KEY_FORMAT_PKCS8, pk8_key));
   1774 
   1775     // Check values derived from the key.
   1776     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
   1777                                                                                  : sw_enforced(),
   1778                          TAG_ALGORITHM, KM_ALGORITHM_RSA));
   1779     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
   1780                                                                                  : sw_enforced(),
   1781                          TAG_KEY_SIZE, 1024));
   1782     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
   1783                                                                                  : sw_enforced(),
   1784                          TAG_RSA_PUBLIC_EXPONENT, 65537U));
   1785 
   1786     // And values provided by AndroidKeymaster
   1787     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1788         EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
   1789     else
   1790         EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
   1791     EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
   1792 
   1793     string message(1024 / 8, 'a');
   1794     string signature;
   1795     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
   1796     VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
   1797 
   1798     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1799         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1800 }
   1801 
   1802 TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
   1803     string pk8_key = read_file("rsa_privkey_pk8.der");
   1804     ASSERT_EQ(633U, pk8_key.size());
   1805     ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
   1806               ImportKey(AuthorizationSetBuilder()
   1807                             .RsaSigningKey(2048 /* Doesn't match key */, 3)
   1808                             .Digest(KM_DIGEST_NONE)
   1809                             .Padding(KM_PAD_NONE),
   1810                         KM_KEY_FORMAT_PKCS8, pk8_key));
   1811 
   1812     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1813 }
   1814 
   1815 TEST_P(ImportKeyTest, RsaPublicExponenMismatch) {
   1816     string pk8_key = read_file("rsa_privkey_pk8.der");
   1817     ASSERT_EQ(633U, pk8_key.size());
   1818     ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
   1819               ImportKey(AuthorizationSetBuilder()
   1820                             .RsaSigningKey(256, 3 /* Doesnt' match key */)
   1821                             .Digest(KM_DIGEST_NONE)
   1822                             .Padding(KM_PAD_NONE),
   1823                         KM_KEY_FORMAT_PKCS8, pk8_key));
   1824 
   1825     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1826 }
   1827 
   1828 TEST_P(ImportKeyTest, EcdsaSuccess) {
   1829     string pk8_key = read_file("ec_privkey_pk8.der");
   1830     ASSERT_EQ(138U, pk8_key.size());
   1831 
   1832     ASSERT_EQ(KM_ERROR_OK,
   1833               ImportKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE),
   1834                         KM_KEY_FORMAT_PKCS8, pk8_key));
   1835 
   1836     // Check values derived from the key.
   1837     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
   1838                                                                                 : sw_enforced(),
   1839                          TAG_ALGORITHM, KM_ALGORITHM_EC));
   1840     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
   1841                                                                                 : sw_enforced(),
   1842                          TAG_KEY_SIZE, 256));
   1843 
   1844     // And values provided by AndroidKeymaster
   1845     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
   1846         EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
   1847     else
   1848         EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
   1849     EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
   1850 
   1851     string message(32, 'a');
   1852     string signature;
   1853     SignMessage(message, &signature, KM_DIGEST_NONE);
   1854     VerifyMessage(message, signature, KM_DIGEST_NONE);
   1855 
   1856     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
   1857         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1858 }
   1859 
   1860 TEST_P(ImportKeyTest, EcdsaSizeSpecified) {
   1861     string pk8_key = read_file("ec_privkey_pk8.der");
   1862     ASSERT_EQ(138U, pk8_key.size());
   1863 
   1864     ASSERT_EQ(KM_ERROR_OK,
   1865               ImportKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE),
   1866                         KM_KEY_FORMAT_PKCS8, pk8_key));
   1867 
   1868     // Check values derived from the key.
   1869     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
   1870                                                                                 : sw_enforced(),
   1871                          TAG_ALGORITHM, KM_ALGORITHM_EC));
   1872     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
   1873                                                                                 : sw_enforced(),
   1874                          TAG_KEY_SIZE, 256));
   1875 
   1876     // And values provided by AndroidKeymaster
   1877     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
   1878         EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
   1879     else
   1880         EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
   1881     EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
   1882 
   1883     string message(32, 'a');
   1884     string signature;
   1885     SignMessage(message, &signature, KM_DIGEST_NONE);
   1886     VerifyMessage(message, signature, KM_DIGEST_NONE);
   1887 
   1888     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
   1889         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1890 }
   1891 
   1892 TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
   1893     string pk8_key = read_file("ec_privkey_pk8.der");
   1894     ASSERT_EQ(138U, pk8_key.size());
   1895     ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
   1896               ImportKey(AuthorizationSetBuilder()
   1897                             .EcdsaSigningKey(224 /* Doesn't match key */)
   1898                             .Digest(KM_DIGEST_NONE),
   1899                         KM_KEY_FORMAT_PKCS8, pk8_key));
   1900 
   1901     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1902 }
   1903 
   1904 TEST_P(ImportKeyTest, AesKeySuccess) {
   1905     char key_data[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
   1906     string key(key_data, sizeof(key_data));
   1907     ASSERT_EQ(KM_ERROR_OK,
   1908               ImportKey(AuthorizationSetBuilder().AesEncryptionKey(128).EcbMode().Authorization(
   1909                             TAG_PADDING, KM_PAD_PKCS7),
   1910                         KM_KEY_FORMAT_RAW, key));
   1911 
   1912     EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
   1913     EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
   1914 
   1915     string message = "Hello World!";
   1916     string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
   1917     string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
   1918     EXPECT_EQ(message, plaintext);
   1919 
   1920     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1921 }
   1922 
   1923 TEST_P(ImportKeyTest, HmacSha256KeySuccess) {
   1924     char key_data[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
   1925     string key(key_data, sizeof(key_data));
   1926     ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
   1927                                          .HmacKey(sizeof(key_data) * 8)
   1928                                          .Digest(KM_DIGEST_SHA_2_256)
   1929                                          .Authorization(TAG_MIN_MAC_LENGTH, 256),
   1930                                      KM_KEY_FORMAT_RAW, key));
   1931 
   1932     EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
   1933     EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
   1934 
   1935     string message = "Hello World!";
   1936     string signature;
   1937     MacMessage(message, &signature, 256);
   1938     VerifyMac(message, signature);
   1939 
   1940     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   1941 }
   1942 
   1943 typedef Keymaster2Test EncryptionOperationsTest;
   1944 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, EncryptionOperationsTest, test_params);
   1945 
   1946 TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
   1947     ASSERT_EQ(KM_ERROR_OK,
   1948               GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
   1949 
   1950     string message = "12345678901234567890123456789012";
   1951     string ciphertext1 = EncryptMessage(string(message), KM_PAD_NONE);
   1952     EXPECT_EQ(256U / 8, ciphertext1.size());
   1953 
   1954     string ciphertext2 = EncryptMessage(string(message), KM_PAD_NONE);
   1955     EXPECT_EQ(256U / 8, ciphertext2.size());
   1956 
   1957     // Unpadded RSA is deterministic
   1958     EXPECT_EQ(ciphertext1, ciphertext2);
   1959 
   1960     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1961         EXPECT_EQ(3, GetParam()->keymaster0_calls());
   1962 }
   1963 
   1964 TEST_P(EncryptionOperationsTest, RsaNoPaddingTooShort) {
   1965     ASSERT_EQ(KM_ERROR_OK,
   1966               GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
   1967 
   1968     string message = "1";
   1969 
   1970     string ciphertext = EncryptMessage(message, KM_PAD_NONE);
   1971     EXPECT_EQ(256U / 8, ciphertext.size());
   1972 
   1973     string expected_plaintext = string(256 / 8 - 1, 0) + message;
   1974     string plaintext = DecryptMessage(ciphertext, KM_PAD_NONE);
   1975 
   1976     EXPECT_EQ(expected_plaintext, plaintext);
   1977 
   1978     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1979         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   1980 }
   1981 
   1982 TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
   1983     ASSERT_EQ(KM_ERROR_OK,
   1984               GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
   1985 
   1986     string message = "123456789012345678901234567890123";
   1987 
   1988     AuthorizationSet begin_params(client_params());
   1989     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   1990     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   1991 
   1992     string result;
   1993     size_t input_consumed;
   1994     EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &result, &input_consumed));
   1995 
   1996     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   1997         EXPECT_EQ(2, GetParam()->keymaster0_calls());
   1998 }
   1999 
   2000 TEST_P(EncryptionOperationsTest, RsaNoPaddingLargerThanModulus) {
   2001     ASSERT_EQ(KM_ERROR_OK,
   2002               GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
   2003 
   2004     string exported;
   2005     ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &exported));
   2006 
   2007     const uint8_t* p = reinterpret_cast<const uint8_t*>(exported.data());
   2008     unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
   2009         d2i_PUBKEY(nullptr /* alloc new */, &p, exported.size()));
   2010     unique_ptr<RSA, RSA_Delete> rsa(EVP_PKEY_get1_RSA(pkey.get()));
   2011 
   2012     size_t modulus_len = BN_num_bytes(rsa->n);
   2013     ASSERT_EQ(256U / 8, modulus_len);
   2014     unique_ptr<uint8_t[]> modulus_buf(new uint8_t[modulus_len]);
   2015     BN_bn2bin(rsa->n, modulus_buf.get());
   2016 
   2017     // The modulus is too big to encrypt.
   2018     string message(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
   2019 
   2020     AuthorizationSet begin_params(client_params());
   2021     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2022     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   2023 
   2024     string result;
   2025     size_t input_consumed;
   2026     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
   2027     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&result));
   2028 
   2029     // One smaller than the modulus is okay.
   2030     BN_sub(rsa->n, rsa->n, BN_value_one());
   2031     modulus_len = BN_num_bytes(rsa->n);
   2032     ASSERT_EQ(256U / 8, modulus_len);
   2033     BN_bn2bin(rsa->n, modulus_buf.get());
   2034     message = string(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
   2035     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   2036     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
   2037     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&result));
   2038 
   2039     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2040         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   2041 }
   2042 
   2043 TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
   2044     size_t key_size = 768;
   2045     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2046                                            .RsaEncryptionKey(key_size, 3)
   2047                                            .Padding(KM_PAD_RSA_OAEP)
   2048                                            .Digest(KM_DIGEST_SHA_2_256)));
   2049 
   2050     string message = "Hello";
   2051     string ciphertext1 = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
   2052     EXPECT_EQ(key_size / 8, ciphertext1.size());
   2053 
   2054     string ciphertext2 = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
   2055     EXPECT_EQ(key_size / 8, ciphertext2.size());
   2056 
   2057     // OAEP randomizes padding so every result should be different.
   2058     EXPECT_NE(ciphertext1, ciphertext2);
   2059 
   2060     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2061         EXPECT_EQ(3, GetParam()->keymaster0_calls());
   2062 }
   2063 
   2064 TEST_P(EncryptionOperationsTest, RsaOaepSha224Success) {
   2065     size_t key_size = 768;
   2066     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2067                                            .RsaEncryptionKey(key_size, 3)
   2068                                            .Padding(KM_PAD_RSA_OAEP)
   2069                                            .Digest(KM_DIGEST_SHA_2_224)));
   2070 
   2071     string message = "Hello";
   2072     string ciphertext1 = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
   2073     EXPECT_EQ(key_size / 8, ciphertext1.size());
   2074 
   2075     string ciphertext2 = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
   2076     EXPECT_EQ(key_size / 8, ciphertext2.size());
   2077 
   2078     // OAEP randomizes padding so every result should be different.
   2079     EXPECT_NE(ciphertext1, ciphertext2);
   2080 
   2081     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2082         EXPECT_EQ(3, GetParam()->keymaster0_calls());
   2083 }
   2084 
   2085 TEST_P(EncryptionOperationsTest, RsaOaepRoundTrip) {
   2086     size_t key_size = 768;
   2087     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2088                                            .RsaEncryptionKey(key_size, 3)
   2089                                            .Padding(KM_PAD_RSA_OAEP)
   2090                                            .Digest(KM_DIGEST_SHA_2_256)));
   2091     string message = "Hello World!";
   2092     string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
   2093     EXPECT_EQ(key_size / 8, ciphertext.size());
   2094 
   2095     string plaintext = DecryptMessage(ciphertext, KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
   2096     EXPECT_EQ(message, plaintext);
   2097 
   2098     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2099         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   2100 }
   2101 
   2102 TEST_P(EncryptionOperationsTest, RsaOaepSha224RoundTrip) {
   2103     size_t key_size = 768;
   2104     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2105                                            .RsaEncryptionKey(key_size, 3)
   2106                                            .Padding(KM_PAD_RSA_OAEP)
   2107                                            .Digest(KM_DIGEST_SHA_2_224)));
   2108     string message = "Hello World!";
   2109     string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
   2110     EXPECT_EQ(key_size / 8, ciphertext.size());
   2111 
   2112     string plaintext = DecryptMessage(ciphertext, KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
   2113     EXPECT_EQ(message, plaintext);
   2114 
   2115     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2116         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   2117 }
   2118 
   2119 TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
   2120     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2121                                            .RsaEncryptionKey(512, 3)
   2122                                            .Padding(KM_PAD_RSA_OAEP)
   2123                                            .Digest(KM_DIGEST_NONE)));
   2124     string message = "Hello World!";
   2125 
   2126     AuthorizationSet begin_params(client_params());
   2127     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
   2128     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
   2129     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   2130 
   2131     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2132         EXPECT_EQ(2, GetParam()->keymaster0_calls());
   2133 }
   2134 
   2135 TEST_P(EncryptionOperationsTest, RsaOaepUnauthorizedDigest) {
   2136     if (GetParam()->minimal_digest_set())
   2137         // We don't have two supported digests, so we can't try authorizing one and using another.
   2138         return;
   2139 
   2140     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2141                                            .RsaEncryptionKey(512, 3)
   2142                                            .Padding(KM_PAD_RSA_OAEP)
   2143                                            .Digest(KM_DIGEST_SHA_2_256)));
   2144     string message = "Hello World!";
   2145     // Works because encryption is a public key operation.
   2146     EncryptMessage(string(message), KM_DIGEST_SHA1, KM_PAD_RSA_OAEP);
   2147 
   2148     AuthorizationSet begin_params(client_params());
   2149     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
   2150     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA1);
   2151     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
   2152 
   2153     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2154         EXPECT_EQ(3, GetParam()->keymaster0_calls());
   2155 }
   2156 
   2157 TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
   2158     if (GetParam()->minimal_digest_set())
   2159         // We don't have two supported digests, so we can't try encrypting with one and decrypting
   2160         // with another.
   2161         return;
   2162 
   2163     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2164                                            .RsaEncryptionKey(768, 3)
   2165                                            .Padding(KM_PAD_RSA_OAEP)
   2166                                            .Digest(KM_DIGEST_SHA_2_256)
   2167                                            .Digest(KM_DIGEST_SHA_2_384)));
   2168     string message = "Hello World!";
   2169     string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
   2170 
   2171     string result;
   2172     size_t input_consumed;
   2173     AuthorizationSet begin_params(client_params());
   2174     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
   2175     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_384);
   2176     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
   2177     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
   2178     EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
   2179     EXPECT_EQ(0U, result.size());
   2180 
   2181     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2182         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   2183 }
   2184 
   2185 TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
   2186     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2187                                            .RsaEncryptionKey(512, 3)
   2188                                            .Padding(KM_PAD_RSA_OAEP)
   2189                                            .Digest(KM_DIGEST_SHA1)));
   2190     string message = "12345678901234567890123";
   2191     string result;
   2192     size_t input_consumed;
   2193 
   2194     AuthorizationSet begin_params(client_params());
   2195     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
   2196     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA1);
   2197     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   2198     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
   2199     EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&result));
   2200     EXPECT_EQ(0U, result.size());
   2201 
   2202     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2203         EXPECT_EQ(2, GetParam()->keymaster0_calls());
   2204 }
   2205 
   2206 TEST_P(EncryptionOperationsTest, RsaOaepCorruptedDecrypt) {
   2207     size_t key_size = 768;
   2208     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2209                                            .RsaEncryptionKey(768, 3)
   2210                                            .Padding(KM_PAD_RSA_OAEP)
   2211                                            .Digest(KM_DIGEST_SHA_2_256)));
   2212     string message = "Hello World!";
   2213     string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
   2214     EXPECT_EQ(key_size / 8, ciphertext.size());
   2215 
   2216     // Corrupt the ciphertext
   2217     ciphertext[key_size / 8 / 2]++;
   2218 
   2219     string result;
   2220     size_t input_consumed;
   2221     AuthorizationSet begin_params(client_params());
   2222     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
   2223     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
   2224     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
   2225     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
   2226     EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
   2227     EXPECT_EQ(0U, result.size());
   2228 
   2229     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2230         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   2231 }
   2232 
   2233 TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
   2234     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
   2235                                KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
   2236     string message = "Hello World!";
   2237     string ciphertext1 = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
   2238     EXPECT_EQ(512U / 8, ciphertext1.size());
   2239 
   2240     string ciphertext2 = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
   2241     EXPECT_EQ(512U / 8, ciphertext2.size());
   2242 
   2243     // PKCS1 v1.5 randomizes padding so every result should be different.
   2244     EXPECT_NE(ciphertext1, ciphertext2);
   2245 
   2246     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2247         EXPECT_EQ(3, GetParam()->keymaster0_calls());
   2248 }
   2249 
   2250 TEST_P(EncryptionOperationsTest, RsaPkcs1RoundTrip) {
   2251     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
   2252                                KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
   2253     string message = "Hello World!";
   2254     string ciphertext = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
   2255     EXPECT_EQ(512U / 8, ciphertext.size());
   2256 
   2257     string plaintext = DecryptMessage(ciphertext, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
   2258     EXPECT_EQ(message, plaintext);
   2259 
   2260     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2261         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   2262 }
   2263 
   2264 TEST_P(EncryptionOperationsTest, RsaRoundTripAllCombinations) {
   2265     size_t key_size = 2048;
   2266     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2267                                            .RsaEncryptionKey(key_size, 3)
   2268                                            .Padding(KM_PAD_RSA_PKCS1_1_5_ENCRYPT)
   2269                                            .Padding(KM_PAD_RSA_OAEP)
   2270                                            .Digest(KM_DIGEST_NONE)
   2271                                            .Digest(KM_DIGEST_MD5)
   2272                                            .Digest(KM_DIGEST_SHA1)
   2273                                            .Digest(KM_DIGEST_SHA_2_224)
   2274                                            .Digest(KM_DIGEST_SHA_2_256)
   2275                                            .Digest(KM_DIGEST_SHA_2_384)
   2276                                            .Digest(KM_DIGEST_SHA_2_512)));
   2277 
   2278     string message = "Hello World!";
   2279 
   2280     keymaster_padding_t padding_modes[] = {KM_PAD_RSA_OAEP, KM_PAD_RSA_PKCS1_1_5_ENCRYPT};
   2281     keymaster_digest_t digests[] = {
   2282         KM_DIGEST_NONE,      KM_DIGEST_MD5,       KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
   2283         KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
   2284     };
   2285 
   2286     for (auto padding : padding_modes)
   2287         for (auto digest : digests) {
   2288             if (padding == KM_PAD_RSA_OAEP && digest == KM_DIGEST_NONE)
   2289                 // OAEP requires a digest.
   2290                 continue;
   2291 
   2292             string ciphertext = EncryptMessage(message, digest, padding);
   2293             EXPECT_EQ(key_size / 8, ciphertext.size());
   2294 
   2295             string plaintext = DecryptMessage(ciphertext, digest, padding);
   2296             EXPECT_EQ(message, plaintext);
   2297         }
   2298 
   2299     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2300         EXPECT_EQ(40, GetParam()->keymaster0_calls());
   2301 }
   2302 
   2303 TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
   2304     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
   2305                                KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
   2306     string message = "123456789012345678901234567890123456789012345678901234";
   2307     string result;
   2308     size_t input_consumed;
   2309 
   2310     AuthorizationSet begin_params(client_params());
   2311     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
   2312     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   2313     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
   2314     EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&result));
   2315     EXPECT_EQ(0U, result.size());
   2316 
   2317     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2318         EXPECT_EQ(2, GetParam()->keymaster0_calls());
   2319 }
   2320 
   2321 TEST_P(EncryptionOperationsTest, RsaPkcs1CorruptedDecrypt) {
   2322     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
   2323                                KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
   2324     string message = "Hello World!";
   2325     string ciphertext = EncryptMessage(string(message), KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
   2326     EXPECT_EQ(512U / 8, ciphertext.size());
   2327 
   2328     // Corrupt the ciphertext
   2329     ciphertext[512 / 8 / 2]++;
   2330 
   2331     string result;
   2332     size_t input_consumed;
   2333     AuthorizationSet begin_params(client_params());
   2334     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
   2335     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
   2336     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
   2337     EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
   2338     EXPECT_EQ(0U, result.size());
   2339 
   2340     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2341         EXPECT_EQ(4, GetParam()->keymaster0_calls());
   2342 }
   2343 
   2344 TEST_P(EncryptionOperationsTest, RsaEncryptWithSigningKey) {
   2345     ASSERT_EQ(KM_ERROR_OK,
   2346               GenerateKey(AuthorizationSetBuilder().RsaSigningKey(256, 3).Padding(KM_PAD_NONE)));
   2347 
   2348     AuthorizationSet begin_params(client_params());
   2349     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2350     ASSERT_EQ(KM_ERROR_INCOMPATIBLE_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
   2351 
   2352     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   2353         EXPECT_EQ(2, GetParam()->keymaster0_calls());
   2354 }
   2355 
   2356 TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
   2357     ASSERT_EQ(KM_ERROR_OK,
   2358               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
   2359     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_ENCRYPT));
   2360     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT));
   2361 
   2362     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
   2363         EXPECT_EQ(3, GetParam()->keymaster0_calls());
   2364 }
   2365 
   2366 TEST_P(EncryptionOperationsTest, HmacEncrypt) {
   2367     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2368                                            .HmacKey(128)
   2369                                            .Digest(KM_DIGEST_SHA_2_256)
   2370                                            .Padding(KM_PAD_NONE)
   2371                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
   2372     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_ENCRYPT));
   2373     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT));
   2374 
   2375     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2376 }
   2377 
   2378 TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
   2379     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2380                                            .AesEncryptionKey(128)
   2381                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
   2382                                            .Padding(KM_PAD_NONE)));
   2383     // Two-block message.
   2384     string message = "12345678901234567890123456789012";
   2385     string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
   2386     EXPECT_EQ(message.size(), ciphertext1.size());
   2387 
   2388     string ciphertext2 = EncryptMessage(string(message), KM_MODE_ECB, KM_PAD_NONE);
   2389     EXPECT_EQ(message.size(), ciphertext2.size());
   2390 
   2391     // ECB is deterministic.
   2392     EXPECT_EQ(ciphertext1, ciphertext2);
   2393 
   2394     string plaintext = DecryptMessage(ciphertext1, KM_MODE_ECB, KM_PAD_NONE);
   2395     EXPECT_EQ(message, plaintext);
   2396 
   2397     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2398 }
   2399 
   2400 TEST_P(EncryptionOperationsTest, AesEcbNotAuthorized) {
   2401     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2402                                            .AesEncryptionKey(128)
   2403                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
   2404                                            .Padding(KM_PAD_NONE)));
   2405     // Two-block message.
   2406     string message = "12345678901234567890123456789012";
   2407     AuthorizationSet begin_params(client_params());
   2408     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
   2409     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2410     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_BLOCK_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   2411 
   2412     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2413 }
   2414 
   2415 TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
   2416     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2417                                            .AesEncryptionKey(128)
   2418                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
   2419                                            .Padding(KM_PAD_NONE)));
   2420     // Message is slightly shorter than two blocks.
   2421     string message = "1234567890123456789012345678901";
   2422 
   2423     AuthorizationSet begin_params(client_params());
   2424     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
   2425     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2426     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   2427     string ciphertext;
   2428     size_t input_consumed;
   2429     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &ciphertext, &input_consumed));
   2430     EXPECT_EQ(message.size(), input_consumed);
   2431     EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&ciphertext));
   2432 
   2433     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2434 }
   2435 
   2436 TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
   2437     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2438                                            .AesEncryptionKey(128)
   2439                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
   2440                                            .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
   2441 
   2442     // Try various message lengths; all should work.
   2443     for (size_t i = 0; i < 32; ++i) {
   2444         string message(i, 'a');
   2445         string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
   2446         EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
   2447         string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
   2448         EXPECT_EQ(message, plaintext);
   2449     }
   2450 
   2451     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2452 }
   2453 
   2454 TEST_P(EncryptionOperationsTest, AesEcbNoPaddingKeyWithPkcs7Padding) {
   2455     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2456                                            .AesEncryptionKey(128)
   2457                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
   2458                                            .Authorization(TAG_PADDING, KM_PAD_NONE)));
   2459 
   2460     // Try various message lengths; all should fail.
   2461     for (size_t i = 0; i < 32; ++i) {
   2462         AuthorizationSet begin_params(client_params());
   2463         begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
   2464         begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
   2465         EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE,
   2466                   BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   2467     }
   2468 
   2469     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2470 }
   2471 
   2472 TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
   2473     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2474                                            .AesEncryptionKey(128)
   2475                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
   2476                                            .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
   2477 
   2478     string message = "a";
   2479     string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
   2480     EXPECT_EQ(16U, ciphertext.size());
   2481     EXPECT_NE(ciphertext, message);
   2482     ++ciphertext[ciphertext.size() / 2];
   2483 
   2484     AuthorizationSet begin_params(client_params());
   2485     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
   2486     begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
   2487     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
   2488     string plaintext;
   2489     size_t input_consumed;
   2490     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &plaintext, &input_consumed));
   2491     EXPECT_EQ(ciphertext.size(), input_consumed);
   2492     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&plaintext));
   2493 
   2494     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2495 }
   2496 
   2497 TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
   2498     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2499                                            .AesEncryptionKey(128)
   2500                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
   2501                                            .Padding(KM_PAD_NONE)));
   2502     string message = "123";
   2503     string iv1;
   2504     string ciphertext1 = EncryptMessage(message, KM_MODE_CTR, KM_PAD_NONE, &iv1);
   2505     EXPECT_EQ(message.size(), ciphertext1.size());
   2506     EXPECT_EQ(16U, iv1.size());
   2507 
   2508     string iv2;
   2509     string ciphertext2 = EncryptMessage(message, KM_MODE_CTR, KM_PAD_NONE, &iv2);
   2510     EXPECT_EQ(message.size(), ciphertext2.size());
   2511     EXPECT_EQ(16U, iv2.size());
   2512 
   2513     // IVs should be random, so ciphertexts should differ.
   2514     EXPECT_NE(iv1, iv2);
   2515     EXPECT_NE(ciphertext1, ciphertext2);
   2516 
   2517     string plaintext = DecryptMessage(ciphertext1, KM_MODE_CTR, KM_PAD_NONE, iv1);
   2518     EXPECT_EQ(message, plaintext);
   2519 
   2520     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2521 }
   2522 
   2523 TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
   2524     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2525                                            .AesEncryptionKey(128)
   2526                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
   2527                                            .Padding(KM_PAD_NONE)));
   2528 
   2529     int increment = 15;
   2530     string message(239, 'a');
   2531     AuthorizationSet input_params(client_params());
   2532     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
   2533     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2534     AuthorizationSet output_params;
   2535     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
   2536 
   2537     string ciphertext;
   2538     size_t input_consumed;
   2539     for (size_t i = 0; i < message.size(); i += increment)
   2540         EXPECT_EQ(KM_ERROR_OK,
   2541                   UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
   2542     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
   2543     EXPECT_EQ(message.size(), ciphertext.size());
   2544 
   2545     // Move TAG_NONCE into input_params
   2546     input_params.Reinitialize(output_params);
   2547     input_params.push_back(client_params());
   2548     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
   2549     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2550     output_params.Clear();
   2551 
   2552     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
   2553     string plaintext;
   2554     for (size_t i = 0; i < ciphertext.size(); i += increment)
   2555         EXPECT_EQ(KM_ERROR_OK,
   2556                   UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
   2557     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
   2558     EXPECT_EQ(ciphertext.size(), plaintext.size());
   2559     EXPECT_EQ(message, plaintext);
   2560 
   2561     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2562 }
   2563 
   2564 struct AesCtrSp80038aTestVector {
   2565     const char* key;
   2566     const char* nonce;
   2567     const char* plaintext;
   2568     const char* ciphertext;
   2569 };
   2570 
   2571 // These test vectors are taken from
   2572 // http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
   2573 static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
   2574     // AES-128
   2575     {
   2576         "2b7e151628aed2a6abf7158809cf4f3c", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
   2577         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
   2578         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
   2579         "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
   2580         "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
   2581     },
   2582     // AES-192
   2583     {
   2584         "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
   2585         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
   2586         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
   2587         "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
   2588         "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
   2589     },
   2590     // AES-256
   2591     {
   2592         "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
   2593         "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
   2594         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
   2595         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
   2596         "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
   2597         "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
   2598     },
   2599 };
   2600 
   2601 TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
   2602     for (size_t i = 0; i < 3; i++) {
   2603         const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
   2604         const string key = hex2str(test.key);
   2605         const string nonce = hex2str(test.nonce);
   2606         const string plaintext = hex2str(test.plaintext);
   2607         const string ciphertext = hex2str(test.ciphertext);
   2608         CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
   2609     }
   2610 
   2611     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2612 }
   2613 
   2614 TEST_P(EncryptionOperationsTest, AesCtrInvalidPaddingMode) {
   2615     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2616                                            .AesEncryptionKey(128)
   2617                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
   2618                                            .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
   2619     AuthorizationSet begin_params(client_params());
   2620     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
   2621     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2622     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   2623 
   2624     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2625 }
   2626 
   2627 TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
   2628     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2629                                            .AesEncryptionKey(128)
   2630                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
   2631                                            .Authorization(TAG_CALLER_NONCE)
   2632                                            .Padding(KM_PAD_NONE)));
   2633 
   2634     AuthorizationSet input_params(client_params());
   2635     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
   2636     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2637     input_params.push_back(TAG_NONCE, "123", 3);
   2638     EXPECT_EQ(KM_ERROR_INVALID_NONCE, BeginOperation(KM_PURPOSE_ENCRYPT, input_params));
   2639 
   2640     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2641 }
   2642 
   2643 TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
   2644     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2645                                            .AesEncryptionKey(128)
   2646                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
   2647                                            .Padding(KM_PAD_NONE)));
   2648     // Two-block message.
   2649     string message = "12345678901234567890123456789012";
   2650     string iv1;
   2651     string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
   2652     EXPECT_EQ(message.size(), ciphertext1.size());
   2653 
   2654     string iv2;
   2655     string ciphertext2 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv2);
   2656     EXPECT_EQ(message.size(), ciphertext2.size());
   2657 
   2658     // IVs should be random, so ciphertexts should differ.
   2659     EXPECT_NE(iv1, iv2);
   2660     EXPECT_NE(ciphertext1, ciphertext2);
   2661 
   2662     string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
   2663     EXPECT_EQ(message, plaintext);
   2664 
   2665     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2666 }
   2667 
   2668 TEST_P(EncryptionOperationsTest, AesCallerNonce) {
   2669     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2670                                            .AesEncryptionKey(128)
   2671                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
   2672                                            .Authorization(TAG_CALLER_NONCE)
   2673                                            .Padding(KM_PAD_NONE)));
   2674     string message = "12345678901234567890123456789012";
   2675     string iv1;
   2676     // Don't specify nonce, should get a random one.
   2677     string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
   2678     EXPECT_EQ(message.size(), ciphertext1.size());
   2679     EXPECT_EQ(16U, iv1.size());
   2680 
   2681     string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
   2682     EXPECT_EQ(message, plaintext);
   2683 
   2684     // Now specify a nonce, should also work.
   2685     AuthorizationSet input_params(client_params());
   2686     AuthorizationSet update_params;
   2687     AuthorizationSet output_params;
   2688     input_params.push_back(TAG_NONCE, "abcdefghijklmnop", 16);
   2689     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
   2690     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2691     string ciphertext2 =
   2692         ProcessMessage(KM_PURPOSE_ENCRYPT, message, input_params, update_params, &output_params);
   2693 
   2694     // Decrypt with correct nonce.
   2695     plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
   2696                                &output_params);
   2697     EXPECT_EQ(message, plaintext);
   2698 
   2699     // Now try with wrong nonce.
   2700     input_params.Reinitialize(client_params());
   2701     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
   2702     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2703     input_params.push_back(TAG_NONCE, "aaaaaaaaaaaaaaaa", 16);
   2704     plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
   2705                                &output_params);
   2706     EXPECT_NE(message, plaintext);
   2707 
   2708     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2709 }
   2710 
   2711 TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
   2712     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2713                                            .AesEncryptionKey(128)
   2714                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
   2715                                            .Padding(KM_PAD_NONE)));
   2716 
   2717     string message = "12345678901234567890123456789012";
   2718     string iv1;
   2719     // Don't specify nonce, should get a random one.
   2720     string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
   2721     EXPECT_EQ(message.size(), ciphertext1.size());
   2722     EXPECT_EQ(16U, iv1.size());
   2723 
   2724     string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
   2725     EXPECT_EQ(message, plaintext);
   2726 
   2727     // Now specify a nonce, should fail.
   2728     AuthorizationSet input_params(client_params());
   2729     AuthorizationSet update_params;
   2730     AuthorizationSet output_params;
   2731     input_params.push_back(TAG_NONCE, "abcdefghijklmnop", 16);
   2732     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
   2733     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2734 
   2735     EXPECT_EQ(KM_ERROR_CALLER_NONCE_PROHIBITED,
   2736               BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
   2737 
   2738     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2739 }
   2740 
   2741 TEST_P(EncryptionOperationsTest, AesCbcIncrementalNoPadding) {
   2742     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2743                                            .AesEncryptionKey(128)
   2744                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
   2745                                            .Padding(KM_PAD_NONE)));
   2746 
   2747     int increment = 15;
   2748     string message(240, 'a');
   2749     AuthorizationSet input_params(client_params());
   2750     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
   2751     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2752     AuthorizationSet output_params;
   2753     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
   2754 
   2755     string ciphertext;
   2756     size_t input_consumed;
   2757     for (size_t i = 0; i < message.size(); i += increment)
   2758         EXPECT_EQ(KM_ERROR_OK,
   2759                   UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
   2760     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
   2761     EXPECT_EQ(message.size(), ciphertext.size());
   2762 
   2763     // Move TAG_NONCE into input_params
   2764     input_params.Reinitialize(output_params);
   2765     input_params.push_back(client_params());
   2766     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
   2767     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2768     output_params.Clear();
   2769 
   2770     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
   2771     string plaintext;
   2772     for (size_t i = 0; i < ciphertext.size(); i += increment)
   2773         EXPECT_EQ(KM_ERROR_OK,
   2774                   UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
   2775     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
   2776     EXPECT_EQ(ciphertext.size(), plaintext.size());
   2777     EXPECT_EQ(message, plaintext);
   2778 
   2779     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2780 }
   2781 
   2782 TEST_P(EncryptionOperationsTest, AesCbcPkcs7Padding) {
   2783     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2784                                            .AesEncryptionKey(128)
   2785                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
   2786                                            .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
   2787 
   2788     // Try various message lengths; all should work.
   2789     for (size_t i = 0; i < 32; ++i) {
   2790         string message(i, 'a');
   2791         string iv;
   2792         string ciphertext = EncryptMessage(message, KM_MODE_CBC, KM_PAD_PKCS7, &iv);
   2793         EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
   2794         string plaintext = DecryptMessage(ciphertext, KM_MODE_CBC, KM_PAD_PKCS7, iv);
   2795         EXPECT_EQ(message, plaintext);
   2796     }
   2797 
   2798     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2799 }
   2800 
   2801 TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
   2802     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2803                                            .AesEncryptionKey(128)
   2804                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
   2805                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
   2806                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
   2807     string aad = "foobar";
   2808     string message = "123456789012345678901234567890123456";
   2809     AuthorizationSet begin_params(client_params());
   2810     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
   2811     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2812     begin_params.push_back(TAG_MAC_LENGTH, 128);
   2813 
   2814     AuthorizationSet update_params;
   2815     update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
   2816 
   2817     // Encrypt
   2818     AuthorizationSet begin_out_params;
   2819     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
   2820     string ciphertext;
   2821     size_t input_consumed;
   2822     AuthorizationSet update_out_params;
   2823     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
   2824                                            &input_consumed));
   2825     EXPECT_EQ(message.size(), input_consumed);
   2826     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
   2827 
   2828     // Grab nonce
   2829     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
   2830     begin_params.push_back(begin_out_params);
   2831 
   2832     // Decrypt.
   2833     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
   2834     string plaintext;
   2835     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
   2836                                            &plaintext, &input_consumed));
   2837     EXPECT_EQ(ciphertext.size(), input_consumed);
   2838     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
   2839 
   2840     EXPECT_EQ(message, plaintext);
   2841     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2842 }
   2843 
   2844 TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
   2845     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2846                                            .AesEncryptionKey(128)
   2847                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
   2848                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
   2849                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
   2850     string aad = "foobar";
   2851     string message = "123456789012345678901234567890123456";
   2852     AuthorizationSet begin_params(client_params());
   2853     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
   2854     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2855     begin_params.push_back(TAG_MAC_LENGTH, 96);
   2856 
   2857     AuthorizationSet update_params;
   2858     update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
   2859 
   2860     AuthorizationSet begin_out_params;
   2861     EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH,
   2862               BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
   2863 
   2864     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2865 }
   2866 
   2867 TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
   2868     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2869                                            .AesEncryptionKey(128)
   2870                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
   2871                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
   2872                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
   2873     string aad = "foobar";
   2874     string message = "123456789012345678901234567890123456";
   2875     AuthorizationSet begin_params(client_params());
   2876     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
   2877     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2878     begin_params.push_back(TAG_MAC_LENGTH, 128);
   2879 
   2880     AuthorizationSet update_params;
   2881     update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
   2882 
   2883     // Encrypt
   2884     AuthorizationSet begin_out_params;
   2885     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
   2886     string ciphertext;
   2887     size_t input_consumed;
   2888     AuthorizationSet update_out_params;
   2889     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
   2890                                            &input_consumed));
   2891     EXPECT_EQ(message.size(), input_consumed);
   2892     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
   2893 
   2894     // Grab nonce
   2895     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
   2896     begin_params.Reinitialize(client_params());
   2897     begin_params.push_back(begin_out_params);
   2898     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
   2899     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2900     begin_params.push_back(TAG_MAC_LENGTH, 96);
   2901 
   2902     // Decrypt.
   2903     EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
   2904 
   2905     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2906 }
   2907 
   2908 TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
   2909     uint8_t nonce[] = {
   2910         0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
   2911     };
   2912     uint8_t ciphertext[] = {
   2913         0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc, 0xd2, 0xcb, 0x16,
   2914         0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78, 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a,
   2915         0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d, 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76,
   2916         0x76, 0x5e, 0xfb, 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
   2917         0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
   2918     };
   2919     string ciphertext_str(reinterpret_cast<char*>(ciphertext), sizeof(ciphertext));
   2920 
   2921     AuthorizationSet begin_params(client_params());
   2922     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
   2923     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2924     begin_params.push_back(TAG_MAC_LENGTH, 128);
   2925     begin_params.push_back(TAG_NONCE, nonce, sizeof(nonce));
   2926 
   2927     string plaintext;
   2928     size_t input_consumed;
   2929 
   2930     // Import correct key and decrypt
   2931     uint8_t good_key[] = {
   2932         0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
   2933         0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
   2934     };
   2935     string good_key_str(reinterpret_cast<char*>(good_key), sizeof(good_key));
   2936     ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
   2937                                          .AesEncryptionKey(128)
   2938                                          .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
   2939                                          .Authorization(TAG_PADDING, KM_PAD_NONE)
   2940                                          .Authorization(TAG_CALLER_NONCE)
   2941                                          .Authorization(TAG_MIN_MAC_LENGTH, 128),
   2942                                      KM_KEY_FORMAT_RAW, good_key_str));
   2943     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
   2944     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext_str, &plaintext, &input_consumed));
   2945     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
   2946 
   2947     // Import bad key and decrypt
   2948     uint8_t bad_key[] = {
   2949         0xbb, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
   2950         0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
   2951     };
   2952     string bad_key_str(reinterpret_cast<char*>(bad_key), sizeof(bad_key));
   2953     ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
   2954                                          .AesEncryptionKey(128)
   2955                                          .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
   2956                                          .Authorization(TAG_PADDING, KM_PAD_NONE)
   2957                                          .Authorization(TAG_MIN_MAC_LENGTH, 128),
   2958                                      KM_KEY_FORMAT_RAW, bad_key_str));
   2959     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
   2960     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext_str, &plaintext, &input_consumed));
   2961     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
   2962 
   2963     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   2964 }
   2965 
   2966 TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
   2967     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   2968                                            .AesEncryptionKey(128)
   2969                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
   2970                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
   2971                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
   2972     string aad = "123456789012345678";
   2973     string empty_message;
   2974     AuthorizationSet begin_params(client_params());
   2975     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
   2976     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   2977     begin_params.push_back(TAG_MAC_LENGTH, 128);
   2978 
   2979     AuthorizationSet update_params;
   2980     update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
   2981 
   2982     // Encrypt
   2983     AuthorizationSet begin_out_params;
   2984     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
   2985     string ciphertext;
   2986     size_t input_consumed;
   2987     AuthorizationSet update_out_params;
   2988     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, empty_message, &update_out_params,
   2989                                            &ciphertext, &input_consumed));
   2990     EXPECT_EQ(0U, input_consumed);
   2991     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
   2992 
   2993     // Grab nonce
   2994     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
   2995     begin_params.push_back(begin_out_params);
   2996 
   2997     // Decrypt.
   2998     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
   2999     string plaintext;
   3000     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
   3001                                            &plaintext, &input_consumed));
   3002     EXPECT_EQ(ciphertext.size(), input_consumed);
   3003     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
   3004 
   3005     EXPECT_EQ(empty_message, plaintext);
   3006     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3007 }
   3008 
   3009 TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
   3010     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   3011                                            .AesEncryptionKey(128)
   3012                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
   3013                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
   3014                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
   3015     AuthorizationSet begin_params(client_params());
   3016     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
   3017     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   3018     begin_params.push_back(TAG_MAC_LENGTH, 128);
   3019 
   3020     AuthorizationSet update_params;
   3021     update_params.push_back(TAG_ASSOCIATED_DATA, "b", 1);
   3022 
   3023     // Encrypt
   3024     AuthorizationSet begin_out_params;
   3025     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
   3026     string ciphertext;
   3027     size_t input_consumed;
   3028     AuthorizationSet update_out_params;
   3029 
   3030     // Send AAD, incrementally
   3031     for (int i = 0; i < 1000; ++i) {
   3032         EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "", &update_out_params, &ciphertext,
   3033                                                &input_consumed));
   3034         EXPECT_EQ(0U, input_consumed);
   3035         EXPECT_EQ(0U, ciphertext.size());
   3036     }
   3037 
   3038     // Now send data, incrementally, no data.
   3039     AuthorizationSet empty_params;
   3040     for (int i = 0; i < 1000; ++i) {
   3041         EXPECT_EQ(KM_ERROR_OK, UpdateOperation(empty_params, "a", &update_out_params, &ciphertext,
   3042                                                &input_consumed));
   3043         EXPECT_EQ(1U, input_consumed);
   3044     }
   3045     EXPECT_EQ(1000U, ciphertext.size());
   3046 
   3047     // And finish.
   3048     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
   3049     EXPECT_EQ(1016U, ciphertext.size());
   3050 
   3051     // Grab nonce
   3052     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
   3053     begin_params.push_back(begin_out_params);
   3054 
   3055     // Decrypt.
   3056     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
   3057     string plaintext;
   3058 
   3059     // Send AAD, incrementally, no data
   3060     for (int i = 0; i < 1000; ++i) {
   3061         EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "", &update_out_params, &plaintext,
   3062                                                &input_consumed));
   3063         EXPECT_EQ(0U, input_consumed);
   3064         EXPECT_EQ(0U, plaintext.size());
   3065     }
   3066 
   3067     // Now send data, incrementally.
   3068     for (size_t i = 0; i < ciphertext.length(); ++i) {
   3069         EXPECT_EQ(KM_ERROR_OK, UpdateOperation(empty_params, string(ciphertext.data() + i, 1),
   3070                                                &update_out_params, &plaintext, &input_consumed));
   3071         EXPECT_EQ(1U, input_consumed);
   3072     }
   3073     EXPECT_EQ(1000U, plaintext.size());
   3074     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
   3075 
   3076     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3077 }
   3078 
   3079 TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
   3080     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   3081                                            .AesEncryptionKey(128)
   3082                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
   3083                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
   3084                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
   3085     string message = "123456789012345678901234567890123456";
   3086     AuthorizationSet begin_params(client_params());
   3087     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
   3088     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   3089     begin_params.push_back(TAG_MAC_LENGTH, 128);
   3090     AuthorizationSet begin_out_params;
   3091 
   3092     AuthorizationSet update_params;
   3093     update_params.push_back(TAG_ASSOCIATED_DATA, "foo", 3);
   3094 
   3095     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
   3096 
   3097     // No data, AAD only.
   3098     string ciphertext;
   3099     size_t input_consumed;
   3100     AuthorizationSet update_out_params;
   3101     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "" /* message */, &update_out_params,
   3102                                            &ciphertext, &input_consumed));
   3103     EXPECT_EQ(0U, input_consumed);
   3104 
   3105     // AAD and data.
   3106     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
   3107                                            &input_consumed));
   3108     EXPECT_EQ(message.size(), input_consumed);
   3109     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
   3110 
   3111     // Grab nonce.
   3112     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
   3113     begin_params.push_back(begin_out_params);
   3114 
   3115     // Decrypt
   3116     update_params.Clear();
   3117     update_params.push_back(TAG_ASSOCIATED_DATA, "foofoo", 6);
   3118 
   3119     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
   3120     string plaintext;
   3121     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
   3122                                            &plaintext, &input_consumed));
   3123     EXPECT_EQ(ciphertext.size(), input_consumed);
   3124     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
   3125 
   3126     EXPECT_EQ(message, plaintext);
   3127     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3128 }
   3129 
   3130 TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
   3131     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   3132                                            .AesEncryptionKey(128)
   3133                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
   3134                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
   3135                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
   3136     string message = "12345678901234567890123456789012";
   3137     AuthorizationSet begin_params(client_params());
   3138     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
   3139     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   3140     begin_params.push_back(TAG_MAC_LENGTH, 128);
   3141 
   3142     AuthorizationSet update_params;
   3143     update_params.push_back(TAG_ASSOCIATED_DATA, "foobar", 6);
   3144 
   3145     AuthorizationSet finish_params;
   3146     AuthorizationSet finish_out_params;
   3147 
   3148     // Encrypt
   3149     AuthorizationSet begin_out_params;
   3150     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
   3151     AuthorizationSet update_out_params;
   3152     string ciphertext;
   3153     size_t input_consumed;
   3154     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
   3155                                            &input_consumed));
   3156     EXPECT_EQ(message.size(), input_consumed);
   3157     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
   3158 
   3159     // Grab nonce
   3160     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
   3161     begin_params.push_back(begin_out_params);
   3162 
   3163     update_params.Clear();
   3164     update_params.push_back(TAG_ASSOCIATED_DATA, "barfoo" /* Wrong AAD */, 6);
   3165 
   3166     // Decrypt.
   3167     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
   3168     string plaintext;
   3169     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
   3170                                            &plaintext, &input_consumed));
   3171     EXPECT_EQ(ciphertext.size(), input_consumed);
   3172     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
   3173 
   3174     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3175 }
   3176 
   3177 TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
   3178     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   3179                                            .AesEncryptionKey(128)
   3180                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
   3181                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
   3182                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
   3183     string message = "12345678901234567890123456789012";
   3184     AuthorizationSet begin_params(client_params());
   3185     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
   3186     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   3187     begin_params.push_back(TAG_MAC_LENGTH, 128);
   3188 
   3189     AuthorizationSet update_params;
   3190     update_params.push_back(TAG_ASSOCIATED_DATA, "foobar", 6);
   3191 
   3192     // Encrypt
   3193     AuthorizationSet begin_out_params;
   3194     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
   3195     AuthorizationSet update_out_params;
   3196     string ciphertext;
   3197     size_t input_consumed;
   3198     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
   3199                                            &input_consumed));
   3200     EXPECT_EQ(message.size(), input_consumed);
   3201     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
   3202 
   3203     begin_params.push_back(TAG_NONCE, "123456789012", 12);
   3204 
   3205     // Decrypt
   3206     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
   3207     string plaintext;
   3208     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
   3209                                            &plaintext, &input_consumed));
   3210     EXPECT_EQ(ciphertext.size(), input_consumed);
   3211     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
   3212 
   3213     // With wrong nonce, should have gotten garbage plaintext.
   3214     EXPECT_NE(message, plaintext);
   3215     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3216 }
   3217 
   3218 TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
   3219     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   3220                                            .AesEncryptionKey(128)
   3221                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
   3222                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
   3223                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
   3224     string aad = "foobar";
   3225     string message = "123456789012345678901234567890123456";
   3226     AuthorizationSet begin_params(client_params());
   3227     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
   3228     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   3229     begin_params.push_back(TAG_MAC_LENGTH, 128);
   3230     AuthorizationSet begin_out_params;
   3231 
   3232     AuthorizationSet update_params;
   3233     update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
   3234 
   3235     // Encrypt
   3236     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
   3237     AuthorizationSet update_out_params;
   3238     string ciphertext;
   3239     size_t input_consumed;
   3240     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
   3241                                            &input_consumed));
   3242     EXPECT_EQ(message.size(), input_consumed);
   3243     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
   3244 
   3245     // Corrupt tag
   3246     (*ciphertext.rbegin())++;
   3247 
   3248     // Grab nonce.
   3249     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
   3250     begin_params.push_back(begin_out_params);
   3251 
   3252     // Decrypt.
   3253     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
   3254     string plaintext;
   3255     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
   3256                                            &plaintext, &input_consumed));
   3257     EXPECT_EQ(ciphertext.size(), input_consumed);
   3258     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
   3259 
   3260     EXPECT_EQ(message, plaintext);
   3261     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3262 }
   3263 
   3264 typedef Keymaster2Test MaxOperationsTest;
   3265 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, MaxOperationsTest, test_params);
   3266 
   3267 TEST_P(MaxOperationsTest, TestLimit) {
   3268     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   3269                                            .AesEncryptionKey(128)
   3270                                            .EcbMode()
   3271                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
   3272                                            .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
   3273 
   3274     string message = "1234567890123456";
   3275     string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
   3276     string ciphertext2 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
   3277     string ciphertext3 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
   3278 
   3279     // Fourth time should fail.
   3280     AuthorizationSet begin_params(client_params());
   3281     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
   3282     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   3283     EXPECT_EQ(KM_ERROR_KEY_MAX_OPS_EXCEEDED, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   3284 
   3285     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3286 }
   3287 
   3288 TEST_P(MaxOperationsTest, TestAbort) {
   3289     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   3290                                            .AesEncryptionKey(128)
   3291                                            .EcbMode()
   3292                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
   3293                                            .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
   3294 
   3295     string message = "1234567890123456";
   3296     string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
   3297     string ciphertext2 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
   3298     string ciphertext3 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
   3299 
   3300     // Fourth time should fail.
   3301     AuthorizationSet begin_params(client_params());
   3302     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
   3303     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   3304     EXPECT_EQ(KM_ERROR_KEY_MAX_OPS_EXCEEDED, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   3305 
   3306     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3307 }
   3308 
   3309 typedef Keymaster2Test AddEntropyTest;
   3310 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, AddEntropyTest, test_params);
   3311 
   3312 TEST_P(AddEntropyTest, AddEntropy) {
   3313     // There's no obvious way to test that entropy is actually added, but we can test that the API
   3314     // doesn't blow up or return an error.
   3315     EXPECT_EQ(KM_ERROR_OK,
   3316               device()->add_rng_entropy(device(), reinterpret_cast<const uint8_t*>("foo"), 3));
   3317 
   3318     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3319 }
   3320 
   3321 typedef Keymaster2Test Keymaster0AdapterTest;
   3322 INSTANTIATE_TEST_CASE_P(
   3323     AndroidKeymasterTest, Keymaster0AdapterTest,
   3324     ::testing::Values(
   3325         InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(true /* support_ec */)),
   3326         InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(false /* support_ec */))));
   3327 
   3328 TEST_P(Keymaster0AdapterTest, OldSoftwareKeymaster1RsaBlob) {
   3329     // Load and use an old-style Keymaster1 software key blob.  These blobs contain OCB-encrypted
   3330     // key data.
   3331     string km1_sw = read_file("km1_sw_rsa_512.blob");
   3332     EXPECT_EQ(486U, km1_sw.length());
   3333 
   3334     uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km1_sw.length()));
   3335     memcpy(key_data, km1_sw.data(), km1_sw.length());
   3336     set_key_blob(key_data, km1_sw.length());
   3337 
   3338     string message(64, 'a');
   3339     string signature;
   3340     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
   3341 
   3342     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3343 }
   3344 
   3345 TEST_P(Keymaster0AdapterTest, UnversionedSoftwareKeymaster1RsaBlob) {
   3346     // Load and use an old-style Keymaster1 software key blob, without the version byte.  These
   3347     // blobs contain OCB-encrypted key data.
   3348     string km1_sw = read_file("km1_sw_rsa_512_unversioned.blob");
   3349     EXPECT_EQ(477U, km1_sw.length());
   3350 
   3351     uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km1_sw.length()));
   3352     memcpy(key_data, km1_sw.data(), km1_sw.length());
   3353     set_key_blob(key_data, km1_sw.length());
   3354 
   3355     string message(64, 'a');
   3356     string signature;
   3357     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
   3358 
   3359     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3360 }
   3361 
   3362 TEST_P(Keymaster0AdapterTest, OldSoftwareKeymaster1EcdsaBlob) {
   3363     // Load and use an old-style Keymaster1 software key blob.  These blobs contain OCB-encrypted
   3364     // key data.
   3365     string km1_sw = read_file("km1_sw_ecdsa_256.blob");
   3366     EXPECT_EQ(270U, km1_sw.length());
   3367 
   3368     uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km1_sw.length()));
   3369     memcpy(key_data, km1_sw.data(), km1_sw.length());
   3370     set_key_blob(key_data, km1_sw.length());
   3371 
   3372     string message(32, static_cast<char>(0xFF));
   3373     string signature;
   3374     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
   3375 
   3376     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3377 }
   3378 
   3379 struct Malloc_Delete {
   3380     void operator()(void* p) { free(p); }
   3381 };
   3382 
   3383 TEST_P(Keymaster0AdapterTest, OldSoftwareKeymaster0RsaBlob) {
   3384     // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
   3385     string km0_sw = read_file("km0_sw_rsa_512.blob");
   3386     EXPECT_EQ(333U, km0_sw.length());
   3387 
   3388     uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
   3389     memcpy(key_data, km0_sw.data(), km0_sw.length());
   3390     set_key_blob(key_data, km0_sw.length());
   3391 
   3392     string message(64, 'a');
   3393     string signature;
   3394     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
   3395 
   3396     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3397 }
   3398 
   3399 TEST_P(Keymaster0AdapterTest, OldSwKeymaster0RsaBlobGetCharacteristics) {
   3400     // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
   3401     string km0_sw = read_file("km0_sw_rsa_512.blob");
   3402     EXPECT_EQ(333U, km0_sw.length());
   3403 
   3404     uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
   3405     memcpy(key_data, km0_sw.data(), km0_sw.length());
   3406     set_key_blob(key_data, km0_sw.length());
   3407 
   3408     EXPECT_EQ(KM_ERROR_OK, GetCharacteristics());
   3409     EXPECT_TRUE(contains(sw_enforced(), TAG_ALGORITHM, KM_ALGORITHM_RSA));
   3410     EXPECT_TRUE(contains(sw_enforced(), TAG_KEY_SIZE, 512));
   3411     EXPECT_TRUE(contains(sw_enforced(), TAG_RSA_PUBLIC_EXPONENT, 3));
   3412     EXPECT_TRUE(contains(sw_enforced(), TAG_DIGEST, KM_DIGEST_NONE));
   3413     EXPECT_TRUE(contains(sw_enforced(), TAG_PADDING, KM_PAD_NONE));
   3414     EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_SIGN));
   3415     EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_VERIFY));
   3416     EXPECT_TRUE(sw_enforced().GetTagValue(TAG_ALL_USERS));
   3417     EXPECT_TRUE(sw_enforced().GetTagValue(TAG_NO_AUTH_REQUIRED));
   3418 
   3419     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3420 }
   3421 
   3422 TEST_P(Keymaster0AdapterTest, OldHwKeymaster0RsaBlob) {
   3423     // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
   3424     string km0_sw = read_file("km0_sw_rsa_512.blob");
   3425     EXPECT_EQ(333U, km0_sw.length());
   3426 
   3427     // The keymaster0 wrapper swaps the old softkeymaster leading 'P' for a 'Q' to make the key not
   3428     // be recognized as a software key.  Do the same here to pretend this is a hardware key.
   3429     EXPECT_EQ('P', km0_sw[0]);
   3430     km0_sw[0] = 'Q';
   3431 
   3432     uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
   3433     memcpy(key_data, km0_sw.data(), km0_sw.length());
   3434     set_key_blob(key_data, km0_sw.length());
   3435 
   3436     string message(64, 'a');
   3437     string signature;
   3438     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
   3439     VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
   3440 
   3441     EXPECT_EQ(5, GetParam()->keymaster0_calls());
   3442 }
   3443 
   3444 TEST_P(Keymaster0AdapterTest, OldHwKeymaster0RsaBlobGetCharacteristics) {
   3445     // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
   3446     string km0_sw = read_file("km0_sw_rsa_512.blob");
   3447     EXPECT_EQ(333U, km0_sw.length());
   3448 
   3449     // The keymaster0 wrapper swaps the old softkeymaster leading 'P' for a 'Q' to make the key not
   3450     // be recognized as a software key.  Do the same here to pretend this is a hardware key.
   3451     EXPECT_EQ('P', km0_sw[0]);
   3452     km0_sw[0] = 'Q';
   3453 
   3454     uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
   3455     memcpy(key_data, km0_sw.data(), km0_sw.length());
   3456     set_key_blob(key_data, km0_sw.length());
   3457 
   3458     EXPECT_EQ(KM_ERROR_OK, GetCharacteristics());
   3459     EXPECT_TRUE(contains(hw_enforced(), TAG_ALGORITHM, KM_ALGORITHM_RSA));
   3460     EXPECT_TRUE(contains(hw_enforced(), TAG_KEY_SIZE, 512));
   3461     EXPECT_TRUE(contains(hw_enforced(), TAG_RSA_PUBLIC_EXPONENT, 3));
   3462     EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_NONE));
   3463     EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_MD5));
   3464     EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA1));
   3465     EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA_2_224));
   3466     EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA_2_256));
   3467     EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA_2_384));
   3468     EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA_2_512));
   3469     EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_NONE));
   3470     EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT));
   3471     EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN));
   3472     EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_RSA_OAEP));
   3473     EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_RSA_PSS));
   3474     EXPECT_EQ(15U, hw_enforced().size());
   3475 
   3476     EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_SIGN));
   3477     EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_VERIFY));
   3478     EXPECT_TRUE(sw_enforced().GetTagValue(TAG_ALL_USERS));
   3479     EXPECT_TRUE(sw_enforced().GetTagValue(TAG_NO_AUTH_REQUIRED));
   3480 
   3481     EXPECT_FALSE(contains(sw_enforced(), TAG_ALGORITHM, KM_ALGORITHM_RSA));
   3482     EXPECT_FALSE(contains(sw_enforced(), TAG_KEY_SIZE, 512));
   3483     EXPECT_FALSE(contains(sw_enforced(), TAG_RSA_PUBLIC_EXPONENT, 3));
   3484     EXPECT_FALSE(contains(sw_enforced(), TAG_DIGEST, KM_DIGEST_NONE));
   3485     EXPECT_FALSE(contains(sw_enforced(), TAG_PADDING, KM_PAD_NONE));
   3486 
   3487     EXPECT_EQ(1, GetParam()->keymaster0_calls());
   3488 }
   3489 
   3490 typedef Keymaster2Test AttestationTest;
   3491 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, AttestationTest, test_params);
   3492 
   3493 static X509* parse_cert_blob(const keymaster_blob_t& blob) {
   3494     const uint8_t* p = blob.data;
   3495     return d2i_X509(nullptr, &p, blob.data_length);
   3496 }
   3497 
   3498 static bool verify_chain(const keymaster_cert_chain_t& chain) {
   3499     for (size_t i = 0; i < chain.entry_count - 1; ++i) {
   3500         keymaster_blob_t& key_cert_blob = chain.entries[i];
   3501         keymaster_blob_t& signing_cert_blob = chain.entries[i + 1];
   3502 
   3503         X509_Ptr key_cert(parse_cert_blob(key_cert_blob));
   3504         X509_Ptr signing_cert(parse_cert_blob(signing_cert_blob));
   3505         EXPECT_TRUE(!!key_cert.get() && !!signing_cert.get());
   3506         if (!key_cert.get() || !signing_cert.get())
   3507             return false;
   3508 
   3509         EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
   3510         EXPECT_TRUE(!!signing_pubkey.get());
   3511         if (!signing_pubkey.get())
   3512             return false;
   3513 
   3514         EXPECT_EQ(1, X509_verify(key_cert.get(), signing_pubkey.get()))
   3515             << "Verification of certificate " << i << " failed";
   3516     }
   3517 
   3518     return true;
   3519 }
   3520 
   3521 // Extract attestation record from cert. Returned object is still part of cert; don't free it
   3522 // separately.
   3523 static ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
   3524     ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
   3525     EXPECT_TRUE(!!oid.get());
   3526     if (!oid.get())
   3527         return nullptr;
   3528 
   3529     int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
   3530     EXPECT_NE(-1, location);
   3531     if (location == -1)
   3532         return nullptr;
   3533 
   3534     X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
   3535     EXPECT_TRUE(!!attest_rec_ext);
   3536     if (!attest_rec_ext)
   3537         return nullptr;
   3538 
   3539     ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
   3540     EXPECT_TRUE(!!attest_rec);
   3541     return attest_rec;
   3542 }
   3543 
   3544 static bool verify_attestation_record(const string& challenge,
   3545                                       AuthorizationSet expected_sw_enforced,
   3546                                       AuthorizationSet expected_tee_enforced,
   3547                                       uint32_t expected_keymaster_version,
   3548                                       keymaster_security_level_t expected_keymaster_security_level,
   3549                                       const keymaster_blob_t& attestation_cert) {
   3550 
   3551     X509_Ptr cert(parse_cert_blob(attestation_cert));
   3552     EXPECT_TRUE(!!cert.get());
   3553     if (!cert.get())
   3554         return false;
   3555 
   3556     ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
   3557     EXPECT_TRUE(!!attest_rec);
   3558     if (!attest_rec)
   3559         return false;
   3560 
   3561     AuthorizationSet att_sw_enforced;
   3562     AuthorizationSet att_tee_enforced;
   3563     uint32_t att_attestation_version;
   3564     uint32_t att_keymaster_version;
   3565     keymaster_security_level_t att_attestation_security_level;
   3566     keymaster_security_level_t att_keymaster_security_level;
   3567     keymaster_blob_t att_challenge = {};
   3568     keymaster_blob_t att_unique_id = {};
   3569     EXPECT_EQ(KM_ERROR_OK, parse_attestation_record(
   3570                                attest_rec->data, attest_rec->length, &att_attestation_version,
   3571                                &att_attestation_security_level, &att_keymaster_version,
   3572                                &att_keymaster_security_level, &att_challenge, &att_sw_enforced,
   3573                                &att_tee_enforced, &att_unique_id));
   3574 
   3575     EXPECT_EQ(1U, att_attestation_version);
   3576     EXPECT_EQ(KM_SECURITY_LEVEL_SOFTWARE, att_attestation_security_level);
   3577     EXPECT_EQ(expected_keymaster_version, att_keymaster_version);
   3578     EXPECT_EQ(expected_keymaster_security_level, att_keymaster_security_level);
   3579 
   3580     EXPECT_EQ(challenge.length(), att_challenge.data_length);
   3581     EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data, challenge.length()));
   3582 
   3583     // Add TAG_USER_ID to the relevant attestation list, because user IDs are not included in
   3584     // attestations, since they're meaningless off-device.
   3585     uint32_t user_id;
   3586     if (expected_sw_enforced.GetTagValue(TAG_USER_ID, &user_id))
   3587         att_sw_enforced.push_back(TAG_USER_ID, user_id);
   3588     if (expected_tee_enforced.GetTagValue(TAG_USER_ID, &user_id))
   3589         att_tee_enforced.push_back(TAG_USER_ID, user_id);
   3590 
   3591     // Add TAG_INCLUDE_UNIQUE_ID to the relevant attestation list, because that tag is not included
   3592     // in the attestation.
   3593     if (expected_sw_enforced.GetTagValue(TAG_INCLUDE_UNIQUE_ID))
   3594         att_sw_enforced.push_back(TAG_INCLUDE_UNIQUE_ID);
   3595     if (expected_tee_enforced.GetTagValue(TAG_INCLUDE_UNIQUE_ID))
   3596         att_tee_enforced.push_back(TAG_INCLUDE_UNIQUE_ID);
   3597 
   3598     att_sw_enforced.Sort();
   3599     expected_sw_enforced.Sort();
   3600     EXPECT_EQ(expected_sw_enforced, att_sw_enforced);
   3601 
   3602     att_tee_enforced.Sort();
   3603     expected_tee_enforced.Sort();
   3604     EXPECT_EQ(expected_tee_enforced, att_tee_enforced);
   3605 
   3606     return true;
   3607 }
   3608 
   3609 TEST_P(AttestationTest, RsaAttestation) {
   3610     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   3611                                            .RsaSigningKey(256, 3)
   3612                                            .Digest(KM_DIGEST_NONE)
   3613                                            .Padding(KM_PAD_NONE)
   3614                                            .Authorization(TAG_INCLUDE_UNIQUE_ID)));
   3615 
   3616     keymaster_cert_chain_t cert_chain;
   3617     EXPECT_EQ(KM_ERROR_OK, AttestKey("challenge", &cert_chain));
   3618     EXPECT_EQ(3U, cert_chain.entry_count);
   3619     EXPECT_TRUE(verify_chain(cert_chain));
   3620 
   3621     uint32_t expected_keymaster_version;
   3622     keymaster_security_level_t expected_keymaster_security_level;
   3623     // TODO(swillden): Add a test KM1 that claims to be hardware.
   3624     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA)) {
   3625         expected_keymaster_version = 0;
   3626         expected_keymaster_security_level = KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
   3627     } else {
   3628         expected_keymaster_version = 2;
   3629         expected_keymaster_security_level = KM_SECURITY_LEVEL_SOFTWARE;
   3630     }
   3631 
   3632     EXPECT_TRUE(verify_attestation_record(
   3633         "challenge", sw_enforced(), hw_enforced(), expected_keymaster_version,
   3634         expected_keymaster_security_level, cert_chain.entries[0]));
   3635 
   3636     keymaster_free_cert_chain(&cert_chain);
   3637 }
   3638 
   3639 TEST_P(AttestationTest, EcAttestation) {
   3640     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(
   3641                                KM_DIGEST_SHA_2_256)));
   3642 
   3643     uint32_t expected_keymaster_version;
   3644     keymaster_security_level_t expected_keymaster_security_level;
   3645     // TODO(swillden): Add a test KM1 that claims to be hardware.
   3646     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC)) {
   3647         expected_keymaster_version = 0;
   3648         expected_keymaster_security_level = KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
   3649     } else {
   3650         expected_keymaster_version = 2;
   3651         expected_keymaster_security_level = KM_SECURITY_LEVEL_SOFTWARE;
   3652     }
   3653 
   3654     keymaster_cert_chain_t cert_chain;
   3655     EXPECT_EQ(KM_ERROR_OK, AttestKey("challenge", &cert_chain));
   3656     EXPECT_EQ(3U, cert_chain.entry_count);
   3657     EXPECT_TRUE(verify_chain(cert_chain));
   3658     EXPECT_TRUE(verify_attestation_record(
   3659         "challenge", sw_enforced(), hw_enforced(), expected_keymaster_version,
   3660         expected_keymaster_security_level, cert_chain.entries[0]));
   3661 
   3662     keymaster_free_cert_chain(&cert_chain);
   3663 }
   3664 
   3665 typedef Keymaster2Test KeyUpgradeTest;
   3666 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, KeyUpgradeTest, test_params);
   3667 
   3668 TEST_P(KeyUpgradeTest, AesVersionUpgrade) {
   3669     GetParam()->keymaster_context()->SetSystemVersion(1, 1);
   3670 
   3671     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
   3672                                            .AesEncryptionKey(128)
   3673                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
   3674                                            .Padding(KM_PAD_NONE)));
   3675 
   3676     // Key should operate fine.
   3677     string message = "1234567890123456";
   3678     string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
   3679     EXPECT_EQ(message, DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_NONE));
   3680 
   3681     // Increase patch level.  Key usage should fail with KM_ERROR_KEY_REQUIRES_UPGRADE.
   3682     GetParam()->keymaster_context()->SetSystemVersion(1, 2);
   3683     AuthorizationSet begin_params(client_params());
   3684     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
   3685     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   3686     if (GetParam()->is_keymaster1_hw()) {
   3687         // Keymaster1 hardware can't support version binding.  The key will work regardless
   3688         // of system version.  Just abort the remainder of the test.
   3689         EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   3690         EXPECT_EQ(KM_ERROR_OK, AbortOperation());
   3691         return;
   3692     }
   3693     EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   3694 
   3695     // Getting characteristics should also fail
   3696     EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, GetCharacteristics());
   3697 
   3698     // Upgrade key.
   3699     EXPECT_EQ(KM_ERROR_OK, UpgradeKey(client_params()));
   3700 
   3701     // Key should work again
   3702     ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
   3703     EXPECT_EQ(message, DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_NONE));
   3704 
   3705     // Decrease patch level.  Key usage should fail with KM_ERROR_INVALID_KEY_BLOB.
   3706     GetParam()->keymaster_context()->SetSystemVersion(1, 1);
   3707     EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   3708     EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, GetCharacteristics());
   3709 
   3710     // Upgrade should fail
   3711     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, UpgradeKey(client_params()));
   3712 
   3713     EXPECT_EQ(0, GetParam()->keymaster0_calls());
   3714 }
   3715 
   3716 TEST_P(KeyUpgradeTest, RsaVersionUpgrade) {
   3717     GetParam()->keymaster_context()->SetSystemVersion(1, 1);
   3718 
   3719     ASSERT_EQ(KM_ERROR_OK,
   3720               GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(128, 3).Padding(KM_PAD_NONE)));
   3721 
   3722     // Key should operate fine.
   3723     string message = "1234567890123456";
   3724     string ciphertext = EncryptMessage(message, KM_PAD_NONE);
   3725     EXPECT_EQ(message, DecryptMessage(ciphertext, KM_PAD_NONE));
   3726 
   3727     // Increase patch level.  Key usage should fail with KM_ERROR_KEY_REQUIRES_UPGRADE.
   3728     GetParam()->keymaster_context()->SetSystemVersion(1, 2);
   3729     AuthorizationSet begin_params(client_params());
   3730     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
   3731     if (GetParam()->is_keymaster1_hw()) {
   3732         // Keymaster1 hardware can't support version binding.  The key will work regardless
   3733         // of system version.  Just abort the remainder of the test.
   3734         EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   3735         EXPECT_EQ(KM_ERROR_OK, AbortOperation());
   3736         return;
   3737     }
   3738     EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   3739 
   3740     // Getting characteristics should also fail
   3741     EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, GetCharacteristics());
   3742 
   3743     // Upgrade key.
   3744     EXPECT_EQ(KM_ERROR_OK, UpgradeKey(client_params()));
   3745 
   3746     // Key should work again
   3747     ciphertext = EncryptMessage(message, KM_PAD_NONE);
   3748     EXPECT_EQ(message, DecryptMessage(ciphertext, KM_PAD_NONE));
   3749 
   3750     // Decrease patch level.  Key usage should fail with KM_ERROR_INVALID_KEY_BLOB.
   3751     GetParam()->keymaster_context()->SetSystemVersion(1, 1);
   3752     EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   3753     EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, GetCharacteristics());
   3754 
   3755     // Upgrade should fail
   3756     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, UpgradeKey(client_params()));
   3757 
   3758     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
   3759         EXPECT_EQ(7, GetParam()->keymaster0_calls());
   3760 }
   3761 
   3762 TEST_P(KeyUpgradeTest, EcVersionUpgrade) {
   3763     GetParam()->keymaster_context()->SetSystemVersion(1, 1);
   3764 
   3765     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(
   3766                                KM_DIGEST_SHA_2_256)));
   3767 
   3768     // Key should operate fine.
   3769     string message = "1234567890123456";
   3770     string signature;
   3771     SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
   3772     VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
   3773 
   3774     // Increase patch level.  Key usage should fail with KM_ERROR_KEY_REQUIRES_UPGRADE.
   3775     GetParam()->keymaster_context()->SetSystemVersion(1, 2);
   3776     AuthorizationSet begin_params(client_params());
   3777     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
   3778     if (GetParam()->is_keymaster1_hw()) {
   3779         // Keymaster1 hardware can't support version binding.  The key will work regardless
   3780         // of system version.  Just abort the remainder of the test.
   3781         EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
   3782         EXPECT_EQ(KM_ERROR_OK, AbortOperation());
   3783         return;
   3784     }
   3785     EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
   3786 
   3787     // Getting characteristics should also fail
   3788     EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, GetCharacteristics());
   3789 
   3790     // Upgrade key.
   3791     EXPECT_EQ(KM_ERROR_OK, UpgradeKey(client_params()));
   3792 
   3793     // Key should work again
   3794     SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
   3795     VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
   3796 
   3797     // Decrease patch level.  Key usage should fail with KM_ERROR_INVALID_KEY_BLOB.
   3798     GetParam()->keymaster_context()->SetSystemVersion(1, 1);
   3799     EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
   3800     EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, GetCharacteristics());
   3801 
   3802     // Upgrade should fail
   3803     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, UpgradeKey(client_params()));
   3804 
   3805     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
   3806         EXPECT_EQ(7, GetParam()->keymaster0_calls());
   3807 }
   3808 
   3809 TEST(SoftKeymasterWrapperTest, CheckKeymaster2Device) {
   3810     // Make a good fake device, and wrap it.
   3811     SoftKeymasterDevice* good_fake(new SoftKeymasterDevice(new TestKeymasterContext));
   3812 
   3813     // Wrap it and check it.
   3814     SoftKeymasterDevice* good_fake_wrapper(new SoftKeymasterDevice(new TestKeymasterContext));
   3815     good_fake_wrapper->SetHardwareDevice(good_fake->keymaster_device());
   3816     EXPECT_TRUE(good_fake_wrapper->Keymaster1DeviceIsGood());
   3817 
   3818     // Close and clean up wrapper and wrapped
   3819     good_fake_wrapper->keymaster_device()->common.close(good_fake_wrapper->hw_device());
   3820 
   3821     // Make a "bad" (doesn't support all digests) device;
   3822     keymaster1_device_t* sha256_only_fake = make_device_sha256_only(
   3823         (new SoftKeymasterDevice(new TestKeymasterContext("256")))->keymaster_device());
   3824 
   3825     // Wrap it and check it.
   3826     SoftKeymasterDevice* sha256_only_fake_wrapper(
   3827         (new SoftKeymasterDevice(new TestKeymasterContext)));
   3828     sha256_only_fake_wrapper->SetHardwareDevice(sha256_only_fake);
   3829     EXPECT_FALSE(sha256_only_fake_wrapper->Keymaster1DeviceIsGood());
   3830 
   3831     // Close and clean up wrapper and wrapped
   3832     sha256_only_fake_wrapper->keymaster_device()->common.close(
   3833         sha256_only_fake_wrapper->hw_device());
   3834 }
   3835 
   3836 }  // namespace test
   3837 }  // namespace keymaster
   3838