Home | History | Annotate | Download | only in keymaster
      1 /*
      2  * Copyright 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 "android_keymaster_test_utils.h"
     18 
     19 #include <algorithm>
     20 
     21 #include <openssl/rand.h>
     22 
     23 #include <keymaster/android_keymaster_messages.h>
     24 #include <keymaster/android_keymaster_utils.h>
     25 
     26 using std::copy_if;
     27 using std::find_if;
     28 using std::is_permutation;
     29 using std::ostream;
     30 using std::string;
     31 using std::vector;
     32 
     33 #ifndef KEYMASTER_NAME_TAGS
     34 #error Keymaster test code requires that KEYMASTER_NAME_TAGS is defined
     35 #endif
     36 
     37 std::ostream& operator<<(std::ostream& os, const keymaster_key_param_t& param) {
     38     os << "Tag: " << keymaster::StringifyTag(param.tag);
     39     switch (keymaster_tag_get_type(param.tag)) {
     40     case KM_INVALID:
     41         os << " Invalid";
     42         break;
     43     case KM_UINT_REP:
     44         os << " (Rep)";
     45     /* Falls through */
     46     case KM_UINT:
     47         os << " Int: " << param.integer;
     48         break;
     49     case KM_ENUM_REP:
     50         os << " (Rep)";
     51     /* Falls through */
     52     case KM_ENUM:
     53         os << " Enum: " << param.enumerated;
     54         break;
     55     case KM_ULONG_REP:
     56         os << " (Rep)";
     57     /* Falls through */
     58     case KM_ULONG:
     59         os << " Long: " << param.long_integer;
     60         break;
     61     case KM_DATE:
     62         os << " Date: " << param.date_time;
     63         break;
     64     case KM_BOOL:
     65         os << " Bool: " << param.boolean;
     66         break;
     67     case KM_BIGNUM:
     68         os << " Bignum: ";
     69         if (!param.blob.data)
     70             os << "(null)";
     71         else
     72             for (size_t i = 0; i < param.blob.data_length; ++i)
     73                 os << std::hex << std::setw(2) << static_cast<int>(param.blob.data[i]) << std::dec;
     74         break;
     75     case KM_BYTES:
     76         os << " Bytes: ";
     77         if (!param.blob.data)
     78             os << "(null)";
     79         else
     80             for (size_t i = 0; i < param.blob.data_length; ++i)
     81                 os << std::hex << std::setw(2) << static_cast<int>(param.blob.data[i]) << std::dec;
     82         break;
     83     }
     84     return os;
     85 }
     86 
     87 bool operator==(const keymaster_key_param_t& a, const keymaster_key_param_t& b) {
     88     if (a.tag != b.tag) {
     89         return false;
     90     }
     91 
     92     switch (keymaster_tag_get_type(a.tag)) {
     93     case KM_INVALID:
     94         return true;
     95     case KM_UINT_REP:
     96     case KM_UINT:
     97         return a.integer == b.integer;
     98     case KM_ENUM_REP:
     99     case KM_ENUM:
    100         return a.enumerated == b.enumerated;
    101     case KM_ULONG:
    102     case KM_ULONG_REP:
    103         return a.long_integer == b.long_integer;
    104     case KM_DATE:
    105         return a.date_time == b.date_time;
    106     case KM_BOOL:
    107         return a.boolean == b.boolean;
    108     case KM_BIGNUM:
    109     case KM_BYTES:
    110         if ((a.blob.data == NULL || b.blob.data == NULL) && a.blob.data != b.blob.data)
    111             return false;
    112         return a.blob.data_length == b.blob.data_length &&
    113                (memcmp(a.blob.data, b.blob.data, a.blob.data_length) == 0);
    114     }
    115 
    116     return false;
    117 }
    118 
    119 static char hex_value[256] = {
    120     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
    121     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
    122     0, 1,  2,  3,  4,  5,  6,  7, 8, 9, 0, 0, 0, 0, 0, 0,  // '0'..'9'
    123     0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 'A'..'F'
    124     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 0,
    125     0, 0,  0,  0,  0,  0,  0,  0,  // 'a'..'f'
    126     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
    127     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
    128     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
    129     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
    130     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
    131     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0};
    132 
    133 string hex2str(string a) {
    134     string b;
    135     size_t num = a.size() / 2;
    136     b.resize(num);
    137     for (size_t i = 0; i < num; i++) {
    138         b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
    139     }
    140     return b;
    141 }
    142 
    143 namespace keymaster {
    144 
    145 bool operator==(const AuthorizationSet& a, const AuthorizationSet& b) {
    146     if (a.size() != b.size())
    147         return false;
    148 
    149     for (size_t i = 0; i < a.size(); ++i)
    150         if (!(a[i] == b[i]))
    151             return false;
    152     return true;
    153 }
    154 
    155 bool operator!=(const AuthorizationSet& a, const AuthorizationSet& b) {
    156     return !(a == b);
    157 }
    158 
    159 std::ostream& operator<<(std::ostream& os, const AuthorizationSet& set) {
    160     if (set.size() == 0)
    161         os << "(Empty)" << std::endl;
    162     else {
    163         os << "\n";
    164         for (size_t i = 0; i < set.size(); ++i)
    165             os << set[i] << std::endl;
    166     }
    167     return os;
    168 }
    169 
    170 namespace test {
    171 
    172 std::ostream& operator<<(std::ostream& os, const InstanceCreatorPtr& instance_creator) {
    173     return os << instance_creator->name();
    174 }
    175 
    176 Keymaster2Test::Keymaster2Test() : op_handle_(OP_HANDLE_SENTINEL) {
    177     memset(&characteristics_, 0, sizeof(characteristics_));
    178     blob_.key_material = nullptr;
    179     RAND_seed("foobar", 6);
    180     blob_.key_material = 0;
    181     device_ = GetParam()->CreateDevice();
    182 }
    183 
    184 Keymaster2Test::~Keymaster2Test() {
    185     FreeCharacteristics();
    186     FreeKeyBlob();
    187     device_->common.close(reinterpret_cast<hw_device_t*>(device_));
    188 }
    189 
    190 keymaster2_device_t* Keymaster2Test::device() {
    191     return device_;
    192 }
    193 
    194 keymaster_error_t Keymaster2Test::GenerateKey(const AuthorizationSetBuilder& builder) {
    195     AuthorizationSet params(builder.build());
    196     params.push_back(UserAuthParams());
    197     params.push_back(ClientParams());
    198 
    199     FreeKeyBlob();
    200     FreeCharacteristics();
    201     return device()->generate_key(device(), &params, &blob_, &characteristics_);
    202 }
    203 
    204 keymaster_error_t Keymaster2Test::DeleteKey() {
    205     return device()->delete_key(device(), &blob_);
    206 }
    207 
    208 keymaster_error_t Keymaster2Test::ImportKey(const AuthorizationSetBuilder& builder,
    209                                             keymaster_key_format_t format,
    210                                             const string& key_material) {
    211     AuthorizationSet params(builder.build());
    212     params.push_back(UserAuthParams());
    213     params.push_back(ClientParams());
    214 
    215     FreeKeyBlob();
    216     FreeCharacteristics();
    217     keymaster_blob_t key = {reinterpret_cast<const uint8_t*>(key_material.c_str()),
    218                             key_material.length()};
    219     return device()->import_key(device(), &params, format, &key, &blob_, &characteristics_);
    220 }
    221 
    222 AuthorizationSet Keymaster2Test::UserAuthParams() {
    223     AuthorizationSet set;
    224     set.push_back(TAG_USER_ID, 7);
    225     set.push_back(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD);
    226     set.push_back(TAG_AUTH_TIMEOUT, 300);
    227     return set;
    228 }
    229 
    230 AuthorizationSet Keymaster2Test::ClientParams() {
    231     AuthorizationSet set;
    232     set.push_back(TAG_APPLICATION_ID, "app_id", 6);
    233     return set;
    234 }
    235 
    236 keymaster_error_t Keymaster2Test::BeginOperation(keymaster_purpose_t purpose) {
    237     AuthorizationSet in_params(client_params());
    238     keymaster_key_param_set_t out_params;
    239     keymaster_error_t error =
    240         device()->begin(device(), purpose, &blob_, &in_params, &out_params, &op_handle_);
    241     EXPECT_EQ(0U, out_params.length);
    242     EXPECT_TRUE(out_params.params == nullptr);
    243     return error;
    244 }
    245 
    246 keymaster_error_t Keymaster2Test::BeginOperation(keymaster_purpose_t purpose,
    247                                                  const AuthorizationSet& input_set,
    248                                                  AuthorizationSet* output_set) {
    249     keymaster_key_param_set_t out_params;
    250     keymaster_error_t error =
    251         device()->begin(device(), purpose, &blob_, &input_set, &out_params, &op_handle_);
    252     if (error == KM_ERROR_OK) {
    253         if (output_set) {
    254             output_set->Reinitialize(out_params);
    255         } else {
    256             EXPECT_EQ(0U, out_params.length);
    257             EXPECT_TRUE(out_params.params == nullptr);
    258         }
    259         keymaster_free_param_set(&out_params);
    260     }
    261     return error;
    262 }
    263 
    264 keymaster_error_t Keymaster2Test::UpdateOperation(const string& message, string* output,
    265                                                   size_t* input_consumed) {
    266     EXPECT_NE(op_handle_, OP_HANDLE_SENTINEL);
    267     keymaster_blob_t input = {reinterpret_cast<const uint8_t*>(message.c_str()), message.length()};
    268     keymaster_blob_t out_tmp;
    269     keymaster_key_param_set_t out_params;
    270     keymaster_error_t error = device()->update(device(), op_handle_, nullptr /* params */, &input,
    271                                                input_consumed, &out_params, &out_tmp);
    272     if (error == KM_ERROR_OK && out_tmp.data)
    273         output->append(reinterpret_cast<const char*>(out_tmp.data), out_tmp.data_length);
    274     free(const_cast<uint8_t*>(out_tmp.data));
    275     return error;
    276 }
    277 
    278 keymaster_error_t Keymaster2Test::UpdateOperation(const AuthorizationSet& additional_params,
    279                                                   const string& message,
    280                                                   AuthorizationSet* output_params, string* output,
    281                                                   size_t* input_consumed) {
    282     EXPECT_NE(op_handle_, OP_HANDLE_SENTINEL);
    283     keymaster_blob_t input = {reinterpret_cast<const uint8_t*>(message.c_str()), message.length()};
    284     keymaster_blob_t out_tmp;
    285     keymaster_key_param_set_t out_params;
    286     keymaster_error_t error = device()->update(device(), op_handle_, &additional_params, &input,
    287                                                input_consumed, &out_params, &out_tmp);
    288     if (error == KM_ERROR_OK && out_tmp.data)
    289         output->append(reinterpret_cast<const char*>(out_tmp.data), out_tmp.data_length);
    290     free((void*)out_tmp.data);
    291     if (output_params)
    292         output_params->Reinitialize(out_params);
    293     keymaster_free_param_set(&out_params);
    294     return error;
    295 }
    296 
    297 keymaster_error_t Keymaster2Test::FinishOperation(string* output) {
    298     return FinishOperation("", "", output);
    299 }
    300 
    301 keymaster_error_t Keymaster2Test::FinishOperation(const string& input, const string& signature,
    302                                                   string* output) {
    303     AuthorizationSet additional_params;
    304     AuthorizationSet output_params;
    305     return FinishOperation(additional_params, input, signature, &output_params, output);
    306 }
    307 
    308 keymaster_error_t Keymaster2Test::FinishOperation(const AuthorizationSet& additional_params,
    309                                                   const string& input, const string& signature,
    310                                                   AuthorizationSet* output_params, string* output) {
    311     keymaster_blob_t inp = {reinterpret_cast<const uint8_t*>(input.c_str()), input.length()};
    312     keymaster_blob_t sig = {reinterpret_cast<const uint8_t*>(signature.c_str()),
    313                             signature.length()};
    314     keymaster_blob_t out_tmp;
    315     keymaster_key_param_set_t out_params;
    316     keymaster_error_t error = device()->finish(device(), op_handle_, &additional_params, &inp, &sig,
    317                                                &out_params, &out_tmp);
    318     if (error != KM_ERROR_OK) {
    319         EXPECT_TRUE(out_tmp.data == nullptr);
    320         EXPECT_TRUE(out_params.params == nullptr);
    321         return error;
    322     }
    323 
    324     if (out_tmp.data)
    325         output->append(reinterpret_cast<const char*>(out_tmp.data), out_tmp.data_length);
    326     free((void*)out_tmp.data);
    327     if (output_params)
    328         output_params->Reinitialize(out_params);
    329     keymaster_free_param_set(&out_params);
    330     return error;
    331 }
    332 
    333 keymaster_error_t Keymaster2Test::AbortOperation() {
    334     return device()->abort(device(), op_handle_);
    335 }
    336 
    337 keymaster_error_t Keymaster2Test::AttestKey(const string& attest_challenge,
    338                                             const string& attest_app_id,
    339                                             keymaster_cert_chain_t* cert_chain) {
    340     AuthorizationSet attest_params;
    341     attest_params.push_back(UserAuthParams());
    342     attest_params.push_back(ClientParams());
    343     attest_params.push_back(TAG_ATTESTATION_CHALLENGE, attest_challenge.data(),
    344                             attest_challenge.length());
    345     attest_params.push_back(TAG_ATTESTATION_APPLICATION_ID, attest_app_id.data(),
    346                             attest_app_id.length());
    347     return device()->attest_key(device(), &blob_, &attest_params, cert_chain);
    348 }
    349 
    350 keymaster_error_t Keymaster2Test::UpgradeKey(const AuthorizationSet& upgrade_params) {
    351     keymaster_key_blob_t upgraded_blob;
    352     keymaster_error_t error =
    353         device()->upgrade_key(device(), &blob_, &upgrade_params, &upgraded_blob);
    354     if (error == KM_ERROR_OK) {
    355         FreeKeyBlob();
    356         blob_ = upgraded_blob;
    357     }
    358     return error;
    359 }
    360 
    361 string Keymaster2Test::ProcessMessage(keymaster_purpose_t purpose, const string& message) {
    362     EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, client_params(), NULL /* output_params */));
    363 
    364     string result;
    365     EXPECT_EQ(KM_ERROR_OK, FinishOperation(message, "" /* signature */, &result));
    366     return result;
    367 }
    368 
    369 string Keymaster2Test::ProcessMessage(keymaster_purpose_t purpose, const string& message,
    370                                       const AuthorizationSet& begin_params,
    371                                       const AuthorizationSet& update_params,
    372                                       AuthorizationSet* begin_out_params) {
    373     EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, begin_params, begin_out_params));
    374 
    375     string result;
    376     EXPECT_EQ(KM_ERROR_OK, FinishOperation(update_params, message, "" /* signature */, &result));
    377     return result;
    378 }
    379 
    380 string Keymaster2Test::ProcessMessage(keymaster_purpose_t purpose, const string& message,
    381                                       const string& signature, const AuthorizationSet& begin_params,
    382                                       const AuthorizationSet& update_params,
    383                                       AuthorizationSet* output_params) {
    384     EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, begin_params, output_params));
    385 
    386     string result;
    387     EXPECT_EQ(KM_ERROR_OK, FinishOperation(update_params, message, signature, &result));
    388     return result;
    389 }
    390 
    391 string Keymaster2Test::ProcessMessage(keymaster_purpose_t purpose, const string& message,
    392                                       const string& signature) {
    393     EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, client_params(), NULL /* output_params */));
    394 
    395     string result;
    396     EXPECT_EQ(KM_ERROR_OK, FinishOperation(message, signature, &result));
    397     return result;
    398 }
    399 
    400 void Keymaster2Test::SignMessage(const string& message, string* signature,
    401                                  keymaster_digest_t digest) {
    402     SCOPED_TRACE("SignMessage");
    403     AuthorizationSet input_params(AuthorizationSet(client_params_, array_length(client_params_)));
    404     input_params.push_back(TAG_DIGEST, digest);
    405     AuthorizationSet update_params;
    406     AuthorizationSet output_params;
    407     *signature =
    408         ProcessMessage(KM_PURPOSE_SIGN, message, input_params, update_params, &output_params);
    409     EXPECT_GT(signature->size(), 0U);
    410 }
    411 
    412 void Keymaster2Test::SignMessage(const string& message, string* signature,
    413                                  keymaster_digest_t digest, keymaster_padding_t padding) {
    414     SCOPED_TRACE("SignMessage");
    415     AuthorizationSet input_params(AuthorizationSet(client_params_, array_length(client_params_)));
    416     input_params.push_back(TAG_DIGEST, digest);
    417     input_params.push_back(TAG_PADDING, padding);
    418     AuthorizationSet update_params;
    419     AuthorizationSet output_params;
    420     *signature =
    421         ProcessMessage(KM_PURPOSE_SIGN, message, input_params, update_params, &output_params);
    422     EXPECT_GT(signature->size(), 0U);
    423 }
    424 
    425 void Keymaster2Test::MacMessage(const string& message, string* signature, size_t mac_length) {
    426     SCOPED_TRACE("SignMessage");
    427     AuthorizationSet input_params(AuthorizationSet(client_params_, array_length(client_params_)));
    428     input_params.push_back(TAG_MAC_LENGTH, mac_length);
    429     AuthorizationSet update_params;
    430     AuthorizationSet output_params;
    431     *signature =
    432         ProcessMessage(KM_PURPOSE_SIGN, message, input_params, update_params, &output_params);
    433     EXPECT_GT(signature->size(), 0U);
    434 }
    435 
    436 void Keymaster2Test::VerifyMessage(const string& message, const string& signature,
    437                                    keymaster_digest_t digest) {
    438     SCOPED_TRACE("VerifyMessage");
    439     AuthorizationSet input_params(client_params());
    440     input_params.push_back(TAG_DIGEST, digest);
    441     AuthorizationSet update_params;
    442     AuthorizationSet output_params;
    443     ProcessMessage(KM_PURPOSE_VERIFY, message, signature, input_params, update_params,
    444                    &output_params);
    445 }
    446 
    447 void Keymaster2Test::VerifyMessage(const string& message, const string& signature,
    448                                    keymaster_digest_t digest, keymaster_padding_t padding) {
    449     SCOPED_TRACE("VerifyMessage");
    450     AuthorizationSet input_params(client_params());
    451     input_params.push_back(TAG_DIGEST, digest);
    452     input_params.push_back(TAG_PADDING, padding);
    453     AuthorizationSet update_params;
    454     AuthorizationSet output_params;
    455     ProcessMessage(KM_PURPOSE_VERIFY, message, signature, input_params, update_params,
    456                    &output_params);
    457 }
    458 
    459 void Keymaster2Test::VerifyMac(const string& message, const string& signature) {
    460     SCOPED_TRACE("VerifyMac");
    461     ProcessMessage(KM_PURPOSE_VERIFY, message, signature);
    462 }
    463 
    464 string Keymaster2Test::EncryptMessage(const string& message, keymaster_padding_t padding,
    465                                       string* generated_nonce) {
    466     SCOPED_TRACE("EncryptMessage");
    467     AuthorizationSet begin_params(client_params()), output_params;
    468     begin_params.push_back(TAG_PADDING, padding);
    469     AuthorizationSet update_params;
    470     string ciphertext =
    471         ProcessMessage(KM_PURPOSE_ENCRYPT, message, begin_params, update_params, &output_params);
    472     if (generated_nonce) {
    473         keymaster_blob_t nonce_blob;
    474         EXPECT_TRUE(output_params.GetTagValue(TAG_NONCE, &nonce_blob));
    475         *generated_nonce = make_string(nonce_blob.data, nonce_blob.data_length);
    476     } else {
    477         EXPECT_EQ(-1, output_params.find(TAG_NONCE));
    478     }
    479     return ciphertext;
    480 }
    481 
    482 string Keymaster2Test::EncryptMessage(const string& message, keymaster_digest_t digest,
    483                                       keymaster_padding_t padding, string* generated_nonce) {
    484     AuthorizationSet update_params;
    485     return EncryptMessage(update_params, message, digest, padding, generated_nonce);
    486 }
    487 
    488 string Keymaster2Test::EncryptMessage(const string& message, keymaster_block_mode_t block_mode,
    489                                       keymaster_padding_t padding, string* generated_nonce) {
    490     AuthorizationSet update_params;
    491     return EncryptMessage(update_params, message, block_mode, padding, generated_nonce);
    492 }
    493 
    494 string Keymaster2Test::EncryptMessage(const AuthorizationSet& update_params, const string& message,
    495                                       keymaster_digest_t digest, keymaster_padding_t padding,
    496                                       string* generated_nonce) {
    497     SCOPED_TRACE("EncryptMessage");
    498     AuthorizationSet begin_params(client_params()), output_params;
    499     begin_params.push_back(TAG_PADDING, padding);
    500     begin_params.push_back(TAG_DIGEST, digest);
    501     string ciphertext =
    502         ProcessMessage(KM_PURPOSE_ENCRYPT, message, begin_params, update_params, &output_params);
    503     if (generated_nonce) {
    504         keymaster_blob_t nonce_blob;
    505         EXPECT_TRUE(output_params.GetTagValue(TAG_NONCE, &nonce_blob));
    506         *generated_nonce = make_string(nonce_blob.data, nonce_blob.data_length);
    507     } else {
    508         EXPECT_EQ(-1, output_params.find(TAG_NONCE));
    509     }
    510     return ciphertext;
    511 }
    512 
    513 string Keymaster2Test::EncryptMessage(const AuthorizationSet& update_params, const string& message,
    514                                       keymaster_block_mode_t block_mode,
    515                                       keymaster_padding_t padding, string* generated_nonce) {
    516     SCOPED_TRACE("EncryptMessage");
    517     AuthorizationSet begin_params(client_params()), output_params;
    518     begin_params.push_back(TAG_PADDING, padding);
    519     begin_params.push_back(TAG_BLOCK_MODE, block_mode);
    520     string ciphertext =
    521         ProcessMessage(KM_PURPOSE_ENCRYPT, message, begin_params, update_params, &output_params);
    522     if (generated_nonce) {
    523         keymaster_blob_t nonce_blob;
    524         EXPECT_TRUE(output_params.GetTagValue(TAG_NONCE, &nonce_blob));
    525         *generated_nonce = make_string(nonce_blob.data, nonce_blob.data_length);
    526     } else {
    527         EXPECT_EQ(-1, output_params.find(TAG_NONCE));
    528     }
    529     return ciphertext;
    530 }
    531 
    532 string Keymaster2Test::EncryptMessageWithParams(const string& message,
    533                                                 const AuthorizationSet& begin_params,
    534                                                 const AuthorizationSet& update_params,
    535                                                 AuthorizationSet* output_params) {
    536     SCOPED_TRACE("EncryptMessageWithParams");
    537     return ProcessMessage(KM_PURPOSE_ENCRYPT, message, begin_params, update_params, output_params);
    538 }
    539 
    540 string Keymaster2Test::DecryptMessage(const string& ciphertext, keymaster_padding_t padding) {
    541     SCOPED_TRACE("DecryptMessage");
    542     AuthorizationSet begin_params(client_params());
    543     begin_params.push_back(TAG_PADDING, padding);
    544     AuthorizationSet update_params;
    545     return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
    546 }
    547 
    548 string Keymaster2Test::DecryptMessage(const string& ciphertext, keymaster_digest_t digest,
    549                                       keymaster_padding_t padding) {
    550     SCOPED_TRACE("DecryptMessage");
    551     AuthorizationSet begin_params(client_params());
    552     begin_params.push_back(TAG_PADDING, padding);
    553     begin_params.push_back(TAG_DIGEST, digest);
    554     AuthorizationSet update_params;
    555     return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
    556 }
    557 
    558 string Keymaster2Test::DecryptMessage(const string& ciphertext, keymaster_block_mode_t block_mode,
    559                                       keymaster_padding_t padding) {
    560     SCOPED_TRACE("DecryptMessage");
    561     AuthorizationSet begin_params(client_params());
    562     begin_params.push_back(TAG_PADDING, padding);
    563     begin_params.push_back(TAG_BLOCK_MODE, block_mode);
    564     AuthorizationSet update_params;
    565     return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
    566 }
    567 
    568 string Keymaster2Test::DecryptMessage(const string& ciphertext, keymaster_digest_t digest,
    569                                       keymaster_padding_t padding, const string& nonce) {
    570     SCOPED_TRACE("DecryptMessage");
    571     AuthorizationSet begin_params(client_params());
    572     begin_params.push_back(TAG_PADDING, padding);
    573     begin_params.push_back(TAG_DIGEST, digest);
    574     begin_params.push_back(TAG_NONCE, nonce.data(), nonce.size());
    575     AuthorizationSet update_params;
    576     return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
    577 }
    578 
    579 string Keymaster2Test::DecryptMessage(const string& ciphertext, keymaster_block_mode_t block_mode,
    580                                       keymaster_padding_t padding, const string& nonce) {
    581     SCOPED_TRACE("DecryptMessage");
    582     AuthorizationSet begin_params(client_params());
    583     begin_params.push_back(TAG_PADDING, padding);
    584     begin_params.push_back(TAG_BLOCK_MODE, block_mode);
    585     begin_params.push_back(TAG_NONCE, nonce.data(), nonce.size());
    586     AuthorizationSet update_params;
    587     return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
    588 }
    589 
    590 string Keymaster2Test::DecryptMessage(const AuthorizationSet& update_params,
    591                                       const string& ciphertext, keymaster_digest_t digest,
    592                                       keymaster_padding_t padding, const string& nonce) {
    593     SCOPED_TRACE("DecryptMessage");
    594     AuthorizationSet begin_params(client_params());
    595     begin_params.push_back(TAG_PADDING, padding);
    596     begin_params.push_back(TAG_DIGEST, digest);
    597     begin_params.push_back(TAG_NONCE, nonce.data(), nonce.size());
    598     return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
    599 }
    600 
    601 keymaster_error_t Keymaster2Test::GetCharacteristics() {
    602     FreeCharacteristics();
    603     return device()->get_key_characteristics(device(), &blob_, &client_id_, NULL /* app_data */,
    604                                              &characteristics_);
    605 }
    606 
    607 keymaster_error_t Keymaster2Test::ExportKey(keymaster_key_format_t format, string* export_data) {
    608     keymaster_blob_t export_tmp;
    609     keymaster_error_t error = device()->export_key(device(), format, &blob_, &client_id_,
    610                                                    NULL /* app_data */, &export_tmp);
    611 
    612     if (error != KM_ERROR_OK)
    613         return error;
    614 
    615     *export_data = string(reinterpret_cast<const char*>(export_tmp.data), export_tmp.data_length);
    616     free((void*)export_tmp.data);
    617     return error;
    618 }
    619 
    620 void Keymaster2Test::CheckHmacTestVector(const string& key, const string& message,
    621                                          keymaster_digest_t digest, string expected_mac) {
    622     ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
    623                                          .HmacKey(key.size() * 8)
    624                                          .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
    625                                          .Digest(digest),
    626                                      KM_KEY_FORMAT_RAW, key));
    627     string signature;
    628     MacMessage(message, &signature, expected_mac.size() * 8);
    629     EXPECT_EQ(expected_mac, signature) << "Test vector didn't match for digest " << (int)digest;
    630 }
    631 
    632 void Keymaster2Test::CheckAesCtrTestVector(const string& key, const string& nonce,
    633                                            const string& message,
    634                                            const string& expected_ciphertext) {
    635     ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
    636                                          .AesEncryptionKey(key.size() * 8)
    637                                          .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
    638                                          .Authorization(TAG_CALLER_NONCE)
    639                                          .Padding(KM_PAD_NONE),
    640                                      KM_KEY_FORMAT_RAW, key));
    641 
    642     AuthorizationSet begin_params(client_params()), update_params, output_params;
    643     begin_params.push_back(TAG_NONCE, nonce.data(), nonce.size());
    644     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
    645     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
    646     string ciphertext =
    647         EncryptMessageWithParams(message, begin_params, update_params, &output_params);
    648     EXPECT_EQ(expected_ciphertext, ciphertext);
    649 }
    650 
    651 AuthorizationSet Keymaster2Test::hw_enforced() {
    652     return AuthorizationSet(characteristics_.hw_enforced);
    653 }
    654 
    655 AuthorizationSet Keymaster2Test::sw_enforced() {
    656     return AuthorizationSet(characteristics_.sw_enforced);
    657 }
    658 
    659 void Keymaster2Test::FreeCharacteristics() {
    660     keymaster_free_characteristics(&characteristics_);
    661 }
    662 
    663 void Keymaster2Test::FreeKeyBlob() {
    664     free(const_cast<uint8_t*>(blob_.key_material));
    665     blob_.key_material = NULL;
    666 }
    667 
    668 void Keymaster2Test::corrupt_key_blob() {
    669     assert(blob_.key_material);
    670     uint8_t* tmp = const_cast<uint8_t*>(blob_.key_material);
    671     ++tmp[blob_.key_material_size / 2];
    672 }
    673 
    674 class Sha256OnlyWrapper {
    675   public:
    676     explicit Sha256OnlyWrapper(const keymaster1_device_t* wrapped_device)
    677         : wrapped_device_(wrapped_device) {
    678 
    679         new_module = *wrapped_device_->common.module;
    680         new_module_name = std::string("SHA 256-only ") + wrapped_device_->common.module->name;
    681         new_module.name = new_module_name.c_str();
    682 
    683         memset(&device_, 0, sizeof(device_));
    684         device_.common.module = &new_module;
    685 
    686         device_.common.close = close_device;
    687         device_.get_supported_algorithms = get_supported_algorithms;
    688         device_.get_supported_block_modes = get_supported_block_modes;
    689         device_.get_supported_padding_modes = get_supported_padding_modes;
    690         device_.get_supported_digests = get_supported_digests;
    691         device_.get_supported_import_formats = get_supported_import_formats;
    692         device_.get_supported_export_formats = get_supported_export_formats;
    693         device_.add_rng_entropy = add_rng_entropy;
    694         device_.generate_key = generate_key;
    695         device_.get_key_characteristics = get_key_characteristics;
    696         device_.import_key = import_key;
    697         device_.export_key = export_key;
    698         device_.begin = begin;
    699         device_.update = update;
    700         device_.finish = finish;
    701         device_.abort = abort;
    702     }
    703 
    704     keymaster1_device_t* keymaster_device() { return &device_; }
    705 
    706     static bool is_supported(keymaster_digest_t digest) {
    707         return digest == KM_DIGEST_NONE || digest == KM_DIGEST_SHA_2_256;
    708     }
    709 
    710     static bool all_digests_supported(const keymaster_key_param_set_t* params) {
    711         for (size_t i = 0; i < params->length; ++i)
    712             if (params->params[i].tag == TAG_DIGEST)
    713                 if (!is_supported(static_cast<keymaster_digest_t>(params->params[i].enumerated)))
    714                     return false;
    715         return true;
    716     }
    717 
    718     static const keymaster_key_param_t*
    719     get_algorithm_param(const keymaster_key_param_set_t* params) {
    720         keymaster_key_param_t* end = params->params + params->length;
    721         auto alg_ptr = std::find_if(params->params, end, [](keymaster_key_param_t& p) {
    722             return p.tag == KM_TAG_ALGORITHM;
    723         });
    724         if (alg_ptr == end)
    725             return nullptr;
    726         return alg_ptr;
    727     }
    728 
    729     static int close_device(hw_device_t* dev) {
    730         Sha256OnlyWrapper* wrapper = reinterpret_cast<Sha256OnlyWrapper*>(dev);
    731         const keymaster1_device_t* wrapped_device = wrapper->wrapped_device_;
    732         delete wrapper;
    733         return wrapped_device->common.close(const_cast<hw_device_t*>(&wrapped_device->common));
    734     }
    735 
    736     static const keymaster1_device_t* unwrap(const keymaster1_device_t* dev) {
    737         return reinterpret_cast<const Sha256OnlyWrapper*>(dev)->wrapped_device_;
    738     }
    739 
    740     static keymaster_error_t get_supported_algorithms(const struct keymaster1_device* dev,
    741                                                       keymaster_algorithm_t** algorithms,
    742                                                       size_t* algorithms_length) {
    743         return unwrap(dev)->get_supported_algorithms(unwrap(dev), algorithms, algorithms_length);
    744     }
    745     static keymaster_error_t get_supported_block_modes(const struct keymaster1_device* dev,
    746                                                        keymaster_algorithm_t algorithm,
    747                                                        keymaster_purpose_t purpose,
    748                                                        keymaster_block_mode_t** modes,
    749                                                        size_t* modes_length) {
    750         return unwrap(dev)->get_supported_block_modes(unwrap(dev), algorithm, purpose, modes,
    751                                                       modes_length);
    752     }
    753     static keymaster_error_t get_supported_padding_modes(const struct keymaster1_device* dev,
    754                                                          keymaster_algorithm_t algorithm,
    755                                                          keymaster_purpose_t purpose,
    756                                                          keymaster_padding_t** modes,
    757                                                          size_t* modes_length) {
    758         return unwrap(dev)->get_supported_padding_modes(unwrap(dev), algorithm, purpose, modes,
    759                                                         modes_length);
    760     }
    761 
    762     static keymaster_error_t get_supported_digests(const keymaster1_device_t* dev,
    763                                                    keymaster_algorithm_t algorithm,
    764                                                    keymaster_purpose_t purpose,
    765                                                    keymaster_digest_t** digests,
    766                                                    size_t* digests_length) {
    767         keymaster_error_t error = unwrap(dev)->get_supported_digests(
    768             unwrap(dev), algorithm, purpose, digests, digests_length);
    769         if (error != KM_ERROR_OK)
    770             return error;
    771 
    772         std::vector<keymaster_digest_t> filtered_digests;
    773         std::copy_if(*digests, *digests + *digests_length, std::back_inserter(filtered_digests),
    774                      [](keymaster_digest_t digest) { return is_supported(digest); });
    775 
    776         free(*digests);
    777         *digests_length = filtered_digests.size();
    778         *digests = reinterpret_cast<keymaster_digest_t*>(
    779             malloc(*digests_length * sizeof(keymaster_digest_t)));
    780         std::copy(filtered_digests.begin(), filtered_digests.end(), *digests);
    781 
    782         return KM_ERROR_OK;
    783     }
    784 
    785     static keymaster_error_t get_supported_import_formats(const struct keymaster1_device* dev,
    786                                                           keymaster_algorithm_t algorithm,
    787                                                           keymaster_key_format_t** formats,
    788                                                           size_t* formats_length) {
    789         return unwrap(dev)->get_supported_import_formats(unwrap(dev), algorithm, formats,
    790                                                          formats_length);
    791     }
    792     static keymaster_error_t get_supported_export_formats(const struct keymaster1_device* dev,
    793                                                           keymaster_algorithm_t algorithm,
    794                                                           keymaster_key_format_t** formats,
    795                                                           size_t* formats_length) {
    796         return unwrap(dev)->get_supported_export_formats(unwrap(dev), algorithm, formats,
    797                                                          formats_length);
    798     }
    799     static keymaster_error_t add_rng_entropy(const struct keymaster1_device* dev,
    800                                              const uint8_t* data, size_t data_length) {
    801         return unwrap(dev)->add_rng_entropy(unwrap(dev), data, data_length);
    802     }
    803 
    804     static keymaster_error_t generate_key(const keymaster1_device_t* dev,
    805                                           const keymaster_key_param_set_t* params,
    806                                           keymaster_key_blob_t* key_blob,
    807                                           keymaster_key_characteristics_t** characteristics) {
    808         auto alg_ptr = get_algorithm_param(params);
    809         if (!alg_ptr)
    810             return KM_ERROR_UNSUPPORTED_ALGORITHM;
    811         if (alg_ptr->enumerated == KM_ALGORITHM_HMAC && !all_digests_supported(params))
    812             return KM_ERROR_UNSUPPORTED_DIGEST;
    813 
    814         return unwrap(dev)->generate_key(unwrap(dev), params, key_blob, characteristics);
    815     }
    816 
    817     static keymaster_error_t
    818     get_key_characteristics(const struct keymaster1_device* dev,
    819                             const keymaster_key_blob_t* key_blob, const keymaster_blob_t* client_id,
    820                             const keymaster_blob_t* app_data,
    821                             keymaster_key_characteristics_t** characteristics) {
    822         return unwrap(dev)->get_key_characteristics(unwrap(dev), key_blob, client_id, app_data,
    823                                                     characteristics);
    824     }
    825 
    826     static keymaster_error_t
    827     import_key(const keymaster1_device_t* dev, const keymaster_key_param_set_t* params,
    828                keymaster_key_format_t key_format, const keymaster_blob_t* key_data,
    829                keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t** characteristics) {
    830         auto alg_ptr = get_algorithm_param(params);
    831         if (!alg_ptr)
    832             return KM_ERROR_UNSUPPORTED_ALGORITHM;
    833         if (alg_ptr->enumerated == KM_ALGORITHM_HMAC && !all_digests_supported(params))
    834             return KM_ERROR_UNSUPPORTED_DIGEST;
    835 
    836         return unwrap(dev)->import_key(unwrap(dev), params, key_format, key_data, key_blob,
    837                                        characteristics);
    838     }
    839 
    840     static keymaster_error_t export_key(const struct keymaster1_device* dev,  //
    841                                         keymaster_key_format_t export_format,
    842                                         const keymaster_key_blob_t* key_to_export,
    843                                         const keymaster_blob_t* client_id,
    844                                         const keymaster_blob_t* app_data,
    845                                         keymaster_blob_t* export_data) {
    846         return unwrap(dev)->export_key(unwrap(dev), export_format, key_to_export, client_id,
    847                                        app_data, export_data);
    848     }
    849 
    850     static keymaster_error_t begin(const keymaster1_device_t* dev,  //
    851                                    keymaster_purpose_t purpose, const keymaster_key_blob_t* key,
    852                                    const keymaster_key_param_set_t* in_params,
    853                                    keymaster_key_param_set_t* out_params,
    854                                    keymaster_operation_handle_t* operation_handle) {
    855         if (!all_digests_supported(in_params))
    856             return KM_ERROR_UNSUPPORTED_DIGEST;
    857         return unwrap(dev)->begin(unwrap(dev), purpose, key, in_params, out_params,
    858                                   operation_handle);
    859     }
    860 
    861     static keymaster_error_t update(const keymaster1_device_t* dev,
    862                                     keymaster_operation_handle_t operation_handle,
    863                                     const keymaster_key_param_set_t* in_params,
    864                                     const keymaster_blob_t* input, size_t* input_consumed,
    865                                     keymaster_key_param_set_t* out_params,
    866                                     keymaster_blob_t* output) {
    867         return unwrap(dev)->update(unwrap(dev), operation_handle, in_params, input, input_consumed,
    868                                    out_params, output);
    869     }
    870 
    871     static keymaster_error_t finish(const struct keymaster1_device* dev,  //
    872                                     keymaster_operation_handle_t operation_handle,
    873                                     const keymaster_key_param_set_t* in_params,
    874                                     const keymaster_blob_t* signature,
    875                                     keymaster_key_param_set_t* out_params,
    876                                     keymaster_blob_t* output) {
    877         return unwrap(dev)->finish(unwrap(dev), operation_handle, in_params, signature, out_params,
    878                                    output);
    879     }
    880 
    881     static keymaster_error_t abort(const struct keymaster1_device* dev,
    882                                    keymaster_operation_handle_t operation_handle) {
    883         return unwrap(dev)->abort(unwrap(dev), operation_handle);
    884     }
    885 
    886   private:
    887     keymaster1_device_t device_;
    888     const keymaster1_device_t* wrapped_device_;
    889     hw_module_t new_module;
    890     string new_module_name;
    891 };
    892 
    893 keymaster1_device_t* make_device_sha256_only(keymaster1_device_t* device) {
    894     return (new Sha256OnlyWrapper(device))->keymaster_device();
    895 }
    896 
    897 }  // namespace test
    898 }  // namespace keymaster
    899