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