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