Home | History | Annotate | Download | only in keymaster
      1 /*
      2  * Copyright 2015 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 "keymaster0_engine.h"
     18 
     19 #include <assert.h>
     20 
     21 #include <memory>
     22 
     23 #define LOG_TAG "Keymaster0Engine"
     24 #include <cutils/log.h>
     25 
     26 #include "keymaster/android_keymaster_utils.h"
     27 
     28 #include <openssl/bn.h>
     29 #include <openssl/ec_key.h>
     30 #include <openssl/ecdsa.h>
     31 
     32 #include "openssl_utils.h"
     33 
     34 using std::shared_ptr;
     35 using std::unique_ptr;
     36 
     37 namespace keymaster {
     38 
     39 // int Keymaster0Engine::rsa_index_ = -1;
     40 // int Keymaster0Engine::ec_key_index_ = -1;
     41 Keymaster0Engine* Keymaster0Engine::instance_ = nullptr;
     42 const RSA_METHOD Keymaster0Engine::rsa_method_ = {
     43     .common =
     44         {
     45             0,  // references
     46             1   // is_static
     47         },
     48     .app_data = nullptr,
     49     .init = nullptr,
     50     .finish = nullptr,
     51     .size = nullptr,
     52     .sign = nullptr,
     53     .verify = nullptr,
     54 
     55     .encrypt = nullptr,
     56     .sign_raw = nullptr,
     57     .decrypt = nullptr,
     58     .verify_raw = nullptr,
     59 
     60     .private_transform = Keymaster0Engine::rsa_private_transform,
     61 
     62     .mod_exp = nullptr,
     63     .bn_mod_exp = BN_mod_exp_mont,
     64 
     65     .flags = RSA_FLAG_OPAQUE,
     66 
     67     .keygen = nullptr,
     68     .supports_digest = nullptr,
     69 };
     70 
     71 const ECDSA_METHOD Keymaster0Engine::ecdsa_method_ = {
     72     .common =
     73         {
     74             0,  // references
     75             1   // is_static
     76         },
     77     .app_data = nullptr,
     78     .init = nullptr,
     79     .finish = nullptr,
     80     .group_order_size = nullptr,
     81     .sign = Keymaster0Engine::ecdsa_sign,
     82     .verify = nullptr,
     83     .flags = ECDSA_FLAG_OPAQUE,
     84 };
     85 
     86 Keymaster0Engine::Keymaster0Engine(const keymaster0_device_t* keymaster0_device)
     87     : keymaster0_device_(keymaster0_device), engine_(ENGINE_new()), supports_ec_(false) {
     88     assert(!instance_);
     89     instance_ = this;
     90 
     91     rsa_index_ = RSA_get_ex_new_index(0 /* argl */, NULL /* argp */, NULL /* new_func */,
     92                                       keyblob_dup, keyblob_free);
     93     ec_key_index_ = EC_KEY_get_ex_new_index(0 /* argl */, NULL /* argp */, NULL /* new_func */,
     94                                             keyblob_dup, keyblob_free);
     95 
     96     ENGINE_set_RSA_method(engine_, &rsa_method_, sizeof(rsa_method_));
     97 
     98     if ((keymaster0_device_->flags & KEYMASTER_SUPPORTS_EC) != 0) {
     99         supports_ec_ = true;
    100         ENGINE_set_ECDSA_method(engine_, &ecdsa_method_, sizeof(ecdsa_method_));
    101     }
    102 }
    103 
    104 Keymaster0Engine::~Keymaster0Engine() {
    105     if (keymaster0_device_)
    106         keymaster0_device_->common.close(
    107             reinterpret_cast<hw_device_t*>(const_cast<keymaster0_device_t*>(keymaster0_device_)));
    108     ENGINE_free(engine_);
    109     instance_ = nullptr;
    110 }
    111 
    112 bool Keymaster0Engine::GenerateRsaKey(uint64_t public_exponent, uint32_t public_modulus,
    113                                       KeymasterKeyBlob* key_material) const {
    114     assert(key_material);
    115     keymaster_rsa_keygen_params_t params;
    116     params.public_exponent = public_exponent;
    117     params.modulus_size = public_modulus;
    118 
    119     uint8_t* key_blob = 0;
    120     if (keymaster0_device_->generate_keypair(keymaster0_device_, TYPE_RSA, &params, &key_blob,
    121                                              &key_material->key_material_size) < 0) {
    122         ALOGE("Error generating RSA key pair with keymaster0 device");
    123         return false;
    124     }
    125     unique_ptr<uint8_t, Malloc_Delete> key_blob_deleter(key_blob);
    126     key_material->key_material = dup_buffer(key_blob, key_material->key_material_size);
    127     return true;
    128 }
    129 
    130 bool Keymaster0Engine::GenerateEcKey(uint32_t key_size, KeymasterKeyBlob* key_material) const {
    131     assert(key_material);
    132     keymaster_ec_keygen_params_t params;
    133     params.field_size = key_size;
    134 
    135     uint8_t* key_blob = 0;
    136     if (keymaster0_device_->generate_keypair(keymaster0_device_, TYPE_EC, &params, &key_blob,
    137                                              &key_material->key_material_size) < 0) {
    138         ALOGE("Error generating EC key pair with keymaster0 device");
    139         return false;
    140     }
    141     unique_ptr<uint8_t, Malloc_Delete> key_blob_deleter(key_blob);
    142     key_material->key_material = dup_buffer(key_blob, key_material->key_material_size);
    143     return true;
    144 }
    145 
    146 bool Keymaster0Engine::ImportKey(keymaster_key_format_t key_format,
    147                                  const KeymasterKeyBlob& to_import,
    148                                  KeymasterKeyBlob* imported_key) const {
    149     assert(imported_key);
    150     if (key_format != KM_KEY_FORMAT_PKCS8)
    151         return false;
    152 
    153     uint8_t* key_blob = 0;
    154     if (keymaster0_device_->import_keypair(keymaster0_device_, to_import.key_material,
    155                                            to_import.key_material_size, &key_blob,
    156                                            &imported_key->key_material_size) < 0) {
    157         ALOGW("Error importing keypair with keymaster0 device");
    158         return false;
    159     }
    160     unique_ptr<uint8_t, Malloc_Delete> key_blob_deleter(key_blob);
    161     imported_key->key_material = dup_buffer(key_blob, imported_key->key_material_size);
    162     return true;
    163 }
    164 
    165 static keymaster_key_blob_t* duplicate_blob(const uint8_t* key_data, size_t key_data_size) {
    166     unique_ptr<uint8_t[]> key_material_copy(dup_buffer(key_data, key_data_size));
    167     if (!key_material_copy)
    168         return nullptr;
    169 
    170     unique_ptr<keymaster_key_blob_t> blob_copy(new (std::nothrow) keymaster_key_blob_t);
    171     if (!blob_copy.get())
    172         return nullptr;
    173     blob_copy->key_material_size = key_data_size;
    174     blob_copy->key_material = key_material_copy.release();
    175     return blob_copy.release();
    176 }
    177 
    178 inline keymaster_key_blob_t* duplicate_blob(const keymaster_key_blob_t& blob) {
    179     return duplicate_blob(blob.key_material, blob.key_material_size);
    180 }
    181 
    182 RSA* Keymaster0Engine::BlobToRsaKey(const KeymasterKeyBlob& blob) const {
    183     // Create new RSA key (with engine methods) and insert blob
    184     unique_ptr<RSA, RSA_Delete> rsa(RSA_new_method(engine_));
    185     if (!rsa)
    186         return nullptr;
    187 
    188     keymaster_key_blob_t* blob_copy = duplicate_blob(blob);
    189     if (!blob_copy->key_material || !RSA_set_ex_data(rsa.get(), rsa_index_, blob_copy))
    190         return nullptr;
    191 
    192     // Copy public key into new RSA key
    193     unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(GetKeymaster0PublicKey(blob));
    194     if (!pkey)
    195         return nullptr;
    196     unique_ptr<RSA, RSA_Delete> public_rsa(EVP_PKEY_get1_RSA(pkey.get()));
    197     if (!public_rsa)
    198         return nullptr;
    199     rsa->n = BN_dup(public_rsa->n);
    200     rsa->e = BN_dup(public_rsa->e);
    201     if (!rsa->n || !rsa->e)
    202         return nullptr;
    203 
    204     return rsa.release();
    205 }
    206 
    207 EC_KEY* Keymaster0Engine::BlobToEcKey(const KeymasterKeyBlob& blob) const {
    208     // Create new EC key (with engine methods) and insert blob
    209     unique_ptr<EC_KEY, EC_Delete> ec_key(EC_KEY_new_method(engine_));
    210     if (!ec_key)
    211         return nullptr;
    212 
    213     keymaster_key_blob_t* blob_copy = duplicate_blob(blob);
    214     if (!blob_copy->key_material || !EC_KEY_set_ex_data(ec_key.get(), ec_key_index_, blob_copy))
    215         return nullptr;
    216 
    217     // Copy public key into new EC key
    218     unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(GetKeymaster0PublicKey(blob));
    219     if (!pkey)
    220         return nullptr;
    221 
    222     unique_ptr<EC_KEY, EC_Delete> public_ec_key(EVP_PKEY_get1_EC_KEY(pkey.get()));
    223     if (!public_ec_key)
    224         return nullptr;
    225 
    226     if (!EC_KEY_set_group(ec_key.get(), EC_KEY_get0_group(public_ec_key.get())) ||
    227         !EC_KEY_set_public_key(ec_key.get(), EC_KEY_get0_public_key(public_ec_key.get())))
    228         return nullptr;
    229 
    230     return ec_key.release();
    231 }
    232 
    233 const keymaster_key_blob_t* Keymaster0Engine::RsaKeyToBlob(const RSA* rsa) const {
    234     return reinterpret_cast<keymaster_key_blob_t*>(RSA_get_ex_data(rsa, rsa_index_));
    235 }
    236 
    237 const keymaster_key_blob_t* Keymaster0Engine::EcKeyToBlob(const EC_KEY* ec_key) const {
    238     return reinterpret_cast<keymaster_key_blob_t*>(EC_KEY_get_ex_data(ec_key, ec_key_index_));
    239 }
    240 
    241 /* static */
    242 int Keymaster0Engine::keyblob_dup(CRYPTO_EX_DATA* /* to */, const CRYPTO_EX_DATA* /* from */,
    243                                   void** from_d, int /* index */, long /* argl */,
    244                                   void* /* argp */) {
    245     keymaster_key_blob_t* blob = reinterpret_cast<keymaster_key_blob_t*>(*from_d);
    246     if (!blob)
    247         return 1;
    248     *from_d = duplicate_blob(*blob);
    249     if (*from_d)
    250         return 1;
    251     return 0;
    252 }
    253 
    254 /* static */
    255 void Keymaster0Engine::keyblob_free(void* /* parent */, void* ptr, CRYPTO_EX_DATA* /* data */,
    256                                     int /* index*/, long /* argl */, void* /* argp */) {
    257     keymaster_key_blob_t* blob = reinterpret_cast<keymaster_key_blob_t*>(ptr);
    258     if (blob) {
    259         delete[] blob->key_material;
    260         delete blob;
    261     }
    262 }
    263 
    264 /* static */
    265 int Keymaster0Engine::rsa_private_transform(RSA* rsa, uint8_t* out, const uint8_t* in, size_t len) {
    266     ALOGV("rsa_private_transform(%p, %p, %p, %u)", rsa, out, in, (unsigned)len);
    267 
    268     assert(instance_);
    269     return instance_->RsaPrivateTransform(rsa, out, in, len);
    270 }
    271 
    272 /* static */
    273 int Keymaster0Engine::ecdsa_sign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
    274                                  unsigned int* sig_len, EC_KEY* ec_key) {
    275     ALOGV("ecdsa_sign(%p, %u, %p)", digest, (unsigned)digest_len, ec_key);
    276     assert(instance_);
    277     return instance_->EcdsaSign(digest, digest_len, sig, sig_len, ec_key);
    278 }
    279 
    280 bool Keymaster0Engine::Keymaster0Sign(const void* signing_params, const keymaster_key_blob_t& blob,
    281                                       const uint8_t* data, const size_t data_length,
    282                                       unique_ptr<uint8_t[], Malloc_Delete>* signature,
    283                                       size_t* signature_length) const {
    284     uint8_t* signed_data;
    285     int err = keymaster0_device_->sign_data(keymaster0_device_, signing_params, blob.key_material,
    286                                             blob.key_material_size, data, data_length, &signed_data,
    287                                             signature_length);
    288     if (err < 0) {
    289         ALOGE("Keymaster0 signing failed with error %d", err);
    290         return false;
    291     }
    292 
    293     signature->reset(signed_data);
    294     return true;
    295 }
    296 
    297 EVP_PKEY* Keymaster0Engine::GetKeymaster0PublicKey(const KeymasterKeyBlob& blob) const {
    298     uint8_t* pub_key_data;
    299     size_t pub_key_data_length;
    300     int err = keymaster0_device_->get_keypair_public(keymaster0_device_, blob.key_material,
    301                                                      blob.key_material_size, &pub_key_data,
    302                                                      &pub_key_data_length);
    303     if (err < 0) {
    304         ALOGE("Error %d extracting public key", err);
    305         return nullptr;
    306     }
    307     unique_ptr<uint8_t, Malloc_Delete> pub_key(pub_key_data);
    308 
    309     const uint8_t* p = pub_key_data;
    310     return d2i_PUBKEY(nullptr /* allocate new struct */, &p, pub_key_data_length);
    311 }
    312 
    313 int Keymaster0Engine::RsaPrivateTransform(RSA* rsa, uint8_t* out, const uint8_t* in,
    314                                           size_t len) const {
    315     const keymaster_key_blob_t* key_blob = RsaKeyToBlob(rsa);
    316     if (key_blob == NULL) {
    317         ALOGE("key had no key_blob!");
    318         return 0;
    319     }
    320 
    321     keymaster_rsa_sign_params_t sign_params = {DIGEST_NONE, PADDING_NONE};
    322     unique_ptr<uint8_t[], Malloc_Delete> signature;
    323     size_t signature_length;
    324     if (!Keymaster0Sign(&sign_params, *key_blob, in, len, &signature, &signature_length))
    325         return 0;
    326     Eraser eraser(signature.get(), signature_length);
    327 
    328     if (signature_length > len) {
    329         /* The result of the RSA operation can never be larger than the size of
    330          * the modulus so we assume that the result has extra zeros on the
    331          * left. This provides attackers with an oracle, but there's nothing
    332          * that we can do about it here. */
    333         memcpy(out, signature.get() + signature_length - len, len);
    334     } else if (signature_length < len) {
    335         /* If the keymaster0 implementation returns a short value we assume that
    336          * it's because it removed leading zeros from the left side. This is
    337          * bad because it provides attackers with an oracle but we cannot do
    338          * anything about a broken keymaster0 implementation here. */
    339         memset(out, 0, len);
    340         memcpy(out + len - signature_length, signature.get(), signature_length);
    341     } else {
    342         memcpy(out, signature.get(), len);
    343     }
    344 
    345     ALOGV("rsa=%p keystore_rsa_priv_dec successful", rsa);
    346     return 1;
    347 }
    348 
    349 static size_t ec_group_size_bits(EC_KEY* ec_key) {
    350     const EC_GROUP* group = EC_KEY_get0_group(ec_key);
    351     unique_ptr<BN_CTX, BN_CTX_Delete> bn_ctx(BN_CTX_new());
    352     unique_ptr<BIGNUM, BIGNUM_Delete> order(BN_new());
    353     if (!EC_GROUP_get_order(group, order.get(), bn_ctx.get())) {
    354         ALOGE("Failed to get EC group order");
    355         return 0;
    356     }
    357     return BN_num_bits(order.get());
    358 }
    359 
    360 int Keymaster0Engine::EcdsaSign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
    361                                 unsigned int* sig_len, EC_KEY* ec_key) const {
    362     const keymaster_key_blob_t* key_blob = EcKeyToBlob(ec_key);
    363     if (key_blob == NULL) {
    364         ALOGE("key had no key_blob!");
    365         return 0;
    366     }
    367 
    368     // Truncate digest if it's too long
    369     size_t max_input_len = (ec_group_size_bits(ec_key) + 7) / 8;
    370     if (digest_len > max_input_len)
    371         digest_len = max_input_len;
    372 
    373     keymaster_ec_sign_params_t sign_params = {DIGEST_NONE};
    374     unique_ptr<uint8_t[], Malloc_Delete> signature;
    375     size_t signature_length;
    376     if (!Keymaster0Sign(&sign_params, *key_blob, digest, digest_len, &signature, &signature_length))
    377         return 0;
    378     Eraser eraser(signature.get(), signature_length);
    379 
    380     if (signature_length == 0) {
    381         ALOGW("No valid signature returned");
    382         return 0;
    383     } else if (signature_length > ECDSA_size(ec_key)) {
    384         ALOGW("Signature is too large");
    385         return 0;
    386     } else {
    387         memcpy(sig, signature.get(), signature_length);
    388         *sig_len = signature_length;
    389     }
    390 
    391     ALOGV("ecdsa_sign(%p, %u, %p) => success", digest, (unsigned)digest_len, ec_key);
    392     return 1;
    393 }
    394 
    395 }  // namespace keymaster
    396