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