Home | History | Annotate | Download | only in tests
      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 #ifndef SYSTEM_KEYMASTER_ANDROID_KEYMASTER_TEST_UTILS_H_
     18 #define SYSTEM_KEYMASTER_ANDROID_KEYMASTER_TEST_UTILS_H_
     19 
     20 /*
     21  * Utilities used to help with testing.  Not used in production code.
     22  */
     23 
     24 #include <stdarg.h>
     25 
     26 #include <algorithm>
     27 #include <memory>
     28 #include <ostream>
     29 #include <string>
     30 #include <vector>
     31 
     32 #include <gtest/gtest.h>
     33 
     34 #include <hardware/keymaster0.h>
     35 #include <hardware/keymaster1.h>
     36 #include <hardware/keymaster2.h>
     37 #include <hardware/keymaster_defs.h>
     38 
     39 #include <keymaster/android_keymaster_utils.h>
     40 #include <keymaster/authorization_set.h>
     41 #include <keymaster/keymaster_context.h>
     42 #include <keymaster/logger.h>
     43 
     44 std::ostream& operator<<(std::ostream& os, const keymaster_key_param_t& param);
     45 bool operator==(const keymaster_key_param_t& a, const keymaster_key_param_t& b);
     46 std::string hex2str(std::string);
     47 
     48 namespace keymaster {
     49 
     50 bool operator==(const AuthorizationSet& a, const AuthorizationSet& b);
     51 bool operator!=(const AuthorizationSet& a, const AuthorizationSet& b);
     52 
     53 std::ostream& operator<<(std::ostream& os, const AuthorizationSet& set);
     54 
     55 namespace test {
     56 
     57 template <keymaster_tag_t Tag, typename KeymasterEnum>
     58 bool contains(const AuthorizationSet& set, TypedEnumTag<KM_ENUM, Tag, KeymasterEnum> tag,
     59               KeymasterEnum val) {
     60     int pos = set.find(tag);
     61     return pos != -1 && static_cast<KeymasterEnum>(set[pos].enumerated) == val;
     62 }
     63 
     64 template <keymaster_tag_t Tag, typename KeymasterEnum>
     65 bool contains(const AuthorizationSet& set, TypedEnumTag<KM_ENUM_REP, Tag, KeymasterEnum> tag,
     66               KeymasterEnum val) {
     67     int pos = -1;
     68     while ((pos = set.find(tag, pos)) != -1)
     69         if (static_cast<KeymasterEnum>(set[pos].enumerated) == val)
     70             return true;
     71     return false;
     72 }
     73 
     74 template <keymaster_tag_t Tag>
     75 bool contains(const AuthorizationSet& set, TypedTag<KM_UINT, Tag> tag, uint32_t val) {
     76     int pos = set.find(tag);
     77     return pos != -1 && set[pos].integer == val;
     78 }
     79 
     80 template <keymaster_tag_t Tag>
     81 bool contains(const AuthorizationSet& set, TypedTag<KM_UINT_REP, Tag> tag, uint32_t val) {
     82     int pos = -1;
     83     while ((pos = set.find(tag, pos)) != -1)
     84         if (set[pos].integer == val)
     85             return true;
     86     return false;
     87 }
     88 
     89 template <keymaster_tag_t Tag>
     90 bool contains(const AuthorizationSet& set, TypedTag<KM_ULONG, Tag> tag, uint64_t val) {
     91     int pos = set.find(tag);
     92     return pos != -1 && set[pos].long_integer == val;
     93 }
     94 
     95 template <keymaster_tag_t Tag>
     96 bool contains(const AuthorizationSet& set, TypedTag<KM_BYTES, Tag> tag, const std::string& val) {
     97     int pos = set.find(tag);
     98     return pos != -1 &&
     99            std::string(reinterpret_cast<const char*>(set[pos].blob.data),
    100                        set[pos].blob.data_length) == val;
    101 }
    102 
    103 template <keymaster_tag_t Tag>
    104 bool contains(const AuthorizationSet& set, TypedTag<KM_BIGNUM, Tag> tag, const std::string& val) {
    105     int pos = set.find(tag);
    106     return pos != -1 &&
    107            std::string(reinterpret_cast<const char*>(set[pos].blob.data),
    108                        set[pos].blob.data_length) == val;
    109 }
    110 
    111 inline bool contains(const AuthorizationSet& set, keymaster_tag_t tag) {
    112     return set.find(tag) != -1;
    113 }
    114 
    115 class StdoutLogger : public Logger {
    116   public:
    117     StdoutLogger() { set_instance(this); }
    118 
    119     int log_msg(LogLevel level, const char* fmt, va_list args) const {
    120         int output_len = 0;
    121         switch (level) {
    122         case DEBUG_LVL:
    123             output_len = printf("DEBUG: ");
    124             break;
    125         case INFO_LVL:
    126             output_len = printf("INFO: ");
    127             break;
    128         case WARNING_LVL:
    129             output_len = printf("WARNING: ");
    130             break;
    131         case ERROR_LVL:
    132             output_len = printf("ERROR: ");
    133             break;
    134         case SEVERE_LVL:
    135             output_len = printf("SEVERE: ");
    136             break;
    137         }
    138 
    139         output_len += vprintf(fmt, args);
    140         output_len += printf("\n");
    141         return output_len;
    142     }
    143 };
    144 
    145 inline std::string make_string(const uint8_t* data, size_t length) {
    146     return std::string(reinterpret_cast<const char*>(data), length);
    147 }
    148 
    149 template <size_t N> std::string make_string(const uint8_t (&a)[N]) {
    150     return make_string(a, N);
    151 }
    152 
    153 /**
    154  * Keymaster2TestInstance is used to parameterize Keymaster2Tests.  Its main function is to create a
    155  * keymaster2_device_t to which test calls can be directed.  It also provides a place to specify
    156  * various bits of alternative behavior, in cases where different devices are expected to behave
    157  * differently (any such cases are a potential bug, but sometimes they may make sense).
    158  */
    159 class Keymaster2TestInstanceCreator {
    160   public:
    161     virtual ~Keymaster2TestInstanceCreator(){};
    162     virtual keymaster2_device_t* CreateDevice() const = 0;
    163 
    164     virtual bool algorithm_in_km0_hardware(keymaster_algorithm_t algorithm) const = 0;
    165     virtual int keymaster0_calls() const = 0;
    166     virtual int minimal_digest_set() const { return false; }
    167     virtual bool is_keymaster1_hw() const = 0;
    168     virtual KeymasterContext* keymaster_context() const = 0;
    169 
    170     virtual std::string name() const = 0;
    171 };
    172 
    173 // Use a shared_ptr because it's copyable.
    174 typedef std::shared_ptr<Keymaster2TestInstanceCreator> InstanceCreatorPtr;
    175 
    176 std::ostream& operator<<(std::ostream& os, const InstanceCreatorPtr& instance_creator);
    177 
    178 const uint64_t OP_HANDLE_SENTINEL = 0xFFFFFFFFFFFFFFFF;
    179 class Keymaster2Test : public testing::TestWithParam<InstanceCreatorPtr> {
    180   protected:
    181     Keymaster2Test();
    182     ~Keymaster2Test();
    183 
    184     keymaster2_device_t* device();
    185 
    186     keymaster_error_t GenerateKey(const AuthorizationSetBuilder& builder);
    187 
    188     keymaster_error_t DeleteKey();
    189 
    190     keymaster_error_t ImportKey(const AuthorizationSetBuilder& builder,
    191                                 keymaster_key_format_t format, const std::string& key_material);
    192 
    193     keymaster_error_t ExportKey(keymaster_key_format_t format, std::string* export_data);
    194 
    195     keymaster_error_t GetCharacteristics();
    196 
    197     keymaster_error_t BeginOperation(keymaster_purpose_t purpose);
    198     keymaster_error_t BeginOperation(keymaster_purpose_t purpose, const AuthorizationSet& input_set,
    199                                      AuthorizationSet* output_set = NULL);
    200 
    201     keymaster_error_t UpdateOperation(const std::string& message, std::string* output,
    202                                       size_t* input_consumed);
    203     keymaster_error_t UpdateOperation(const AuthorizationSet& additional_params,
    204                                       const std::string& message, AuthorizationSet* output_params,
    205                                       std::string* output, size_t* input_consumed);
    206 
    207     keymaster_error_t FinishOperation(std::string* output);
    208     keymaster_error_t FinishOperation(const std::string& input, const std::string& signature,
    209                                       std::string* output);
    210     keymaster_error_t FinishOperation(const AuthorizationSet& additional_params,
    211                                       const std::string& input, const std::string& signature,
    212                                       std::string* output) {
    213         return FinishOperation(additional_params, input, signature, nullptr /* output_params */,
    214                                output);
    215     }
    216     keymaster_error_t FinishOperation(const AuthorizationSet& additional_params,
    217                                       const std::string& input, const std::string& signature,
    218                                       AuthorizationSet* output_params, std::string* output);
    219 
    220     keymaster_error_t AbortOperation();
    221 
    222     keymaster_error_t AttestKey(const std::string& attest_challenge,
    223                                 const std::string& attest_app_id, keymaster_cert_chain_t* chain);
    224 
    225     keymaster_error_t UpgradeKey(const AuthorizationSet& upgrade_params);
    226 
    227     keymaster_error_t GetVersion(uint8_t* major, uint8_t* minor, uint8_t* subminor);
    228     std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message);
    229     std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message,
    230                                const AuthorizationSet& begin_params,
    231                                const AuthorizationSet& update_params,
    232                                AuthorizationSet* output_params = NULL);
    233     std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message,
    234                                const std::string& signature, const AuthorizationSet& begin_params,
    235                                const AuthorizationSet& update_params,
    236                                AuthorizationSet* output_params = NULL);
    237     std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message,
    238                                const std::string& signature);
    239 
    240     void SignMessage(const std::string& message, std::string* signature, keymaster_digest_t digest);
    241     void SignMessage(const std::string& message, std::string* signature, keymaster_digest_t digest,
    242                      keymaster_padding_t padding);
    243     void MacMessage(const std::string& message, std::string* signature, size_t mac_length);
    244 
    245     void VerifyMessage(const std::string& message, const std::string& signature,
    246                        keymaster_digest_t digest);
    247     void VerifyMessage(const std::string& message, const std::string& signature,
    248                        keymaster_digest_t digest, keymaster_padding_t padding);
    249     void VerifyMac(const std::string& message, const std::string& signature);
    250 
    251     std::string EncryptMessage(const std::string& message, keymaster_padding_t padding,
    252                                std::string* generated_nonce = NULL);
    253     std::string EncryptMessage(const std::string& message, keymaster_digest_t digest,
    254                                keymaster_padding_t padding, std::string* generated_nonce = NULL);
    255     std::string EncryptMessage(const std::string& message, keymaster_block_mode_t block_mode,
    256                                keymaster_padding_t padding, std::string* generated_nonce = NULL);
    257     std::string EncryptMessage(const AuthorizationSet& update_params, const std::string& message,
    258                                keymaster_digest_t digest, keymaster_padding_t padding,
    259                                std::string* generated_nonce = NULL);
    260     std::string EncryptMessage(const AuthorizationSet& update_params, const std::string& message,
    261                                keymaster_block_mode_t block_mode, keymaster_padding_t padding,
    262                                std::string* generated_nonce = NULL);
    263     std::string EncryptMessageWithParams(const std::string& message,
    264                                          const AuthorizationSet& begin_params,
    265                                          const AuthorizationSet& update_params,
    266                                          AuthorizationSet* output_params);
    267 
    268     std::string DecryptMessage(const std::string& ciphertext, keymaster_padding_t padding);
    269     std::string DecryptMessage(const std::string& ciphertext, keymaster_digest_t digest,
    270                                keymaster_padding_t padding);
    271     std::string DecryptMessage(const std::string& ciphertext, keymaster_block_mode_t block_mode,
    272                                keymaster_padding_t padding);
    273     std::string DecryptMessage(const std::string& ciphertext, keymaster_digest_t digest,
    274                                keymaster_padding_t padding, const std::string& nonce);
    275     std::string DecryptMessage(const std::string& ciphertext, keymaster_block_mode_t block_mode,
    276                                keymaster_padding_t padding, const std::string& nonce);
    277     std::string DecryptMessage(const AuthorizationSet& update_params, const std::string& ciphertext,
    278                                keymaster_digest_t digest, keymaster_padding_t padding,
    279                                const std::string& nonce);
    280     std::string DecryptMessage(const AuthorizationSet& update_params, const std::string& ciphertext,
    281                                keymaster_block_mode_t block_mode, keymaster_padding_t padding,
    282                                const std::string& nonce);
    283     std::string DecryptMessageWithParams(const std::string& message,
    284                                          const AuthorizationSet& begin_params,
    285                                          const AuthorizationSet& update_params,
    286                                          AuthorizationSet* output_params);
    287 
    288     void CheckHmacTestVector(const std::string& key, const std::string& message,
    289                              keymaster_digest_t digest, std::string expected_mac);
    290     void CheckAesOcbTestVector(const std::string& key, const std::string& nonce,
    291                                const std::string& associated_data, const std::string& message,
    292                                const std::string& expected_ciphertext);
    293     void CheckAesCtrTestVector(const std::string& key, const std::string& nonce,
    294                                const std::string& message, const std::string& expected_ciphertext);
    295     void CheckTripleDesTestVector(keymaster_purpose_t purpose, keymaster_block_mode_t mode,
    296                                   keymaster_padding_t padding, const std::string& key,
    297                                   const std::string& iv, const std::string& message,
    298                                   const std::string& expected_ciphertext);
    299     AuthorizationSet UserAuthParams();
    300     AuthorizationSet ClientParams();
    301 
    302     template <typename T>
    303     bool ResponseContains(const std::vector<T>& expected, const T* values, size_t len) {
    304         return expected.size() == len &&
    305                std::is_permutation(values, values + len, expected.begin());
    306     }
    307 
    308     template <typename T> bool ResponseContains(T expected, const T* values, size_t len) {
    309         return (len == 1 && *values == expected);
    310     }
    311 
    312     AuthorizationSet hw_enforced();
    313     AuthorizationSet sw_enforced();
    314 
    315     void FreeCharacteristics();
    316     void FreeKeyBlob();
    317 
    318     void corrupt_key_blob();
    319 
    320     void set_key_blob(const uint8_t* key, size_t key_length) {
    321         FreeKeyBlob();
    322         blob_.key_material = key;
    323         blob_.key_material_size = key_length;
    324     }
    325 
    326     void set_key_blob(KeymasterKeyBlob blob) { blob_ = blob.release(); }
    327     void set_key_characteristics(const AuthorizationSet& hw_enforced,
    328                                  const AuthorizationSet& sw_enforced) {
    329         FreeCharacteristics();
    330         hw_enforced.CopyToParamSet(&characteristics_.hw_enforced);
    331         sw_enforced.CopyToParamSet(&characteristics_.sw_enforced);
    332     }
    333 
    334     AuthorizationSet client_params() {
    335         return AuthorizationSet(client_params_, sizeof(client_params_) / sizeof(client_params_[0]));
    336     }
    337 
    338   private:
    339     keymaster2_device_t* device_;
    340     keymaster_blob_t client_id_ = {.data = reinterpret_cast<const uint8_t*>("app_id"),
    341                                    .data_length = 6};
    342     keymaster_key_param_t client_params_[1] = {
    343         Authorization(TAG_APPLICATION_ID, client_id_.data, client_id_.data_length)};
    344 
    345     uint64_t op_handle_;
    346 
    347     keymaster_key_blob_t blob_;
    348     keymaster_key_characteristics_t characteristics_;
    349 };
    350 
    351 struct Keymaster0CountingWrapper : public keymaster0_device_t {
    352     explicit Keymaster0CountingWrapper(keymaster0_device_t* device) : device_(device), counter_(0) {
    353         common = device_->common;
    354         common.close = counting_close_device;
    355         client_version = device_->client_version;
    356         flags = device_->flags;
    357         context = this;
    358 
    359         generate_keypair = counting_generate_keypair;
    360         import_keypair = counting_import_keypair;
    361         get_keypair_public = counting_get_keypair_public;
    362         delete_keypair = counting_delete_keypair;
    363         delete_all = counting_delete_all;
    364         sign_data = counting_sign_data;
    365         verify_data = counting_verify_data;
    366     }
    367 
    368     int count() { return counter_; }
    369 
    370     // The blobs generated by the underlying softkeymaster start with "PK#8".  Tweak the prefix so
    371     // they don't get identified as softkeymaster blobs.
    372     static void munge_blob(uint8_t* blob, size_t blob_length) {
    373         if (blob && blob_length > 0 && *blob == 'P')
    374             *blob = 'Q';  // Mind your Ps and Qs!
    375     }
    376 
    377     // Copy and un-modfy the blob.  The caller must clean up the return value.
    378     static uint8_t* unmunge_blob(const uint8_t* blob, size_t blob_length) {
    379         uint8_t* dup_blob = dup_buffer(blob, blob_length);
    380         if (dup_blob && blob_length > 0 && *dup_blob == 'Q')
    381             *dup_blob = 'P';
    382         return dup_blob;
    383     }
    384 
    385     static keymaster0_device_t* device(const keymaster0_device_t* dev) {
    386         Keymaster0CountingWrapper* wrapper =
    387             reinterpret_cast<Keymaster0CountingWrapper*>(dev->context);
    388         return wrapper->device_;
    389     }
    390 
    391     static void increment(const keymaster0_device_t* dev) {
    392         Keymaster0CountingWrapper* wrapper =
    393             reinterpret_cast<Keymaster0CountingWrapper*>(dev->context);
    394         wrapper->counter_++;
    395     }
    396 
    397     static int counting_close_device(hw_device_t* dev) {
    398         keymaster0_device_t* k0_dev = reinterpret_cast<keymaster0_device_t*>(dev);
    399         increment(k0_dev);
    400         Keymaster0CountingWrapper* wrapper =
    401             reinterpret_cast<Keymaster0CountingWrapper*>(k0_dev->context);
    402         int retval =
    403             wrapper->device_->common.close(reinterpret_cast<hw_device_t*>(wrapper->device_));
    404         delete wrapper;
    405         return retval;
    406     }
    407 
    408     static int counting_generate_keypair(const struct keymaster0_device* dev,
    409                                          const keymaster_keypair_t key_type, const void* key_params,
    410                                          uint8_t** key_blob, size_t* key_blob_length) {
    411         increment(dev);
    412         int result = device(dev)->generate_keypair(device(dev), key_type, key_params, key_blob,
    413                                                    key_blob_length);
    414         if (result == 0)
    415             munge_blob(*key_blob, *key_blob_length);
    416         return result;
    417     }
    418 
    419     static int counting_import_keypair(const struct keymaster0_device* dev, const uint8_t* key,
    420                                        const size_t key_length, uint8_t** key_blob,
    421                                        size_t* key_blob_length) {
    422         increment(dev);
    423         int result =
    424             device(dev)->import_keypair(device(dev), key, key_length, key_blob, key_blob_length);
    425         if (result == 0)
    426             munge_blob(*key_blob, *key_blob_length);
    427         return result;
    428     }
    429 
    430     static int counting_get_keypair_public(const struct keymaster0_device* dev,
    431                                            const uint8_t* key_blob, const size_t key_blob_length,
    432                                            uint8_t** x509_data, size_t* x509_data_length) {
    433         increment(dev);
    434         std::unique_ptr<uint8_t[]> dup_blob(unmunge_blob(key_blob, key_blob_length));
    435         return device(dev)->get_keypair_public(device(dev), dup_blob.get(), key_blob_length,
    436                                                x509_data, x509_data_length);
    437     }
    438 
    439     static int counting_delete_keypair(const struct keymaster0_device* dev, const uint8_t* key_blob,
    440                                        const size_t key_blob_length) {
    441         increment(dev);
    442         if (key_blob && key_blob_length > 0)
    443             EXPECT_EQ('Q', *key_blob);
    444         if (device(dev)->delete_keypair) {
    445             std::unique_ptr<uint8_t[]> dup_blob(unmunge_blob(key_blob, key_blob_length));
    446             return device(dev)->delete_keypair(device(dev), dup_blob.get(), key_blob_length);
    447         }
    448         return 0;
    449     }
    450 
    451     static int counting_delete_all(const struct keymaster0_device* dev) {
    452         increment(dev);
    453         if (device(dev)->delete_all)
    454             return device(dev)->delete_all(device(dev));
    455         return 0;
    456     }
    457 
    458     static int counting_sign_data(const struct keymaster0_device* dev, const void* signing_params,
    459                                   const uint8_t* key_blob, const size_t key_blob_length,
    460                                   const uint8_t* data, const size_t data_length,
    461                                   uint8_t** signed_data, size_t* signed_data_length) {
    462         increment(dev);
    463         std::unique_ptr<uint8_t[]> dup_blob(unmunge_blob(key_blob, key_blob_length));
    464         return device(dev)->sign_data(device(dev), signing_params, dup_blob.get(), key_blob_length,
    465                                       data, data_length, signed_data, signed_data_length);
    466     }
    467 
    468     static int counting_verify_data(const struct keymaster0_device* dev, const void* signing_params,
    469                                     const uint8_t* key_blob, const size_t key_blob_length,
    470                                     const uint8_t* signed_data, const size_t signed_data_length,
    471                                     const uint8_t* signature, const size_t signature_length) {
    472         increment(dev);
    473         std::unique_ptr<uint8_t[]> dup_blob(unmunge_blob(key_blob, key_blob_length));
    474         return device(dev)->verify_data(device(dev), signing_params, dup_blob.get(),
    475                                         key_blob_length, signed_data, signed_data_length, signature,
    476                                         signature_length);
    477     }
    478 
    479   private:
    480     keymaster0_device_t* device_;
    481     int counter_;
    482 };
    483 
    484 /**
    485  * This function takes a keymaster1_device_t and wraps it in an adapter that supports only
    486  * KM_DIGEST_SHA_2_256.
    487  */
    488 keymaster1_device_t* make_device_sha256_only(keymaster1_device_t* device);
    489 
    490 }  // namespace test
    491 }  // namespace keymaster
    492 
    493 #endif  // SYSTEM_KEYMASTER_ANDROID_KEYMASTER_TEST_UTILS_H_
    494