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 #define LOG_TAG "keystore-engine"
24 #include <UniquePtr.h>
25
26 #include <pthread.h>
27 #include <sys/socket.h>
28 #include <stdarg.h>
29 #include <string.h>
30 #include <unistd.h>
31
32 #include <cutils/log.h>
33
34 #include <openssl/bn.h>
35 #include <openssl/ec.h>
36 #include <openssl/ec_key.h>
37 #include <openssl/ecdsa.h>
38 #include <openssl/engine.h>
39 #include <openssl/evp.h>
40 #include <openssl/rsa.h>
41 #include <openssl/x509.h>
42
43 #ifndef BACKEND_WIFI_HIDL
44 #include "keystore_backend_binder.h"
45 #else
46 #include "keystore_backend_hidl.h"
47 #endif
48
49 namespace {
50 extern const RSA_METHOD keystore_rsa_method;
51 extern const ECDSA_METHOD keystore_ecdsa_method;
52
53 /* 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 *)54 int key_id_dup(CRYPTO_EX_DATA* /* to */,
55 const CRYPTO_EX_DATA* /* from */,
56 void** from_d,
57 int /* index */,
58 long /* argl */,
59 void* /* argp */) {
60 char *key_id = reinterpret_cast<char *>(*from_d);
61 if (key_id != NULL) {
62 *from_d = strdup(key_id);
63 }
64 return 1;
65 }
66
67 /* 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 *)68 void key_id_free(void* /* parent */,
69 void* ptr,
70 CRYPTO_EX_DATA* /* ad */,
71 int /* index */,
72 long /* argl */,
73 void* /* argp */) {
74 char *key_id = reinterpret_cast<char *>(ptr);
75 free(key_id);
76 }
77
78 /* KeystoreEngine is a BoringSSL ENGINE that implements RSA and ECDSA by
79 * forwarding the requested operations to Keystore. */
80 class KeystoreEngine {
81 public:
KeystoreEngine()82 KeystoreEngine()
83 : rsa_index_(RSA_get_ex_new_index(0 /* argl */,
84 NULL /* argp */,
85 NULL /* new_func */,
86 key_id_dup,
87 key_id_free)),
88 ec_key_index_(EC_KEY_get_ex_new_index(0 /* argl */,
89 NULL /* argp */,
90 NULL /* new_func */,
91 key_id_dup,
92 key_id_free)),
93 engine_(ENGINE_new()) {
94 ENGINE_set_RSA_method(
95 engine_, &keystore_rsa_method, sizeof(keystore_rsa_method));
96 ENGINE_set_ECDSA_method(
97 engine_, &keystore_ecdsa_method, sizeof(keystore_ecdsa_method));
98 }
99
rsa_ex_index() const100 int rsa_ex_index() const { return rsa_index_; }
ec_key_ex_index() const101 int ec_key_ex_index() const { return ec_key_index_; }
102
engine() const103 const ENGINE* engine() const { return engine_; }
104
105 private:
106 const int rsa_index_;
107 const int ec_key_index_;
108 ENGINE* const engine_;
109 };
110
111 pthread_once_t g_keystore_engine_once = PTHREAD_ONCE_INIT;
112 KeystoreEngine *g_keystore_engine;
113 KeystoreBackend *g_keystore_backend;
114
115 /* init_keystore_engine is called to initialize |g_keystore_engine|. This
116 * should only be called by |pthread_once|. */
init_keystore_engine()117 void init_keystore_engine() {
118 g_keystore_engine = new KeystoreEngine;
119 #ifndef BACKEND_WIFI_HIDL
120 g_keystore_backend = new KeystoreBackendBinder;
121 #else
122 g_keystore_backend = new KeystoreBackendHidl;
123 #endif
124 }
125
126 /* ensure_keystore_engine ensures that |g_keystore_engine| is pointing to a
127 * valid |KeystoreEngine| object and creates one if not. */
ensure_keystore_engine()128 void ensure_keystore_engine() {
129 pthread_once(&g_keystore_engine_once, init_keystore_engine);
130 }
131
132 /* Many OpenSSL APIs take ownership of an argument on success but don't free
133 * the argument on failure. This means we need to tell our scoped pointers when
134 * we've transferred ownership, without triggering a warning by not using the
135 * result of release(). */
136 #define OWNERSHIP_TRANSFERRED(obj) \
137 typeof ((obj).release()) _dummy __attribute__((unused)) = (obj).release()
138
rsa_get_key_id(const RSA * rsa)139 const char* rsa_get_key_id(const RSA* rsa) {
140 return reinterpret_cast<char*>(
141 RSA_get_ex_data(rsa, g_keystore_engine->rsa_ex_index()));
142 }
143
144 /* rsa_private_transform takes a big-endian integer from |in|, calculates the
145 * d'th power of it, modulo the RSA modulus, and writes the result as a
146 * big-endian integer to |out|. Both |in| and |out| are |len| bytes long. It
147 * returns one on success and zero otherwise. */
rsa_private_transform(RSA * rsa,uint8_t * out,const uint8_t * in,size_t len)148 int rsa_private_transform(RSA *rsa, uint8_t *out, const uint8_t *in, size_t len) {
149 ALOGV("rsa_private_transform(%p, %p, %p, %u)", rsa, out, in, (unsigned) len);
150
151 ensure_keystore_engine();
152
153 const char *key_id = rsa_get_key_id(rsa);
154 if (key_id == NULL) {
155 ALOGE("key had no key_id!");
156 return 0;
157 }
158
159 uint8_t* reply = NULL;
160 size_t reply_len;
161 int32_t ret = g_keystore_backend->sign(key_id, in, len, &reply, &reply_len);
162 if (ret < 0) {
163 ALOGW("There was an error during rsa_decrypt: could not connect");
164 return 0;
165 } else if (ret != 0) {
166 ALOGW("Error during sign from keystore: %d", ret);
167 return 0;
168 } else if (reply_len == 0 || reply == NULL) {
169 ALOGW("No valid signature returned");
170 return 0;
171 }
172
173 if (reply_len > len) {
174 /* The result of the RSA operation can never be larger than the size of
175 * the modulus so we assume that the result has extra zeros on the
176 * left. This provides attackers with an oracle, but there's nothing
177 * that we can do about it here. */
178 ALOGW("Reply len %zu greater than expected %zu", reply_len, len);
179 memcpy(out, &reply[reply_len - len], len);
180 } else if (reply_len < len) {
181 /* If the Keystore implementation returns a short value we assume that
182 * it's because it removed leading zeros from the left side. This is
183 * bad because it provides attackers with an oracle but we cannot do
184 * anything about a broken Keystore implementation here. */
185 ALOGW("Reply len %zu lesser than expected %zu", reply_len, len);
186 memset(out, 0, len);
187 memcpy(out + len - reply_len, &reply[0], reply_len);
188 } else {
189 memcpy(out, &reply[0], len);
190 }
191
192 ALOGV("rsa=%p keystore_rsa_priv_dec successful", rsa);
193 return 1;
194 }
195
196 const struct rsa_meth_st keystore_rsa_method = {
197 {
198 0 /* references */,
199 1 /* is_static */,
200 },
201 NULL /* app_data */,
202
203 NULL /* init */,
204 NULL /* finish */,
205
206 NULL /* size */,
207
208 NULL /* sign */,
209 NULL /* verify */,
210
211 NULL /* encrypt */,
212 NULL /* sign_raw */,
213 NULL /* decrypt */,
214 NULL /* verify_raw */,
215
216 rsa_private_transform,
217
218 NULL /* mod_exp */,
219 NULL /* bn_mod_exp */,
220
221 RSA_FLAG_CACHE_PUBLIC | RSA_FLAG_OPAQUE,
222
223 NULL /* keygen */,
224 NULL /* multi_prime_keygen */,
225 NULL /* supports_digest */,
226 };
227
ecdsa_get_key_id(const EC_KEY * ec_key)228 const char* ecdsa_get_key_id(const EC_KEY* ec_key) {
229 return reinterpret_cast<char*>(
230 EC_KEY_get_ex_data(ec_key, g_keystore_engine->ec_key_ex_index()));
231 }
232
233 /* ecdsa_sign signs |digest_len| bytes from |digest| with |ec_key| and writes
234 * the resulting signature (an ASN.1 encoded blob) to |sig|. It returns one on
235 * 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)236 static int ecdsa_sign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
237 unsigned int* sig_len, EC_KEY* ec_key) {
238 ALOGV("ecdsa_sign(%p, %u, %p)", digest, (unsigned) digest_len, ec_key);
239
240 ensure_keystore_engine();
241
242 const char *key_id = ecdsa_get_key_id(ec_key);
243 if (key_id == NULL) {
244 ALOGE("key had no key_id!");
245 return 0;
246 }
247
248 size_t ecdsa_size = ECDSA_size(ec_key);
249
250 uint8_t* reply = NULL;
251 size_t reply_len;
252 int32_t ret = g_keystore_backend->sign(
253 key_id, digest, digest_len, &reply, &reply_len);
254 if (ret < 0) {
255 ALOGW("There was an error during ecdsa_sign: could not connect");
256 return 0;
257 } else if (reply_len == 0 || reply == NULL) {
258 ALOGW("No valid signature returned");
259 return 0;
260 } else if (reply_len > ecdsa_size) {
261 ALOGW("Signature is too large");
262 return 0;
263 }
264
265 // Reviewer: should't sig_len be checked here? Or is it just assumed that it is at least ecdsa_size?
266 memcpy(sig, &reply[0], reply_len);
267 *sig_len = reply_len;
268
269 ALOGV("ecdsa_sign(%p, %u, %p) => success", digest, (unsigned)digest_len,
270 ec_key);
271 return 1;
272 }
273
274 const ECDSA_METHOD keystore_ecdsa_method = {
275 {
276 0 /* references */,
277 1 /* is_static */
278 } /* common */,
279 NULL /* app_data */,
280
281 NULL /* init */,
282 NULL /* finish */,
283 NULL /* group_order_size */,
284 ecdsa_sign,
285 NULL /* verify */,
286 ECDSA_FLAG_OPAQUE,
287 };
288
289 struct EVP_PKEY_Delete {
operator ()__anon7400a8480111::EVP_PKEY_Delete290 void operator()(EVP_PKEY* p) const {
291 EVP_PKEY_free(p);
292 }
293 };
294 typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
295
296 struct RSA_Delete {
operator ()__anon7400a8480111::RSA_Delete297 void operator()(RSA* p) const {
298 RSA_free(p);
299 }
300 };
301 typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
302
303 struct EC_KEY_Delete {
operator ()__anon7400a8480111::EC_KEY_Delete304 void operator()(EC_KEY* ec) const {
305 EC_KEY_free(ec);
306 }
307 };
308 typedef UniquePtr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY;
309
310 /* wrap_rsa returns an |EVP_PKEY| that contains an RSA key where the public
311 * part is taken from |public_rsa| and the private operations are forwarded to
312 * KeyStore and operate on the key named |key_id|. */
wrap_rsa(const char * key_id,const RSA * public_rsa)313 static EVP_PKEY *wrap_rsa(const char *key_id, const RSA *public_rsa) {
314 Unique_RSA rsa(RSA_new_method(g_keystore_engine->engine()));
315 if (rsa.get() == NULL) {
316 return NULL;
317 }
318
319 char *key_id_copy = strdup(key_id);
320 if (key_id_copy == NULL) {
321 return NULL;
322 }
323
324 if (!RSA_set_ex_data(rsa.get(), g_keystore_engine->rsa_ex_index(),
325 key_id_copy)) {
326 free(key_id_copy);
327 return NULL;
328 }
329
330 rsa->n = BN_dup(public_rsa->n);
331 rsa->e = BN_dup(public_rsa->e);
332 if (rsa->n == NULL || rsa->e == NULL) {
333 return NULL;
334 }
335
336 Unique_EVP_PKEY result(EVP_PKEY_new());
337 if (result.get() == NULL ||
338 !EVP_PKEY_assign_RSA(result.get(), rsa.get())) {
339 return NULL;
340 }
341 OWNERSHIP_TRANSFERRED(rsa);
342
343 return result.release();
344 }
345
346 /* wrap_ecdsa returns an |EVP_PKEY| that contains an ECDSA key where the public
347 * part is taken from |public_rsa| and the private operations are forwarded to
348 * KeyStore and operate on the key named |key_id|. */
wrap_ecdsa(const char * key_id,const EC_KEY * public_ecdsa)349 static EVP_PKEY *wrap_ecdsa(const char *key_id, const EC_KEY *public_ecdsa) {
350 Unique_EC_KEY ec(EC_KEY_new_method(g_keystore_engine->engine()));
351 if (ec.get() == NULL) {
352 return NULL;
353 }
354
355 if (!EC_KEY_set_group(ec.get(), EC_KEY_get0_group(public_ecdsa)) ||
356 !EC_KEY_set_public_key(ec.get(), EC_KEY_get0_public_key(public_ecdsa))) {
357 return NULL;
358 }
359
360 char *key_id_copy = strdup(key_id);
361 if (key_id_copy == NULL) {
362 return NULL;
363 }
364
365 if (!EC_KEY_set_ex_data(ec.get(), g_keystore_engine->ec_key_ex_index(),
366 key_id_copy)) {
367 free(key_id_copy);
368 return NULL;
369 }
370
371 Unique_EVP_PKEY result(EVP_PKEY_new());
372 if (result.get() == NULL ||
373 !EVP_PKEY_assign_EC_KEY(result.get(), ec.get())) {
374 return NULL;
375 }
376 OWNERSHIP_TRANSFERRED(ec);
377
378 return result.release();
379 }
380
381 } /* anonymous namespace */
382
383 extern "C" {
384
385 EVP_PKEY* EVP_PKEY_from_keystore(const char* key_id) __attribute__((visibility("default")));
386
387 /* EVP_PKEY_from_keystore returns an |EVP_PKEY| that contains either an RSA or
388 * ECDSA key where the public part of the key reflects the value of the key
389 * named |key_id| in Keystore and the private operations are forwarded onto
390 * KeyStore. */
EVP_PKEY_from_keystore(const char * key_id)391 EVP_PKEY* EVP_PKEY_from_keystore(const char* key_id) {
392 ALOGV("EVP_PKEY_from_keystore(\"%s\")", key_id);
393
394 ensure_keystore_engine();
395
396 uint8_t *pubkey = NULL;
397 size_t pubkey_len;
398 int32_t ret = g_keystore_backend->get_pubkey(key_id, &pubkey, &pubkey_len);
399 if (ret < 0) {
400 ALOGW("could not contact keystore");
401 return NULL;
402 } else if (ret != 0 || pubkey == NULL) {
403 ALOGW("keystore reports error: %d", ret);
404 return NULL;
405 }
406
407 const uint8_t *inp = pubkey;
408 Unique_EVP_PKEY pkey(d2i_PUBKEY(NULL, &inp, pubkey_len));
409 if (pkey.get() == NULL) {
410 ALOGW("Cannot convert pubkey");
411 return NULL;
412 }
413
414 EVP_PKEY *result;
415 switch (EVP_PKEY_type(pkey->type)) {
416 case EVP_PKEY_RSA: {
417 Unique_RSA public_rsa(EVP_PKEY_get1_RSA(pkey.get()));
418 result = wrap_rsa(key_id, public_rsa.get());
419 break;
420 }
421 case EVP_PKEY_EC: {
422 Unique_EC_KEY public_ecdsa(EVP_PKEY_get1_EC_KEY(pkey.get()));
423 result = wrap_ecdsa(key_id, public_ecdsa.get());
424 break;
425 }
426 default:
427 ALOGE("Unsupported key type %d", EVP_PKEY_type(pkey->type));
428 result = NULL;
429 }
430
431 return result;
432 }
433
434 } // extern "C"
435