blob: 7be00eaa8b21a59d03604677107b24b283d0b632 [file] [log] [blame]
Kenny Root70e3a862012-02-15 17:20:23 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#include <errno.h>
17#include <string.h>
18#include <stdint.h>
19
20#include <hardware/hardware.h>
21#include <hardware/keymaster.h>
22
23#include <openssl/evp.h>
24#include <openssl/bio.h>
25#include <openssl/rsa.h>
26#include <openssl/err.h>
27#include <openssl/x509.h>
28
29#include <UniquePtr.h>
30
31// For debugging
32//#define LOG_NDEBUG 0
33
34#define LOG_TAG "OpenSSLKeyMaster"
35#include <cutils/log.h>
36
37struct BIGNUM_Delete {
38 void operator()(BIGNUM* p) const {
39 BN_free(p);
40 }
41};
42typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
43
44struct EVP_PKEY_Delete {
45 void operator()(EVP_PKEY* p) const {
46 EVP_PKEY_free(p);
47 }
48};
49typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
50
51struct PKCS8_PRIV_KEY_INFO_Delete {
52 void operator()(PKCS8_PRIV_KEY_INFO* p) const {
53 PKCS8_PRIV_KEY_INFO_free(p);
54 }
55};
56typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
57
58struct RSA_Delete {
59 void operator()(RSA* p) const {
60 RSA_free(p);
61 }
62};
63typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
64
65typedef UniquePtr<keymaster_device_t> Unique_keymaster_device_t;
66
67/**
68 * Many OpenSSL APIs take ownership of an argument on success but don't free the argument
69 * on failure. This means we need to tell our scoped pointers when we've transferred ownership,
70 * without triggering a warning by not using the result of release().
71 */
72#define OWNERSHIP_TRANSFERRED(obj) \
73 typeof (obj.release()) _dummy __attribute__((unused)) = obj.release()
74
75
76/*
77 * Checks this thread's OpenSSL error queue and logs if
78 * necessary.
79 */
80static void logOpenSSLError(const char* location) {
81 int error = ERR_get_error();
82
83 if (error != 0) {
84 char message[256];
85 ERR_error_string_n(error, message, sizeof(message));
86 ALOGE("OpenSSL error in %s %d: %s", location, error, message);
87 }
88
89 ERR_clear_error();
90 ERR_remove_state(0);
91}
92
93static int wrap_key(EVP_PKEY* pkey, int type, uint8_t** keyBlob, size_t* keyBlobLength) {
94 /* Find the length of each size */
95 int publicLen = i2d_PublicKey(pkey, NULL);
96 int privateLen = i2d_PrivateKey(pkey, NULL);
97
98 if (privateLen <= 0 || publicLen <= 0) {
99 ALOGE("private or public key size was too big");
100 return -1;
101 }
102
103 /* int type + int size + private key data + int size + public key data */
104 *keyBlobLength = sizeof(int) + sizeof(int) + privateLen + sizeof(int) + publicLen;
105
106 UniquePtr<unsigned char[]> derData(new unsigned char[*keyBlobLength]);
107 if (derData.get() == NULL) {
108 ALOGE("could not allocate memory for key blob");
109 return -1;
110 }
111 unsigned char* p = derData.get();
112
113 /* Write key type to allocated buffer */
114 for (int i = sizeof(int) - 1; i >= 0; i--) {
115 *p++ = (type >> (8*i)) & 0xFF;
116 }
117
118 /* Write public key to allocated buffer */
119 for (int i = sizeof(int) - 1; i >= 0; i--) {
120 *p++ = (publicLen >> (8*i)) & 0xFF;
121 }
122 if (i2d_PublicKey(pkey, &p) != publicLen) {
123 logOpenSSLError("wrap_key");
124 return -1;
125 }
126
127 /* Write private key to allocated buffer */
128 for (int i = sizeof(int) - 1; i >= 0; i--) {
129 *p++ = (privateLen >> (8*i)) & 0xFF;
130 }
131 if (i2d_PrivateKey(pkey, &p) != privateLen) {
132 logOpenSSLError("wrap_key");
133 return -1;
134 }
135
136 *keyBlob = derData.release();
137
138 return 0;
139}
140
141static EVP_PKEY* unwrap_key(const uint8_t* keyBlob, const size_t keyBlobLength) {
142 long publicLen = 0;
143 long privateLen = 0;
144 const uint8_t* p = keyBlob;
145 const uint8_t *const end = keyBlob + keyBlobLength;
146
147 if (keyBlob == NULL) {
148 ALOGE("supplied key blob was NULL");
149 return NULL;
150 }
151
152 // Should be large enough for:
153 // int32 type, int32 pubLen, char* pub, int32 privLen, char* priv
154 if (keyBlobLength < (sizeof(int) + sizeof(int) + 1 + sizeof(int) + 1)) {
155 ALOGE("key blob appears to be truncated");
156 return NULL;
157 }
158
159 int type = 0;
160 for (size_t i = 0; i < sizeof(int); i++) {
161 type = (type << 8) | *p++;
162 }
163
164 Unique_EVP_PKEY pkey(EVP_PKEY_new());
165 if (pkey.get() == NULL) {
166 logOpenSSLError("unwrap_key");
167 return NULL;
168 }
169
170 for (size_t i = 0; i < sizeof(int); i++) {
171 publicLen = (publicLen << 8) | *p++;
172 }
173 if (p + publicLen > end) {
174 ALOGE("public key length encoding error: size=%ld, end=%d", publicLen, end - p);
175 return NULL;
176 }
177 EVP_PKEY* tmp = pkey.get();
178 d2i_PublicKey(type, &tmp, &p, publicLen);
179
180 if (end - p < 2) {
181 ALOGE("private key truncated");
182 return NULL;
183 }
184 for (size_t i = 0; i < sizeof(int); i++) {
185 privateLen = (privateLen << 8) | *p++;
186 }
187 if (p + privateLen > end) {
188 ALOGE("private key length encoding error: size=%ld, end=%d", privateLen, end - p);
189 return NULL;
190 }
191 d2i_PrivateKey(type, &tmp, &p, privateLen);
192
193 return pkey.release();
194}
195
196static int openssl_generate_keypair(const keymaster_device_t* dev,
197 const keymaster_keypair_t key_type, const void* key_params,
198 uint8_t** keyBlob, size_t* keyBlobLength) {
199 ssize_t privateLen, publicLen;
200
201 if (key_type != TYPE_RSA) {
202 ALOGW("Unsupported key type %d", key_type);
203 return -1;
204 } else if (key_params == NULL) {
205 ALOGW("key_params == null");
206 return -1;
207 }
208
209 keymaster_rsa_keygen_params_t* rsa_params = (keymaster_rsa_keygen_params_t*) key_params;
210
211 Unique_BIGNUM bn(BN_new());
212 if (bn.get() == NULL) {
213 logOpenSSLError("openssl_generate_keypair");
214 return -1;
215 }
216
217 if (BN_set_word(bn.get(), rsa_params->public_exponent) == 0) {
218 logOpenSSLError("openssl_generate_keypair");
219 return -1;
220 }
221
222 /* initialize RSA */
223 Unique_RSA rsa(RSA_new());
224 if (rsa.get() == NULL) {
225 logOpenSSLError("openssl_generate_keypair");
226 return -1;
227 }
228
229 if (!RSA_generate_key_ex(rsa.get(), rsa_params->modulus_size, bn.get(), NULL)
230 || RSA_check_key(rsa.get()) < 0) {
231 logOpenSSLError("openssl_generate_keypair");
232 return -1;
233 }
234
235 /* assign to EVP */
236 Unique_EVP_PKEY pkey(EVP_PKEY_new());
237 if (pkey.get() == NULL) {
238 logOpenSSLError("openssl_generate_keypair");
239 return -1;
240 }
241
242 if (EVP_PKEY_assign_RSA(pkey.get(), rsa.get()) == 0) {
243 logOpenSSLError("openssl_generate_keypair");
244 return -1;
245 }
246 OWNERSHIP_TRANSFERRED(rsa);
247
248 if (wrap_key(pkey.get(), EVP_PKEY_RSA, keyBlob, keyBlobLength)) {
249 return -1;
250 }
251
252 return 0;
253}
254
255static int openssl_import_keypair(const keymaster_device_t* dev,
256 const uint8_t* key, const size_t key_length,
257 uint8_t** key_blob, size_t* key_blob_length) {
258 int response = -1;
259
260 if (key == NULL) {
261 ALOGW("input key == NULL");
262 return -1;
263 } else if (key_blob == NULL || key_blob_length == NULL) {
264 ALOGW("output key blob or length == NULL");
265 return -1;
266 }
267
268 Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, key_length));
269 if (pkcs8.get() == NULL) {
270 logOpenSSLError("openssl_import_keypair");
271 return -1;
272 }
273
274 /* assign to EVP */
275 Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
276 if (pkey.get() == NULL) {
277 logOpenSSLError("openssl_import_keypair");
278 return -1;
279 }
280 OWNERSHIP_TRANSFERRED(pkcs8);
281
282 if (wrap_key(pkey.get(), EVP_PKEY_type(pkey->type), key_blob, key_blob_length)) {
283 return -1;
284 }
285
286 return 0;
287}
288
289static int openssl_get_keypair_public(const struct keymaster_device* dev,
290 const uint8_t* key_blob, const size_t key_blob_length,
291 uint8_t** x509_data, size_t* x509_data_length) {
292
293 if (x509_data == NULL || x509_data_length == NULL) {
294 ALOGW("output public key buffer == NULL");
295 return -1;
296 }
297
298 Unique_EVP_PKEY pkey(unwrap_key(key_blob, key_blob_length));
299 if (pkey.get() == NULL) {
300 return -1;
301 }
302
303 int len = i2d_PUBKEY(pkey.get(), NULL);
304 if (len <= 0) {
305 logOpenSSLError("openssl_get_keypair_public");
306 return -1;
307 }
308
309 UniquePtr<uint8_t> key(static_cast<uint8_t*>(malloc(len)));
310 if (key.get() == NULL) {
311 ALOGE("Could not allocate memory for public key data");
312 return -1;
313 }
314
315 unsigned char* tmp = reinterpret_cast<unsigned char*>(key.get());
316 if (i2d_PUBKEY(pkey.get(), &tmp) != len) {
317 logOpenSSLError("openssl_get_keypair_public");
318 return -1;
319 }
320
321 ALOGV("Length of x509 data is %d", len);
322 *x509_data_length = len;
323 *x509_data = key.release();
324
325 return 0;
326}
327
328static int openssl_sign_data(const keymaster_device_t* dev,
329 const void* params,
330 const uint8_t* keyBlob, const size_t keyBlobLength,
331 const uint8_t* data, const size_t dataLength,
332 uint8_t** signedData, size_t* signedDataLength) {
333
334 int result = -1;
335 EVP_MD_CTX ctx;
336 size_t maxSize;
337
338 if (data == NULL) {
339 ALOGW("input data to sign == NULL");
340 return -1;
341 } else if (signedData == NULL || signedDataLength == NULL) {
342 ALOGW("output signature buffer == NULL");
343 return -1;
344 }
345
346 Unique_EVP_PKEY pkey(unwrap_key(keyBlob, keyBlobLength));
347 if (pkey.get() == NULL) {
348 return -1;
349 }
350
351 if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) {
352 ALOGW("Cannot handle non-RSA keys yet");
353 return -1;
354 }
355
356 keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params;
357 if (sign_params->digest_type != DIGEST_NONE) {
358 ALOGW("Cannot handle digest type %d", sign_params->digest_type);
359 return -1;
360 } else if (sign_params->padding_type != PADDING_NONE) {
361 ALOGW("Cannot handle padding type %d", sign_params->padding_type);
362 return -1;
363 }
364
365 Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get()));
366 if (rsa.get() == NULL) {
367 logOpenSSLError("openssl_sign_data");
368 return -1;
369 }
370
371 UniquePtr<uint8_t> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(dataLength)));
372 if (signedDataPtr.get() == NULL) {
373 logOpenSSLError("openssl_sign_data");
374 return -1;
375 }
376
377 unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get());
378 if (RSA_private_encrypt(dataLength, data, tmp, rsa.get(), RSA_NO_PADDING) <= 0) {
379 logOpenSSLError("openssl_sign_data");
380 return -1;
381 }
382
383 *signedDataLength = dataLength;
384 *signedData = signedDataPtr.release();
385 return 0;
386}
387
388static int openssl_verify_data(const keymaster_device_t* dev,
389 const void* params,
390 const uint8_t* keyBlob, const size_t keyBlobLength,
391 const uint8_t* signedData, const size_t signedDataLength,
392 const uint8_t* signature, const size_t signatureLength) {
393
394 if (signedData == NULL || signature == NULL) {
395 ALOGW("data or signature buffers == NULL");
396 return -1;
397 }
398
399 Unique_EVP_PKEY pkey(unwrap_key(keyBlob, keyBlobLength));
400 if (pkey.get() == NULL) {
401 return -1;
402 }
403
404 if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) {
405 ALOGW("Cannot handle non-RSA keys yet");
406 return -1;
407 }
408
409 keymaster_rsa_sign_params_t* sign_params = (keymaster_rsa_sign_params_t*) params;
410 if (sign_params->digest_type != DIGEST_NONE) {
411 ALOGW("Cannot handle digest type %d", sign_params->digest_type);
412 return -1;
413 } else if (sign_params->padding_type != PADDING_NONE) {
414 ALOGW("Cannot handle padding type %d", sign_params->padding_type);
415 return -1;
416 } else if (signatureLength != signedDataLength) {
417 ALOGW("signed data length must be signature length");
418 return -1;
419 }
420
421 Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey.get()));
422 if (rsa.get() == NULL) {
423 logOpenSSLError("openssl_verify_data");
424 return -1;
425 }
426
427 UniquePtr<uint8_t> dataPtr(reinterpret_cast<uint8_t*>(malloc(signedDataLength)));
428 if (dataPtr.get() == NULL) {
429 logOpenSSLError("openssl_verify_data");
430 return -1;
431 }
432
433 unsigned char* tmp = reinterpret_cast<unsigned char*>(dataPtr.get());
434 if (!RSA_public_decrypt(signatureLength, signature, tmp, rsa.get(), RSA_NO_PADDING)) {
435 logOpenSSLError("openssl_verify_data");
436 return -1;
437 }
438
439 int result = 0;
440 for (size_t i = 0; i < signedDataLength; i++) {
441 result |= tmp[i] ^ signedData[i];
442 }
443
444 return result == 0 ? 0 : -1;
445}
446
447/* Close an opened OpenSSL instance */
448static int openssl_close(hw_device_t *dev) {
449 free(dev);
450 return 0;
451}
452
453/*
454 * Generic device handling
455 */
456static int openssl_open(const hw_module_t* module, const char* name,
457 hw_device_t** device) {
458 if (strcmp(name, KEYSTORE_KEYMASTER) != 0)
459 return -EINVAL;
460
461 Unique_keymaster_device_t dev(new keymaster_device_t);
462 if (dev.get() == NULL)
463 return -ENOMEM;
464
465 dev->common.tag = HARDWARE_DEVICE_TAG;
466 dev->common.version = 1;
467 dev->common.module = (struct hw_module_t*) module;
468 dev->common.close = openssl_close;
469
470 dev->generate_keypair = openssl_generate_keypair;
471 dev->import_keypair = openssl_import_keypair;
472 dev->get_keypair_public = openssl_get_keypair_public;
473 dev->delete_keypair = NULL;
474 dev->sign_data = openssl_sign_data;
475 dev->verify_data = openssl_verify_data;
476
477 ERR_load_crypto_strings();
478 ERR_load_BIO_strings();
479
480 *device = reinterpret_cast<hw_device_t*>(dev.release());
481
482 return 0;
483}
484
485static struct hw_module_methods_t keystore_module_methods = {
486 open: openssl_open,
487};
488
489struct keystore_module HAL_MODULE_INFO_SYM
490__attribute__ ((visibility ("default"))) = {
491 common: {
492 tag: HARDWARE_MODULE_TAG,
493 version_major: 1,
494 version_minor: 0,
495 id: KEYSTORE_HARDWARE_MODULE_ID,
496 name: "Keymaster OpenSSL HAL",
497 author: "The Android Open Source Project",
498 methods: &keystore_module_methods,
499 dso: 0,
500 reserved: {},
501 },
502};