blob: 4790a668bd4d24b7671d1318aee5c0a81ded74ed [file] [log] [blame]
Kenny Root70e3a862012-02-15 17:20:23 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
17 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
20 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23 *
24 */
25
Colin Cross98c2f8f2012-03-28 09:44:09 -070026#include <utils/UniquePtr.h>
Kenny Root70e3a862012-02-15 17:20:23 -080027
28#include <sys/socket.h>
29#include <stdarg.h>
30#include <string.h>
Kenny Rootbef80832012-05-03 11:19:28 -070031#include <unistd.h>
Kenny Root70e3a862012-02-15 17:20:23 -080032
33#include <openssl/objects.h>
34#include <openssl/engine.h>
35#include <openssl/evp.h>
36
Brian Carlstroma8c703d2012-07-17 14:43:46 -070037//#define LOG_NDEBUG 0
Kenny Root70e3a862012-02-15 17:20:23 -080038#define LOG_TAG "OpenSSL-keystore"
39#include <cutils/log.h>
40
Kenny Root07438c82012-11-02 15:41:02 -070041#include <binder/IServiceManager.h>
42#include <keystore/keystore.h>
43#include <keystore/IKeystoreService.h>
Kenny Root70e3a862012-02-15 17:20:23 -080044
Kenny Root07438c82012-11-02 15:41:02 -070045using namespace android;
Kenny Root70e3a862012-02-15 17:20:23 -080046
47#define DYNAMIC_ENGINE
48#define KEYSTORE_ENGINE_ID "keystore"
49#define KEYSTORE_ENGINE_NAME "Android keystore engine"
50
51/**
52 * Many OpenSSL APIs take ownership of an argument on success but don't free the argument
53 * on failure. This means we need to tell our scoped pointers when we've transferred ownership,
54 * without triggering a warning by not using the result of release().
55 */
56#define OWNERSHIP_TRANSFERRED(obj) \
57 typeof (obj.release()) _dummy __attribute__((unused)) = obj.release()
58
59struct ENGINE_Delete {
60 void operator()(ENGINE* p) const {
61 ENGINE_free(p);
62 }
63};
64typedef UniquePtr<ENGINE, ENGINE_Delete> Unique_ENGINE;
65
66struct EVP_PKEY_Delete {
67 void operator()(EVP_PKEY* p) const {
68 EVP_PKEY_free(p);
69 }
70};
71typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
72
73struct RSA_Delete {
74 void operator()(RSA* p) const {
75 RSA_free(p);
76 }
77};
78typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
79
80
81/*
82 * RSA ex_data index for keystore's key handle.
83 */
84static int rsa_key_handle;
85
Kenny Rootbef80832012-05-03 11:19:28 -070086/*
87 * Only initialize the rsa_key_handle once.
Kenny Root70e3a862012-02-15 17:20:23 -080088 */
Kenny Rootbef80832012-05-03 11:19:28 -070089static pthread_once_t rsa_key_handle_control = PTHREAD_ONCE_INIT;
90
Kenny Root70e3a862012-02-15 17:20:23 -080091
92/**
93 * Makes sure the ex_data for the keyhandle is initially set to NULL.
94 */
95int keyhandle_new(void*, void*, CRYPTO_EX_DATA* ad, int idx, long, void*) {
96 return CRYPTO_set_ex_data(ad, idx, NULL);
97}
98
99/**
100 * Frees a previously allocated keyhandle stored in ex_data.
101 */
102void keyhandle_free(void *, void *ptr, CRYPTO_EX_DATA*, int, long, void*) {
103 char* keyhandle = reinterpret_cast<char*>(ptr);
104 if (keyhandle != NULL) {
105 free(keyhandle);
106 }
107}
108
109/**
110 * Duplicates a keyhandle stored in ex_data in case we copy a key.
111 */
112int keyhandle_dup(CRYPTO_EX_DATA* to, CRYPTO_EX_DATA*, void *ptrRef, int idx, long, void *) {
113 // This appears to be a bug in OpenSSL.
114 void** ptr = reinterpret_cast<void**>(ptrRef);
115 char* keyhandle = reinterpret_cast<char*>(*ptr);
116 if (keyhandle != NULL) {
117 char* keyhandle_copy = strdup(keyhandle);
118 *ptr = keyhandle_copy;
119
120 // Call this in case OpenSSL is fixed in the future.
121 (void) CRYPTO_set_ex_data(to, idx, keyhandle_copy);
122 }
123 return 1;
124}
125
126int keystore_rsa_priv_enc(int flen, const unsigned char* from, unsigned char* to, RSA* rsa,
127 int padding) {
128 ALOGV("keystore_rsa_sign(%d, %p, %p, %p, %d)", flen, from, to, rsa, padding);
129
130 int num = RSA_size(rsa);
131 UniquePtr<uint8_t> padded(new uint8_t[num]);
132 if (padded.get() == NULL) {
133 ALOGE("could not allocate padded signature");
134 return 0;
135 }
136
137 switch (padding) {
138 case RSA_PKCS1_PADDING:
139 if (!RSA_padding_add_PKCS1_type_1(padded.get(), num, from, flen)) {
140 return 0;
141 }
142 break;
143 case RSA_X931_PADDING:
144 if (!RSA_padding_add_X931(padded.get(), num, from, flen)) {
145 return 0;
146 }
147 break;
148 case RSA_NO_PADDING:
149 if (!RSA_padding_add_none(padded.get(), num, from, flen)) {
150 return 0;
151 }
152 break;
153 default:
154 ALOGE("Unknown padding type: %d", padding);
155 return 0;
156 }
157
158 uint8_t* key_id = reinterpret_cast<uint8_t*>(RSA_get_ex_data(rsa, rsa_key_handle));
159 if (key_id == NULL) {
160 ALOGE("key had no key_id!");
161 return 0;
162 }
163
Kenny Root07438c82012-11-02 15:41:02 -0700164 sp<IServiceManager> sm = defaultServiceManager();
165 sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
166 sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
167
168 if (service == NULL) {
169 ALOGE("could not contact keystore");
Kenny Root70e3a862012-02-15 17:20:23 -0800170 return 0;
171 }
172
Kenny Root07438c82012-11-02 15:41:02 -0700173 uint8_t* reply = NULL;
174 size_t replyLen;
175 int32_t ret = service->sign(String16(reinterpret_cast<const char*>(key_id)), padded.get(),
176 num, &reply, &replyLen);
177 if (ret < 0) {
178 ALOGW("There was an error during rsa_mod_exp: could not connect");
179 free(reply);
180 return 0;
181 } else if (ret != 0) {
182 ALOGW("Error during rsa_mod_exp from keystore: %d", ret);
183 free(reply);
184 return 0;
185 } else if (replyLen <= 0) {
Kenny Root70e3a862012-02-15 17:20:23 -0800186 ALOGW("No valid signature returned");
187 return 0;
188 }
189
Kenny Root07438c82012-11-02 15:41:02 -0700190 memcpy(to, reply, replyLen);
Kenny Root70e3a862012-02-15 17:20:23 -0800191
192 ALOGV("rsa=%p keystore_rsa_sign => returning %p len %llu", rsa, to,
193 (unsigned long long) replyLen);
194 return static_cast<int>(replyLen);
195}
196
197static RSA_METHOD keystore_rsa_meth = {
198 KEYSTORE_ENGINE_NAME,
199 NULL, /* rsa_pub_enc */
200 NULL, /* rsa_pub_dec (verification) */
201 keystore_rsa_priv_enc, /* rsa_priv_enc (signing) */
202 NULL, /* rsa_priv_dec */
203 NULL, /* rsa_mod_exp */
204 NULL, /* bn_mod_exp */
205 NULL, /* init */
206 NULL, /* finish */
207 RSA_FLAG_EXT_PKEY | RSA_FLAG_NO_BLINDING, /* flags */
208 NULL, /* app_data */
209 NULL, /* rsa_sign */
210 NULL, /* rsa_verify */
211 NULL, /* rsa_keygen */
212};
213
214static int register_rsa_methods() {
215 const RSA_METHOD* rsa_meth = RSA_PKCS1_SSLeay();
216
217 keystore_rsa_meth.rsa_pub_enc = rsa_meth->rsa_pub_enc;
218 keystore_rsa_meth.rsa_pub_dec = rsa_meth->rsa_pub_dec;
219 keystore_rsa_meth.rsa_priv_dec = rsa_meth->rsa_priv_dec;
220 keystore_rsa_meth.rsa_mod_exp = rsa_meth->rsa_mod_exp;
221 keystore_rsa_meth.bn_mod_exp = rsa_meth->bn_mod_exp;
222
223 return 1;
224}
225
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700226static EVP_PKEY* keystore_loadkey(ENGINE* e, const char* key_id, UI_METHOD* ui_method,
227 void* callback_data) {
228#if LOG_NDEBUG
229 (void)ui_method;
230 (void)callback_data;
231#else
Kenny Root70e3a862012-02-15 17:20:23 -0800232 ALOGV("keystore_loadkey(%p, \"%s\", %p, %p)", e, key_id, ui_method, callback_data);
Brian Carlstroma8c703d2012-07-17 14:43:46 -0700233#endif
Kenny Root70e3a862012-02-15 17:20:23 -0800234
Kenny Root07438c82012-11-02 15:41:02 -0700235 sp<IServiceManager> sm = defaultServiceManager();
236 sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
237 sp<IKeystoreService> service = interface_cast<IKeystoreService>(binder);
238
239 if (service == NULL) {
240 ALOGE("could not contact keystore");
241 return 0;
242 }
243
244 uint8_t *pubkey = NULL;
245 size_t pubkeyLen;
246 int32_t ret = service->get_pubkey(String16(key_id), &pubkey, &pubkeyLen);
247 if (ret < 0) {
248 ALOGW("could not contact keystore");
249 free(pubkey);
250 return NULL;
251 } else if (ret != 0) {
252 ALOGW("keystore reports error: %d", ret);
253 free(pubkey);
Kenny Root70e3a862012-02-15 17:20:23 -0800254 return NULL;
255 }
256
Kenny Root07438c82012-11-02 15:41:02 -0700257 const unsigned char* tmp = reinterpret_cast<const unsigned char*>(pubkey);
258 Unique_EVP_PKEY pkey(d2i_PUBKEY(NULL, &tmp, pubkeyLen));
259 free(pubkey);
Kenny Root70e3a862012-02-15 17:20:23 -0800260 if (pkey.get() == NULL) {
261 ALOGW("Cannot convert pubkey");
262 return NULL;
263 }
264
265 switch (EVP_PKEY_type(pkey->type)) {
266 case EVP_PKEY_RSA: {
267 Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get()));
268 if (!RSA_set_ex_data(rsa.get(), rsa_key_handle, reinterpret_cast<void*>(strdup(key_id)))) {
269 ALOGW("Could not set ex_data for loaded RSA key");
270 return NULL;
271 }
272
273 RSA_set_method(rsa.get(), &keystore_rsa_meth);
274 RSA_blinding_off(rsa.get());
275
276 /*
277 * This should probably be an OpenSSL API, but EVP_PKEY_free calls
278 * ENGINE_finish(), so we need to call ENGINE_init() here.
279 */
280 ENGINE_init(e);
281 rsa->engine = e;
282 rsa->flags |= RSA_FLAG_EXT_PKEY;
283
284 break;
285 }
286 default:
287 ALOGE("Unsupported key type %d", EVP_PKEY_type(pkey->type));
288 return NULL;
289 }
290
291 return pkey.release();
292}
293
294static const ENGINE_CMD_DEFN keystore_cmd_defns[] = {
295 {0, NULL, NULL, 0}
296};
297
Kenny Rootbef80832012-05-03 11:19:28 -0700298/**
299 * Called to initialize RSA's ex_data for the key_id handle. This should
300 * only be called when protected by a lock.
301 */
302static void init_rsa_key_handle() {
303 rsa_key_handle = RSA_get_ex_new_index(0, NULL, keyhandle_new, keyhandle_dup,
304 keyhandle_free);
305}
306
Kenny Root70e3a862012-02-15 17:20:23 -0800307static int keystore_engine_setup(ENGINE* e) {
308 ALOGV("keystore_engine_setup");
309
310 if (!ENGINE_set_id(e, KEYSTORE_ENGINE_ID)
311 || !ENGINE_set_name(e, KEYSTORE_ENGINE_NAME)
312 || !ENGINE_set_load_privkey_function(e, keystore_loadkey)
313 || !ENGINE_set_load_pubkey_function(e, keystore_loadkey)
Kenny Root938a9912012-08-15 22:19:25 -0700314 || !ENGINE_set_flags(e, 0)
Kenny Root70e3a862012-02-15 17:20:23 -0800315 || !ENGINE_set_cmd_defns(e, keystore_cmd_defns)) {
316 ALOGE("Could not set up keystore engine");
317 return 0;
318 }
319
320 if (!ENGINE_set_RSA(e, &keystore_rsa_meth)
321 || !register_rsa_methods()) {
322 ALOGE("Could not set up keystore RSA methods");
323 return 0;
324 }
325
Kenny Rootbef80832012-05-03 11:19:28 -0700326 /* We need a handle in the RSA keys as well for keygen if it's not already initialized. */
327 pthread_once(&rsa_key_handle_control, init_rsa_key_handle);
Kenny Root70e3a862012-02-15 17:20:23 -0800328 if (rsa_key_handle < 0) {
329 ALOGE("Could not set up RSA ex_data index");
330 return 0;
331 }
332
333 return 1;
334}
335
336ENGINE* ENGINE_keystore() {
337 ALOGV("ENGINE_keystore");
338
339 Unique_ENGINE engine(ENGINE_new());
340 if (engine.get() == NULL) {
341 return NULL;
342 }
343
344 if (!keystore_engine_setup(engine.get())) {
345 return NULL;
346 }
347
348 return engine.release();
349}
350
351static int keystore_bind_fn(ENGINE *e, const char *id) {
352 ALOGV("keystore_bind_fn");
353
354 if (!id) {
355 return 0;
356 }
357
358 if (strcmp(id, KEYSTORE_ENGINE_ID)) {
359 return 0;
360 }
361
362 if (!keystore_engine_setup(e)) {
363 return 0;
364 }
365
366 return 1;
367}
368
369extern "C" {
370#undef OPENSSL_EXPORT
371#define OPENSSL_EXPORT extern __attribute__ ((visibility ("default")))
372
373IMPLEMENT_DYNAMIC_CHECK_FN()
374IMPLEMENT_DYNAMIC_BIND_FN(keystore_bind_fn)
375};