Home | History | Annotate | Download | only in keystore-engine
      1 /* Copyright 2014 The Android Open Source Project
      2  *
      3  * Redistribution and use in source and binary forms, with or without
      4  * modification, are permitted provided that the following conditions
      5  * are met:
      6  * 1. Redistributions of source code must retain the above copyright
      7  *    notice, this list of conditions and the following disclaimer.
      8  * 2. Redistributions in binary form must reproduce the above copyright
      9  *    notice, this list of conditions and the following disclaimer in the
     10  *    documentation and/or other materials provided with the distribution.
     11  *
     12  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
     13  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     14  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     15  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
     16  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
     17  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     18  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
     19  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     20  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     21  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
     22 
     23 #include <UniquePtr.h>
     24 
     25 #include <sys/socket.h>
     26 #include <stdarg.h>
     27 #include <string.h>
     28 #include <unistd.h>
     29 
     30 #include <openssl/bn.h>
     31 #include <openssl/ec.h>
     32 #include <openssl/ec_key.h>
     33 #include <openssl/ecdsa.h>
     34 #include <openssl/engine.h>
     35 #include <openssl/evp.h>
     36 #include <openssl/rsa.h>
     37 #include <openssl/x509.h>
     38 
     39 #include <binder/IServiceManager.h>
     40 #include <keystore/keystore.h>
     41 #include <keystore/IKeystoreService.h>
     42 
     43 using namespace android;
     44 
     45 namespace {
     46 
     47 extern const RSA_METHOD keystore_rsa_method;
     48 extern const ECDSA_METHOD keystore_ecdsa_method;
     49 
     50 /* key_id_dup is called when one of the RSA or EC_KEY objects is duplicated. */
     51 int key_id_dup(CRYPTO_EX_DATA* /* to */,
     52                const CRYPTO_EX_DATA* /* from */,
     53                void** from_d,
     54                int /* index */,
     55                long /* argl */,
     56                void* /* argp */) {
     57     char *key_id = reinterpret_cast<char *>(*from_d);
     58     if (key_id != NULL) {
     59         *from_d = strdup(key_id);
     60     }
     61     return 1;
     62 }
     63 
     64 /* key_id_free is called when one of the RSA, DSA or EC_KEY object is freed. */
     65 void key_id_free(void* /* parent */,
     66                  void* ptr,
     67                  CRYPTO_EX_DATA* /* ad */,
     68                  int /* index */,
     69                  long /* argl */,
     70                  void* /* argp */) {
     71     char *key_id = reinterpret_cast<char *>(ptr);
     72     free(key_id);
     73 }
     74 
     75 /* KeystoreEngine is a BoringSSL ENGINE that implements RSA and ECDSA by
     76  * forwarding the requested operations to Keystore. */
     77 class KeystoreEngine {
     78  public:
     79   KeystoreEngine()
     80       : rsa_index_(RSA_get_ex_new_index(0 /* argl */,
     81                                         NULL /* argp */,
     82                                         NULL /* new_func */,
     83                                         key_id_dup,
     84                                         key_id_free)),
     85         ec_key_index_(EC_KEY_get_ex_new_index(0 /* argl */,
     86                                               NULL /* argp */,
     87                                               NULL /* new_func */,
     88                                               key_id_dup,
     89                                               key_id_free)),
     90         engine_(ENGINE_new()) {
     91     ENGINE_set_RSA_method(
     92         engine_, &keystore_rsa_method, sizeof(keystore_rsa_method));
     93     ENGINE_set_ECDSA_method(
     94         engine_, &keystore_ecdsa_method, sizeof(keystore_ecdsa_method));
     95   }
     96 
     97   int rsa_ex_index() const { return rsa_index_; }
     98   int ec_key_ex_index() const { return ec_key_index_; }
     99 
    100   const ENGINE* engine() const { return engine_; }
    101 
    102  private:
    103   const int rsa_index_;
    104   const int ec_key_index_;
    105   ENGINE* const engine_;
    106 };
    107 
    108 pthread_once_t g_keystore_engine_once = PTHREAD_ONCE_INIT;
    109 KeystoreEngine *g_keystore_engine;
    110 
    111 /* init_keystore_engine is called to initialize |g_keystore_engine|. This
    112  * should only be called by |pthread_once|. */
    113 void init_keystore_engine() {
    114     g_keystore_engine = new KeystoreEngine;
    115 }
    116 
    117 /* ensure_keystore_engine ensures that |g_keystore_engine| is pointing to a
    118  * valid |KeystoreEngine| object and creates one if not. */
    119 void ensure_keystore_engine() {
    120     pthread_once(&g_keystore_engine_once, init_keystore_engine);
    121 }
    122 
    123 /* Many OpenSSL APIs take ownership of an argument on success but don't free
    124  * the argument on failure. This means we need to tell our scoped pointers when
    125  * we've transferred ownership, without triggering a warning by not using the
    126  * result of release(). */
    127 #define OWNERSHIP_TRANSFERRED(obj) \
    128     typeof (obj.release()) _dummy __attribute__((unused)) = obj.release()
    129 
    130 const char* rsa_get_key_id(const RSA* rsa) {
    131   return reinterpret_cast<char*>(
    132       RSA_get_ex_data(rsa, g_keystore_engine->rsa_ex_index()));
    133 }
    134 
    135 /* rsa_private_transform takes a big-endian integer from |in|, calculates the
    136  * d'th power of it, modulo the RSA modulus, and writes the result as a
    137  * big-endian integer to |out|. Both |in| and |out| are |len| bytes long. It
    138  * returns one on success and zero otherwise. */
    139 int rsa_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in, size_t len) {
    140     ALOGV("rsa_private_transform(%p, %p, %p, %u)", rsa, out, in, (unsigned) len);
    141 
    142     const char *key_id = rsa_get_key_id(rsa);
    143     if (key_id == NULL) {
    144         ALOGE("key had no key_id!");
    145         return 0;
    146     }
    147 
    148     sp<IServiceManager> sm = defaultServiceManager();
    149     sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
    150     sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
    151 
    152     if (service == NULL) {
    153         ALOGE("could not contact keystore");
    154         return 0;
    155     }
    156 
    157     uint8_t* reply = NULL;
    158     size_t reply_len;
    159     int32_t ret = service->sign(String16(key_id), in, len, &reply, &reply_len);
    160     if (ret < 0) {
    161         ALOGW("There was an error during rsa_decrypt: could not connect");
    162         return 0;
    163     } else if (ret != 0) {
    164         ALOGW("Error during sign from keystore: %d", ret);
    165         return 0;
    166     } else if (reply_len == 0) {
    167         ALOGW("No valid signature returned");
    168         free(reply);
    169         return 0;
    170     }
    171 
    172     if (reply_len > len) {
    173         /* The result of the RSA operation can never be larger than the size of
    174          * the modulus so we assume that the result has extra zeros on the
    175          * left. This provides attackers with an oracle, but there's nothing
    176          * that we can do about it here. */
    177         memcpy(out, reply + reply_len - len, len);
    178     } else if (reply_len < len) {
    179         /* If the Keystore implementation returns a short value we assume that
    180          * it's because it removed leading zeros from the left side. This is
    181          * bad because it provides attackers with an oracle but we cannot do
    182          * anything about a broken Keystore implementation here. */
    183         memset(out, 0, len);
    184         memcpy(out + len - reply_len, reply, reply_len);
    185     } else {
    186         memcpy(out, reply, len);
    187     }
    188 
    189     free(reply);
    190 
    191     ALOGV("rsa=%p keystore_rsa_priv_dec successful", rsa);
    192     return 1;
    193 }
    194 
    195 const struct rsa_meth_st keystore_rsa_method = {
    196   {
    197     0 /* references */,
    198     1 /* is_static */,
    199   },
    200   NULL /* app_data */,
    201 
    202   NULL /* init */,
    203   NULL /* finish */,
    204 
    205   NULL /* size */,
    206 
    207   NULL /* sign */,
    208   NULL /* verify */,
    209 
    210   NULL /* encrypt */,
    211   NULL /* sign_raw */,
    212   NULL /* decrypt */,
    213   NULL /* verify_raw */,
    214 
    215   rsa_private_transform,
    216 
    217   NULL /* mod_exp */,
    218   NULL /* bn_mod_exp */,
    219 
    220   RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_OPAQUE | RSA_FLAG_EXT_PKEY,
    221 
    222   NULL /* keygen */,
    223   NULL /* supports_digest */,
    224 };
    225 
    226 const char* ecdsa_get_key_id(const EC_KEY* ec_key) {
    227     return reinterpret_cast<char*>(
    228         EC_KEY_get_ex_data(ec_key, g_keystore_engine->ec_key_ex_index()));
    229 }
    230 
    231 /* ecdsa_sign signs |digest_len| bytes from |digest| with |ec_key| and writes
    232  * the resulting signature (an ASN.1 encoded blob) to |sig|. It returns one on
    233  * success and zero otherwise. */
    234 static int ecdsa_sign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
    235                       unsigned int* sig_len, EC_KEY* ec_key) {
    236     ALOGV("ecdsa_sign(%p, %u, %p)", digest, (unsigned) digest_len, ec_key);
    237 
    238     const char *key_id = ecdsa_get_key_id(ec_key);
    239     if (key_id == NULL) {
    240         ALOGE("key had no key_id!");
    241         return 0;
    242     }
    243 
    244     sp<IServiceManager> sm = defaultServiceManager();
    245     sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
    246     sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
    247 
    248     if (service == NULL) {
    249         ALOGE("could not contact keystore");
    250         return 0;
    251     }
    252 
    253     size_t ecdsa_size = ECDSA_size(ec_key);
    254 
    255     uint8_t* reply = NULL;
    256     size_t reply_len;
    257     int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)),
    258                                 digest, digest_len, &reply, &reply_len);
    259     if (ret < 0) {
    260         ALOGW("There was an error during ecdsa_sign: could not connect");
    261         return 0;
    262     } else if (ret != 0) {
    263         ALOGW("Error during sign from keystore: %d", ret);
    264         return 0;
    265     } else if (reply_len == 0) {
    266         ALOGW("No valid signature returned");
    267         free(reply);
    268         return 0;
    269     } else if (reply_len > ecdsa_size) {
    270         ALOGW("Signature is too large");
    271         free(reply);
    272         return 0;
    273     }
    274 
    275     memcpy(sig, reply, reply_len);
    276     *sig_len = reply_len;
    277 
    278     ALOGV("ecdsa_sign(%p, %u, %p) => success", digest, (unsigned)digest_len,
    279           ec_key);
    280     return 1;
    281 }
    282 
    283 const ECDSA_METHOD keystore_ecdsa_method = {
    284     {
    285      0 /* references */,
    286      1 /* is_static */
    287     } /* common */,
    288     NULL /* app_data */,
    289 
    290     NULL /* init */,
    291     NULL /* finish */,
    292     NULL /* group_order_size */,
    293     ecdsa_sign,
    294     NULL /* verify */,
    295     ECDSA_FLAG_OPAQUE,
    296 };
    297 
    298 struct EVP_PKEY_Delete {
    299     void operator()(EVP_PKEY* p) const {
    300         EVP_PKEY_free(p);
    301     }
    302 };
    303 typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
    304 
    305 struct RSA_Delete {
    306     void operator()(RSA* p) const {
    307         RSA_free(p);
    308     }
    309 };
    310 typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
    311 
    312 struct EC_KEY_Delete {
    313     void operator()(EC_KEY* ec) const {
    314         EC_KEY_free(ec);
    315     }
    316 };
    317 typedef UniquePtr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY;
    318 
    319 /* wrap_rsa returns an |EVP_PKEY| that contains an RSA key where the public
    320  * part is taken from |public_rsa| and the private operations are forwarded to
    321  * KeyStore and operate on the key named |key_id|. */
    322 static EVP_PKEY *wrap_rsa(const char *key_id, const RSA *public_rsa) {
    323     Unique_RSA rsa(RSA_new_method(g_keystore_engine->engine()));
    324     if (rsa.get() == NULL) {
    325         return NULL;
    326     }
    327 
    328     char *key_id_copy = strdup(key_id);
    329     if (key_id_copy == NULL) {
    330         return NULL;
    331     }
    332 
    333     if (!RSA_set_ex_data(rsa.get(), g_keystore_engine->rsa_ex_index(),
    334                          key_id_copy)) {
    335         free(key_id_copy);
    336         return NULL;
    337     }
    338 
    339     rsa->n = BN_dup(public_rsa->n);
    340     rsa->e = BN_dup(public_rsa->e);
    341     if (rsa->n == NULL || rsa->e == NULL) {
    342         return NULL;
    343     }
    344 
    345     Unique_EVP_PKEY result(EVP_PKEY_new());
    346     if (result.get() == NULL ||
    347         !EVP_PKEY_assign_RSA(result.get(), rsa.get())) {
    348         return NULL;
    349     }
    350     OWNERSHIP_TRANSFERRED(rsa);
    351 
    352     return result.release();
    353 }
    354 
    355 /* wrap_ecdsa returns an |EVP_PKEY| that contains an ECDSA key where the public
    356  * part is taken from |public_rsa| and the private operations are forwarded to
    357  * KeyStore and operate on the key named |key_id|. */
    358 static EVP_PKEY *wrap_ecdsa(const char *key_id, const EC_KEY *public_ecdsa) {
    359     Unique_EC_KEY ec(EC_KEY_new_method(g_keystore_engine->engine()));
    360     if (ec.get() == NULL) {
    361         return NULL;
    362     }
    363 
    364     if (!EC_KEY_set_group(ec.get(), EC_KEY_get0_group(public_ecdsa)) ||
    365         !EC_KEY_set_public_key(ec.get(), EC_KEY_get0_public_key(public_ecdsa))) {
    366         return NULL;
    367     }
    368 
    369     char *key_id_copy = strdup(key_id);
    370     if (key_id_copy == NULL) {
    371         return NULL;
    372     }
    373 
    374     if (!EC_KEY_set_ex_data(ec.get(), g_keystore_engine->ec_key_ex_index(),
    375                             key_id_copy)) {
    376         free(key_id_copy);
    377         return NULL;
    378     }
    379 
    380     Unique_EVP_PKEY result(EVP_PKEY_new());
    381     if (result.get() == NULL ||
    382         !EVP_PKEY_assign_EC_KEY(result.get(), ec.get())) {
    383         return NULL;
    384     }
    385     OWNERSHIP_TRANSFERRED(ec);
    386 
    387     return result.release();
    388 }
    389 
    390 }  /* anonymous namespace */
    391 
    392 extern "C" {
    393 
    394 EVP_PKEY* EVP_PKEY_from_keystore(const char* key_id) __attribute__((visibility("default")));
    395 
    396 /* EVP_PKEY_from_keystore returns an |EVP_PKEY| that contains either an RSA or
    397  * ECDSA key where the public part of the key reflects the value of the key
    398  * named |key_id| in Keystore and the private operations are forwarded onto
    399  * KeyStore. */
    400 EVP_PKEY* EVP_PKEY_from_keystore(const char* key_id) {
    401     ALOGV("EVP_PKEY_from_keystore(\"%s\")", key_id);
    402 
    403     sp<IServiceManager> sm = defaultServiceManager();
    404     sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
    405     sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
    406 
    407     if (service == NULL) {
    408         ALOGE("could not contact keystore");
    409         return 0;
    410     }
    411 
    412     uint8_t *pubkey = NULL;
    413     size_t pubkey_len;
    414     int32_t ret = service->get_pubkey(String16(key_id), &pubkey, &pubkey_len);
    415     if (ret < 0) {
    416         ALOGW("could not contact keystore");
    417         return NULL;
    418     } else if (ret != 0) {
    419         ALOGW("keystore reports error: %d", ret);
    420         return NULL;
    421     }
    422 
    423     const uint8_t *inp = pubkey;
    424     Unique_EVP_PKEY pkey(d2i_PUBKEY(NULL, &inp, pubkey_len));
    425     free(pubkey);
    426     if (pkey.get() == NULL) {
    427         ALOGW("Cannot convert pubkey");
    428         return NULL;
    429     }
    430 
    431     ensure_keystore_engine();
    432 
    433     EVP_PKEY *result;
    434     switch (EVP_PKEY_type(pkey->type)) {
    435     case EVP_PKEY_RSA: {
    436         Unique_RSA public_rsa(EVP_PKEY_get1_RSA(pkey.get()));
    437         result = wrap_rsa(key_id, public_rsa.get());
    438         break;
    439     }
    440     case EVP_PKEY_EC: {
    441         Unique_EC_KEY public_ecdsa(EVP_PKEY_get1_EC_KEY(pkey.get()));
    442         result = wrap_ecdsa(key_id, public_ecdsa.get());
    443         break;
    444     }
    445     default:
    446         ALOGE("Unsupported key type %d", EVP_PKEY_type(pkey->type));
    447         result = NULL;
    448     }
    449 
    450     return result;
    451 }
    452 
    453 }  // extern "C"
    454