• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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. */
key_id_dup(CRYPTO_EX_DATA *,const CRYPTO_EX_DATA *,void ** from_d,int,long,void *)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. */
key_id_free(void *,void * ptr,CRYPTO_EX_DATA *,int,long,void *)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:
KeystoreEngine()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 
rsa_ex_index() const97   int rsa_ex_index() const { return rsa_index_; }
ec_key_ex_index() const98   int ec_key_ex_index() const { return ec_key_index_; }
99 
engine() const100   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|. */
init_keystore_engine()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. */
ensure_keystore_engine()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 
rsa_get_key_id(const RSA * rsa)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. */
rsa_private_transform(RSA * rsa,uint8_t * out,const uint8_t * in,size_t len)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 /* multi_prime_keygen */,
224   NULL /* supports_digest */,
225 };
226 
ecdsa_get_key_id(const EC_KEY * ec_key)227 const char* ecdsa_get_key_id(const EC_KEY* ec_key) {
228     return reinterpret_cast<char*>(
229         EC_KEY_get_ex_data(ec_key, g_keystore_engine->ec_key_ex_index()));
230 }
231 
232 /* ecdsa_sign signs |digest_len| bytes from |digest| with |ec_key| and writes
233  * the resulting signature (an ASN.1 encoded blob) to |sig|. It returns one on
234  * success and zero otherwise. */
ecdsa_sign(const uint8_t * digest,size_t digest_len,uint8_t * sig,unsigned int * sig_len,EC_KEY * ec_key)235 static int ecdsa_sign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
236                       unsigned int* sig_len, EC_KEY* ec_key) {
237     ALOGV("ecdsa_sign(%p, %u, %p)", digest, (unsigned) digest_len, ec_key);
238 
239     const char *key_id = ecdsa_get_key_id(ec_key);
240     if (key_id == NULL) {
241         ALOGE("key had no key_id!");
242         return 0;
243     }
244 
245     sp<IServiceManager> sm = defaultServiceManager();
246     sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
247     sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
248 
249     if (service == NULL) {
250         ALOGE("could not contact keystore");
251         return 0;
252     }
253 
254     size_t ecdsa_size = ECDSA_size(ec_key);
255 
256     uint8_t* reply = NULL;
257     size_t reply_len;
258     int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)),
259                                 digest, digest_len, &reply, &reply_len);
260     if (ret < 0) {
261         ALOGW("There was an error during ecdsa_sign: could not connect");
262         return 0;
263     } else if (ret != 0) {
264         ALOGW("Error during sign from keystore: %d", ret);
265         return 0;
266     } else if (reply_len == 0) {
267         ALOGW("No valid signature returned");
268         free(reply);
269         return 0;
270     } else if (reply_len > ecdsa_size) {
271         ALOGW("Signature is too large");
272         free(reply);
273         return 0;
274     }
275 
276     memcpy(sig, reply, reply_len);
277     *sig_len = reply_len;
278 
279     ALOGV("ecdsa_sign(%p, %u, %p) => success", digest, (unsigned)digest_len,
280           ec_key);
281     return 1;
282 }
283 
284 const ECDSA_METHOD keystore_ecdsa_method = {
285     {
286      0 /* references */,
287      1 /* is_static */
288     } /* common */,
289     NULL /* app_data */,
290 
291     NULL /* init */,
292     NULL /* finish */,
293     NULL /* group_order_size */,
294     ecdsa_sign,
295     NULL /* verify */,
296     ECDSA_FLAG_OPAQUE,
297 };
298 
299 struct EVP_PKEY_Delete {
operator ()__anonaa278e8e0111::EVP_PKEY_Delete300     void operator()(EVP_PKEY* p) const {
301         EVP_PKEY_free(p);
302     }
303 };
304 typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
305 
306 struct RSA_Delete {
operator ()__anonaa278e8e0111::RSA_Delete307     void operator()(RSA* p) const {
308         RSA_free(p);
309     }
310 };
311 typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
312 
313 struct EC_KEY_Delete {
operator ()__anonaa278e8e0111::EC_KEY_Delete314     void operator()(EC_KEY* ec) const {
315         EC_KEY_free(ec);
316     }
317 };
318 typedef UniquePtr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY;
319 
320 /* wrap_rsa returns an |EVP_PKEY| that contains an RSA key where the public
321  * part is taken from |public_rsa| and the private operations are forwarded to
322  * KeyStore and operate on the key named |key_id|. */
wrap_rsa(const char * key_id,const RSA * public_rsa)323 static EVP_PKEY *wrap_rsa(const char *key_id, const RSA *public_rsa) {
324     Unique_RSA rsa(RSA_new_method(g_keystore_engine->engine()));
325     if (rsa.get() == NULL) {
326         return NULL;
327     }
328 
329     char *key_id_copy = strdup(key_id);
330     if (key_id_copy == NULL) {
331         return NULL;
332     }
333 
334     if (!RSA_set_ex_data(rsa.get(), g_keystore_engine->rsa_ex_index(),
335                          key_id_copy)) {
336         free(key_id_copy);
337         return NULL;
338     }
339 
340     rsa->n = BN_dup(public_rsa->n);
341     rsa->e = BN_dup(public_rsa->e);
342     if (rsa->n == NULL || rsa->e == NULL) {
343         return NULL;
344     }
345 
346     Unique_EVP_PKEY result(EVP_PKEY_new());
347     if (result.get() == NULL ||
348         !EVP_PKEY_assign_RSA(result.get(), rsa.get())) {
349         return NULL;
350     }
351     OWNERSHIP_TRANSFERRED(rsa);
352 
353     return result.release();
354 }
355 
356 /* wrap_ecdsa returns an |EVP_PKEY| that contains an ECDSA key where the public
357  * part is taken from |public_rsa| and the private operations are forwarded to
358  * KeyStore and operate on the key named |key_id|. */
wrap_ecdsa(const char * key_id,const EC_KEY * public_ecdsa)359 static EVP_PKEY *wrap_ecdsa(const char *key_id, const EC_KEY *public_ecdsa) {
360     Unique_EC_KEY ec(EC_KEY_new_method(g_keystore_engine->engine()));
361     if (ec.get() == NULL) {
362         return NULL;
363     }
364 
365     if (!EC_KEY_set_group(ec.get(), EC_KEY_get0_group(public_ecdsa)) ||
366         !EC_KEY_set_public_key(ec.get(), EC_KEY_get0_public_key(public_ecdsa))) {
367         return NULL;
368     }
369 
370     char *key_id_copy = strdup(key_id);
371     if (key_id_copy == NULL) {
372         return NULL;
373     }
374 
375     if (!EC_KEY_set_ex_data(ec.get(), g_keystore_engine->ec_key_ex_index(),
376                             key_id_copy)) {
377         free(key_id_copy);
378         return NULL;
379     }
380 
381     Unique_EVP_PKEY result(EVP_PKEY_new());
382     if (result.get() == NULL ||
383         !EVP_PKEY_assign_EC_KEY(result.get(), ec.get())) {
384         return NULL;
385     }
386     OWNERSHIP_TRANSFERRED(ec);
387 
388     return result.release();
389 }
390 
391 }  /* anonymous namespace */
392 
393 extern "C" {
394 
395 EVP_PKEY* EVP_PKEY_from_keystore(const char* key_id) __attribute__((visibility("default")));
396 
397 /* EVP_PKEY_from_keystore returns an |EVP_PKEY| that contains either an RSA or
398  * ECDSA key where the public part of the key reflects the value of the key
399  * named |key_id| in Keystore and the private operations are forwarded onto
400  * KeyStore. */
EVP_PKEY_from_keystore(const char * key_id)401 EVP_PKEY* EVP_PKEY_from_keystore(const char* key_id) {
402     ALOGV("EVP_PKEY_from_keystore(\"%s\")", key_id);
403 
404     sp<IServiceManager> sm = defaultServiceManager();
405     sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
406     sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
407 
408     if (service == NULL) {
409         ALOGE("could not contact keystore");
410         return 0;
411     }
412 
413     uint8_t *pubkey = NULL;
414     size_t pubkey_len;
415     int32_t ret = service->get_pubkey(String16(key_id), &pubkey, &pubkey_len);
416     if (ret < 0) {
417         ALOGW("could not contact keystore");
418         return NULL;
419     } else if (ret != 0) {
420         ALOGW("keystore reports error: %d", ret);
421         return NULL;
422     }
423 
424     const uint8_t *inp = pubkey;
425     Unique_EVP_PKEY pkey(d2i_PUBKEY(NULL, &inp, pubkey_len));
426     free(pubkey);
427     if (pkey.get() == NULL) {
428         ALOGW("Cannot convert pubkey");
429         return NULL;
430     }
431 
432     ensure_keystore_engine();
433 
434     EVP_PKEY *result;
435     switch (EVP_PKEY_type(pkey->type)) {
436     case EVP_PKEY_RSA: {
437         Unique_RSA public_rsa(EVP_PKEY_get1_RSA(pkey.get()));
438         result = wrap_rsa(key_id, public_rsa.get());
439         break;
440     }
441     case EVP_PKEY_EC: {
442         Unique_EC_KEY public_ecdsa(EVP_PKEY_get1_EC_KEY(pkey.get()));
443         result = wrap_ecdsa(key_id, public_ecdsa.get());
444         break;
445     }
446     default:
447         ALOGE("Unsupported key type %d", EVP_PKEY_type(pkey->type));
448         result = NULL;
449     }
450 
451     return result;
452 }
453 
454 }  // extern "C"
455