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 #include <keymaster/softkeymaster.h>
22 
23 #include <hardware/hardware.h>
24 #include <hardware/keymaster0.h>
25 
26 #include <openssl/evp.h>
27 #include <openssl/bio.h>
28 #include <openssl/rsa.h>
29 #include <openssl/err.h>
30 #include <openssl/x509.h>
31 
32 #include <UniquePtr.h>
33 
34 // For debugging
35 // #define LOG_NDEBUG 0
36 
37 #define LOG_TAG "OpenSSLKeyMaster"
38 #include <cutils/log.h>
39 
40 struct BIGNUM_Delete {
operator ()BIGNUM_Delete41     void operator()(BIGNUM* p) const { BN_free(p); }
42 };
43 typedef UniquePtr<BIGNUM, BIGNUM_Delete> Unique_BIGNUM;
44 
45 struct EVP_PKEY_Delete {
operator ()EVP_PKEY_Delete46     void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); }
47 };
48 typedef UniquePtr<EVP_PKEY, EVP_PKEY_Delete> Unique_EVP_PKEY;
49 
50 struct PKCS8_PRIV_KEY_INFO_Delete {
operator ()PKCS8_PRIV_KEY_INFO_Delete51     void operator()(PKCS8_PRIV_KEY_INFO* p) const { PKCS8_PRIV_KEY_INFO_free(p); }
52 };
53 typedef UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> Unique_PKCS8_PRIV_KEY_INFO;
54 
55 struct DSA_Delete {
operator ()DSA_Delete56     void operator()(DSA* p) const { DSA_free(p); }
57 };
58 typedef UniquePtr<DSA, DSA_Delete> Unique_DSA;
59 
60 struct EC_KEY_Delete {
operator ()EC_KEY_Delete61     void operator()(EC_KEY* p) const { EC_KEY_free(p); }
62 };
63 typedef UniquePtr<EC_KEY, EC_KEY_Delete> Unique_EC_KEY;
64 
65 struct EC_GROUP_Delete {
operator ()EC_GROUP_Delete66     void operator()(EC_GROUP* p) const { EC_GROUP_free(p); }
67 };
68 typedef UniquePtr<EC_GROUP, EC_GROUP_Delete> Unique_EC_GROUP;
69 
70 struct RSA_Delete {
operator ()RSA_Delete71     void operator()(RSA* p) const { RSA_free(p); }
72 };
73 typedef UniquePtr<RSA, RSA_Delete> Unique_RSA;
74 
75 struct Malloc_Free {
operator ()Malloc_Free76     void operator()(void* p) const { free(p); }
77 };
78 
79 typedef UniquePtr<keymaster0_device_t> Unique_keymaster_device_t;
80 
81 /**
82  * Many OpenSSL APIs take ownership of an argument on success but
83  * don't free the argument on failure. This means we need to tell our
84  * scoped pointers when we've transferred ownership, without
85  * triggering a warning by not using the result of release().
86  */
87 template <typename T, typename Delete_T>
release_because_ownership_transferred(UniquePtr<T,Delete_T> & p)88 inline void release_because_ownership_transferred(UniquePtr<T, Delete_T>& p) {
89     T* val __attribute__((unused)) = p.release();
90 }
91 
92 /*
93  * Checks this thread's OpenSSL error queue and logs if
94  * necessary.
95  */
logOpenSSLError(const char * location)96 static void logOpenSSLError(const char* location) {
97     int error = ERR_get_error();
98 
99     if (error != 0) {
100         char message[256];
101         ERR_error_string_n(error, message, sizeof(message));
102         ALOGE("OpenSSL error in %s %d: %s", location, error, message);
103     }
104 
105     ERR_clear_error();
106     ERR_remove_thread_state(NULL);
107 }
108 
wrap_key(EVP_PKEY * pkey,int type,uint8_t ** keyBlob,size_t * keyBlobLength)109 static int wrap_key(EVP_PKEY* pkey, int type, uint8_t** keyBlob, size_t* keyBlobLength) {
110     /*
111      * Find the length of each size. Public key is not needed anymore
112      * but must be kept for alignment purposes.
113      */
114     int publicLen = 0;
115     int privateLen = i2d_PrivateKey(pkey, NULL);
116 
117     if (privateLen <= 0) {
118         ALOGE("private key size was too big");
119         return -1;
120     }
121 
122     /* int type + int size + private key data + int size + public key data */
123     *keyBlobLength = get_softkey_header_size() + sizeof(type) + sizeof(publicLen) + privateLen +
124                      sizeof(privateLen) + publicLen;
125 
126     // derData will be returned to the caller, so allocate it with malloc.
127     UniquePtr<unsigned char, Malloc_Free> derData(
128         static_cast<unsigned char*>(malloc(*keyBlobLength)));
129     if (derData.get() == NULL) {
130         ALOGE("could not allocate memory for key blob");
131         return -1;
132     }
133     unsigned char* p = derData.get();
134 
135     /* Write the magic value for software keys. */
136     p = add_softkey_header(p, *keyBlobLength);
137 
138     /* Write key type to allocated buffer */
139     for (int i = sizeof(type) - 1; i >= 0; i--) {
140         *p++ = (type >> (8 * i)) & 0xFF;
141     }
142 
143     /* Write public key to allocated buffer */
144     for (int i = sizeof(publicLen) - 1; i >= 0; i--) {
145         *p++ = (publicLen >> (8 * i)) & 0xFF;
146     }
147 
148     /* Write private key to allocated buffer */
149     for (int i = sizeof(privateLen) - 1; i >= 0; i--) {
150         *p++ = (privateLen >> (8 * i)) & 0xFF;
151     }
152     if (i2d_PrivateKey(pkey, &p) != privateLen) {
153         logOpenSSLError("wrap_key");
154         return -1;
155     }
156 
157     *keyBlob = derData.release();
158 
159     return 0;
160 }
161 
unwrap_key(const uint8_t * keyBlob,const size_t keyBlobLength)162 static EVP_PKEY* unwrap_key(const uint8_t* keyBlob, const size_t keyBlobLength) {
163     long publicLen = 0;
164     long privateLen = 0;
165     const uint8_t* p = keyBlob;
166     const uint8_t* const end = keyBlob + keyBlobLength;
167 
168     if (keyBlob == NULL) {
169         ALOGE("supplied key blob was NULL");
170         return NULL;
171     }
172 
173     int type = 0;
174     if (keyBlobLength < (get_softkey_header_size() + sizeof(type) + sizeof(publicLen) + 1 +
175                          sizeof(privateLen) + 1)) {
176         ALOGE("key blob appears to be truncated");
177         return NULL;
178     }
179 
180     if (!is_softkey(p, keyBlobLength)) {
181         ALOGE("cannot read key; it was not made by this keymaster");
182         return NULL;
183     }
184     p += get_softkey_header_size();
185 
186     for (size_t i = 0; i < sizeof(type); i++) {
187         type = (type << 8) | *p++;
188     }
189 
190     for (size_t i = 0; i < sizeof(type); i++) {
191         publicLen = (publicLen << 8) | *p++;
192     }
193     if (p + publicLen > end) {
194         ALOGE("public key length encoding error: size=%ld, end=%td", publicLen, end - p);
195         return NULL;
196     }
197 
198     p += publicLen;
199     if (end - p < 2) {
200         ALOGE("private key truncated");
201         return NULL;
202     }
203     for (size_t i = 0; i < sizeof(type); i++) {
204         privateLen = (privateLen << 8) | *p++;
205     }
206     if (p + privateLen > end) {
207         ALOGE("private key length encoding error: size=%ld, end=%td", privateLen, end - p);
208         return NULL;
209     }
210 
211     Unique_EVP_PKEY pkey(d2i_PrivateKey(type, nullptr, &p, privateLen));
212     if (pkey.get() == NULL) {
213         logOpenSSLError("unwrap_key");
214         return NULL;
215     }
216 
217     return pkey.release();
218 }
219 
generate_dsa_keypair(EVP_PKEY * pkey,const keymaster_dsa_keygen_params_t * dsa_params)220 static int generate_dsa_keypair(EVP_PKEY* pkey, const keymaster_dsa_keygen_params_t* dsa_params) {
221     if (dsa_params->key_size < 512) {
222         ALOGI("Requested DSA key size is too small (<512)");
223         return -1;
224     }
225 
226     Unique_DSA dsa(DSA_new());
227 
228     if (dsa_params->generator_len == 0 || dsa_params->prime_p_len == 0 ||
229         dsa_params->prime_q_len == 0 || dsa_params->generator == NULL ||
230         dsa_params->prime_p == NULL || dsa_params->prime_q == NULL) {
231         if (DSA_generate_parameters_ex(dsa.get(), dsa_params->key_size, NULL, 0, NULL, NULL,
232                                        NULL) != 1) {
233             logOpenSSLError("generate_dsa_keypair");
234             return -1;
235         }
236     } else {
237         dsa->g = BN_bin2bn(dsa_params->generator, dsa_params->generator_len, NULL);
238         if (dsa->g == NULL) {
239             logOpenSSLError("generate_dsa_keypair");
240             return -1;
241         }
242 
243         dsa->p = BN_bin2bn(dsa_params->prime_p, dsa_params->prime_p_len, NULL);
244         if (dsa->p == NULL) {
245             logOpenSSLError("generate_dsa_keypair");
246             return -1;
247         }
248 
249         dsa->q = BN_bin2bn(dsa_params->prime_q, dsa_params->prime_q_len, NULL);
250         if (dsa->q == NULL) {
251             logOpenSSLError("generate_dsa_keypair");
252             return -1;
253         }
254     }
255 
256     if (DSA_generate_key(dsa.get()) != 1) {
257         logOpenSSLError("generate_dsa_keypair");
258         return -1;
259     }
260 
261     if (EVP_PKEY_assign_DSA(pkey, dsa.get()) == 0) {
262         logOpenSSLError("generate_dsa_keypair");
263         return -1;
264     }
265     release_because_ownership_transferred(dsa);
266 
267     return 0;
268 }
269 
generate_ec_keypair(EVP_PKEY * pkey,const keymaster_ec_keygen_params_t * ec_params)270 static int generate_ec_keypair(EVP_PKEY* pkey, const keymaster_ec_keygen_params_t* ec_params) {
271     Unique_EC_GROUP group;
272     switch (ec_params->field_size) {
273     case 224:
274         group.reset(EC_GROUP_new_by_curve_name(NID_secp224r1));
275         break;
276     case 256:
277         group.reset(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
278         break;
279     case 384:
280         group.reset(EC_GROUP_new_by_curve_name(NID_secp384r1));
281         break;
282     case 521:
283         group.reset(EC_GROUP_new_by_curve_name(NID_secp521r1));
284         break;
285     default:
286         break;
287     }
288 
289     if (group.get() == NULL) {
290         logOpenSSLError("generate_ec_keypair");
291         return -1;
292     }
293 
294 #if !defined(OPENSSL_IS_BORINGSSL)
295     EC_GROUP_set_point_conversion_form(group.get(), POINT_CONVERSION_UNCOMPRESSED);
296     EC_GROUP_set_asn1_flag(group.get(), OPENSSL_EC_NAMED_CURVE);
297 #endif
298 
299     /* initialize EC key */
300     Unique_EC_KEY eckey(EC_KEY_new());
301     if (eckey.get() == NULL) {
302         logOpenSSLError("generate_ec_keypair");
303         return -1;
304     }
305 
306     if (EC_KEY_set_group(eckey.get(), group.get()) != 1) {
307         logOpenSSLError("generate_ec_keypair");
308         return -1;
309     }
310 
311     if (EC_KEY_generate_key(eckey.get()) != 1 || EC_KEY_check_key(eckey.get()) < 0) {
312         logOpenSSLError("generate_ec_keypair");
313         return -1;
314     }
315 
316     if (EVP_PKEY_assign_EC_KEY(pkey, eckey.get()) == 0) {
317         logOpenSSLError("generate_ec_keypair");
318         return -1;
319     }
320     release_because_ownership_transferred(eckey);
321 
322     return 0;
323 }
324 
generate_rsa_keypair(EVP_PKEY * pkey,const keymaster_rsa_keygen_params_t * rsa_params)325 static int generate_rsa_keypair(EVP_PKEY* pkey, const keymaster_rsa_keygen_params_t* rsa_params) {
326     Unique_BIGNUM bn(BN_new());
327     if (bn.get() == NULL) {
328         logOpenSSLError("generate_rsa_keypair");
329         return -1;
330     }
331 
332     if (BN_set_word(bn.get(), rsa_params->public_exponent) == 0) {
333         logOpenSSLError("generate_rsa_keypair");
334         return -1;
335     }
336 
337     /* initialize RSA */
338     Unique_RSA rsa(RSA_new());
339     if (rsa.get() == NULL) {
340         logOpenSSLError("generate_rsa_keypair");
341         return -1;
342     }
343 
344     if (!RSA_generate_key_ex(rsa.get(), rsa_params->modulus_size, bn.get(), NULL) ||
345         RSA_check_key(rsa.get()) < 0) {
346         logOpenSSLError("generate_rsa_keypair");
347         return -1;
348     }
349 
350     if (EVP_PKEY_assign_RSA(pkey, rsa.get()) == 0) {
351         logOpenSSLError("generate_rsa_keypair");
352         return -1;
353     }
354     release_because_ownership_transferred(rsa);
355 
356     return 0;
357 }
358 
openssl_generate_keypair(const keymaster0_device_t *,const keymaster_keypair_t key_type,const void * key_params,uint8_t ** keyBlob,size_t * keyBlobLength)359 __attribute__((visibility("default"))) int openssl_generate_keypair(
360     const keymaster0_device_t*, const keymaster_keypair_t key_type, const void* key_params,
361     uint8_t** keyBlob, size_t* keyBlobLength) {
362     Unique_EVP_PKEY pkey(EVP_PKEY_new());
363     if (pkey.get() == NULL) {
364         logOpenSSLError("openssl_generate_keypair");
365         return -1;
366     }
367 
368     if (key_params == NULL) {
369         ALOGW("key_params == null");
370         return -1;
371     } else if (key_type == TYPE_DSA) {
372         const keymaster_dsa_keygen_params_t* dsa_params =
373             (const keymaster_dsa_keygen_params_t*)key_params;
374         generate_dsa_keypair(pkey.get(), dsa_params);
375     } else if (key_type == TYPE_EC) {
376         const keymaster_ec_keygen_params_t* ec_params =
377             (const keymaster_ec_keygen_params_t*)key_params;
378         generate_ec_keypair(pkey.get(), ec_params);
379     } else if (key_type == TYPE_RSA) {
380         const keymaster_rsa_keygen_params_t* rsa_params =
381             (const keymaster_rsa_keygen_params_t*)key_params;
382         generate_rsa_keypair(pkey.get(), rsa_params);
383     } else {
384         ALOGW("Unsupported key type %d", key_type);
385         return -1;
386     }
387 
388     if (wrap_key(pkey.get(), EVP_PKEY_type(pkey->type), keyBlob, keyBlobLength)) {
389         return -1;
390     }
391 
392     return 0;
393 }
394 
openssl_import_keypair(const keymaster0_device_t *,const uint8_t * key,const size_t key_length,uint8_t ** key_blob,size_t * key_blob_length)395 __attribute__((visibility("default"))) int openssl_import_keypair(const keymaster0_device_t*,
396                                                                   const uint8_t* key,
397                                                                   const size_t key_length,
398                                                                   uint8_t** key_blob,
399                                                                   size_t* key_blob_length) {
400     if (key == NULL) {
401         ALOGW("input key == NULL");
402         return -1;
403     } else if (key_blob == NULL || key_blob_length == NULL) {
404         ALOGW("output key blob or length == NULL");
405         return -1;
406     }
407 
408     Unique_PKCS8_PRIV_KEY_INFO pkcs8(d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, key_length));
409     if (pkcs8.get() == NULL) {
410         logOpenSSLError("openssl_import_keypair");
411         return -1;
412     }
413 
414     /* assign to EVP */
415     Unique_EVP_PKEY pkey(EVP_PKCS82PKEY(pkcs8.get()));
416     if (pkey.get() == NULL) {
417         logOpenSSLError("openssl_import_keypair");
418         return -1;
419     }
420 
421     if (wrap_key(pkey.get(), EVP_PKEY_type(pkey->type), key_blob, key_blob_length)) {
422         return -1;
423     }
424 
425     return 0;
426 }
427 
openssl_get_keypair_public(const keymaster0_device_t *,const uint8_t * key_blob,const size_t key_blob_length,uint8_t ** x509_data,size_t * x509_data_length)428 __attribute__((visibility("default"))) int openssl_get_keypair_public(const keymaster0_device_t*,
429                                                                       const uint8_t* key_blob,
430                                                                       const size_t key_blob_length,
431                                                                       uint8_t** x509_data,
432                                                                       size_t* x509_data_length) {
433     if (x509_data == NULL || x509_data_length == NULL) {
434         ALOGW("output public key buffer == NULL");
435         return -1;
436     }
437 
438     Unique_EVP_PKEY pkey(unwrap_key(key_blob, key_blob_length));
439     if (pkey.get() == NULL) {
440         return -1;
441     }
442 
443     int len = i2d_PUBKEY(pkey.get(), NULL);
444     if (len <= 0) {
445         logOpenSSLError("openssl_get_keypair_public");
446         return -1;
447     }
448 
449     UniquePtr<uint8_t, Malloc_Free> key(static_cast<uint8_t*>(malloc(len)));
450     if (key.get() == NULL) {
451         ALOGE("Could not allocate memory for public key data");
452         return -1;
453     }
454 
455     unsigned char* tmp = reinterpret_cast<unsigned char*>(key.get());
456     if (i2d_PUBKEY(pkey.get(), &tmp) != len) {
457         logOpenSSLError("openssl_get_keypair_public");
458         return -1;
459     }
460 
461     ALOGV("Length of x509 data is %d", len);
462     *x509_data_length = len;
463     *x509_data = key.release();
464 
465     return 0;
466 }
467 
sign_dsa(EVP_PKEY * pkey,keymaster_dsa_sign_params_t * sign_params,const uint8_t * data,const size_t dataLength,uint8_t ** signedData,size_t * signedDataLength)468 static int sign_dsa(EVP_PKEY* pkey, keymaster_dsa_sign_params_t* sign_params, const uint8_t* data,
469                     const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) {
470     if (sign_params->digest_type != DIGEST_NONE) {
471         ALOGW("Cannot handle digest type %d", sign_params->digest_type);
472         return -1;
473     }
474 
475     Unique_DSA dsa(EVP_PKEY_get1_DSA(pkey));
476     if (dsa.get() == NULL) {
477         logOpenSSLError("openssl_sign_dsa");
478         return -1;
479     }
480 
481     unsigned int dsaSize = DSA_size(dsa.get());
482     UniquePtr<uint8_t, Malloc_Free> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(dsaSize)));
483     if (signedDataPtr.get() == NULL) {
484         logOpenSSLError("openssl_sign_dsa");
485         return -1;
486     }
487 
488     unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get());
489     if (DSA_sign(0, data, dataLength, tmp, &dsaSize, dsa.get()) <= 0) {
490         logOpenSSLError("openssl_sign_dsa");
491         return -1;
492     }
493 
494     *signedDataLength = dsaSize;
495     *signedData = signedDataPtr.release();
496 
497     return 0;
498 }
499 
sign_ec(EVP_PKEY * pkey,keymaster_ec_sign_params_t * sign_params,const uint8_t * data,const size_t dataLength,uint8_t ** signedData,size_t * signedDataLength)500 static int sign_ec(EVP_PKEY* pkey, keymaster_ec_sign_params_t* sign_params, const uint8_t* data,
501                    const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) {
502     if (sign_params->digest_type != DIGEST_NONE) {
503         ALOGW("Cannot handle digest type %d", sign_params->digest_type);
504         return -1;
505     }
506 
507     Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
508     if (eckey.get() == NULL) {
509         logOpenSSLError("openssl_sign_ec");
510         return -1;
511     }
512 
513     unsigned int ecdsaSize = ECDSA_size(eckey.get());
514     UniquePtr<uint8_t, Malloc_Free> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(ecdsaSize)));
515     if (signedDataPtr.get() == NULL) {
516         logOpenSSLError("openssl_sign_ec");
517         return -1;
518     }
519 
520     unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get());
521     if (ECDSA_sign(0, data, dataLength, tmp, &ecdsaSize, eckey.get()) <= 0) {
522         logOpenSSLError("openssl_sign_ec");
523         return -1;
524     }
525 
526     *signedDataLength = ecdsaSize;
527     *signedData = signedDataPtr.release();
528 
529     return 0;
530 }
531 
sign_rsa(EVP_PKEY * pkey,keymaster_rsa_sign_params_t * sign_params,const uint8_t * data,const size_t dataLength,uint8_t ** signedData,size_t * signedDataLength)532 static int sign_rsa(EVP_PKEY* pkey, keymaster_rsa_sign_params_t* sign_params, const uint8_t* data,
533                     const size_t dataLength, uint8_t** signedData, size_t* signedDataLength) {
534     if (sign_params->digest_type != DIGEST_NONE) {
535         ALOGW("Cannot handle digest type %d", sign_params->digest_type);
536         return -1;
537     } else if (sign_params->padding_type != PADDING_NONE) {
538         ALOGW("Cannot handle padding type %d", sign_params->padding_type);
539         return -1;
540     }
541 
542     Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
543     if (rsa.get() == NULL) {
544         logOpenSSLError("openssl_sign_rsa");
545         return -1;
546     }
547 
548     UniquePtr<uint8_t, Malloc_Free> signedDataPtr(reinterpret_cast<uint8_t*>(malloc(dataLength)));
549     if (signedDataPtr.get() == NULL) {
550         logOpenSSLError("openssl_sign_rsa");
551         return -1;
552     }
553 
554     unsigned char* tmp = reinterpret_cast<unsigned char*>(signedDataPtr.get());
555     if (RSA_private_encrypt(dataLength, data, tmp, rsa.get(), RSA_NO_PADDING) <= 0) {
556         logOpenSSLError("openssl_sign_rsa");
557         return -1;
558     }
559 
560     *signedDataLength = dataLength;
561     *signedData = signedDataPtr.release();
562 
563     return 0;
564 }
565 
openssl_sign_data(const keymaster0_device_t *,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)566 __attribute__((visibility("default"))) int openssl_sign_data(
567     const keymaster0_device_t*, const void* params, const uint8_t* keyBlob,
568     const size_t keyBlobLength, const uint8_t* data, const size_t dataLength, uint8_t** signedData,
569     size_t* signedDataLength) {
570     if (data == NULL) {
571         ALOGW("input data to sign == NULL");
572         return -1;
573     } else if (signedData == NULL || signedDataLength == NULL) {
574         ALOGW("output signature buffer == NULL");
575         return -1;
576     }
577 
578     Unique_EVP_PKEY pkey(unwrap_key(keyBlob, keyBlobLength));
579     if (pkey.get() == NULL) {
580         return -1;
581     }
582 
583     int type = EVP_PKEY_type(pkey->type);
584     if (type == EVP_PKEY_DSA) {
585         const keymaster_dsa_sign_params_t* sign_params =
586             reinterpret_cast<const keymaster_dsa_sign_params_t*>(params);
587         return sign_dsa(pkey.get(), const_cast<keymaster_dsa_sign_params_t*>(sign_params), data,
588                         dataLength, signedData, signedDataLength);
589     } else if (type == EVP_PKEY_EC) {
590         const keymaster_ec_sign_params_t* sign_params =
591             reinterpret_cast<const keymaster_ec_sign_params_t*>(params);
592         return sign_ec(pkey.get(), const_cast<keymaster_ec_sign_params_t*>(sign_params), data,
593                        dataLength, signedData, signedDataLength);
594     } else if (type == EVP_PKEY_RSA) {
595         const keymaster_rsa_sign_params_t* sign_params =
596             reinterpret_cast<const keymaster_rsa_sign_params_t*>(params);
597         return sign_rsa(pkey.get(), const_cast<keymaster_rsa_sign_params_t*>(sign_params), data,
598                         dataLength, signedData, signedDataLength);
599     } else {
600         ALOGW("Unsupported key type");
601         return -1;
602     }
603 }
604 
verify_dsa(EVP_PKEY * pkey,keymaster_dsa_sign_params_t * sign_params,const uint8_t * signedData,const size_t signedDataLength,const uint8_t * signature,const size_t signatureLength)605 static int verify_dsa(EVP_PKEY* pkey, keymaster_dsa_sign_params_t* sign_params,
606                       const uint8_t* signedData, const size_t signedDataLength,
607                       const uint8_t* signature, const size_t signatureLength) {
608     if (sign_params->digest_type != DIGEST_NONE) {
609         ALOGW("Cannot handle digest type %d", sign_params->digest_type);
610         return -1;
611     }
612 
613     Unique_DSA dsa(EVP_PKEY_get1_DSA(pkey));
614     if (dsa.get() == NULL) {
615         logOpenSSLError("openssl_verify_dsa");
616         return -1;
617     }
618 
619     if (DSA_verify(0, signedData, signedDataLength, signature, signatureLength, dsa.get()) <= 0) {
620         logOpenSSLError("openssl_verify_dsa");
621         return -1;
622     }
623 
624     return 0;
625 }
626 
verify_ec(EVP_PKEY * pkey,keymaster_ec_sign_params_t * sign_params,const uint8_t * signedData,const size_t signedDataLength,const uint8_t * signature,const size_t signatureLength)627 static int verify_ec(EVP_PKEY* pkey, keymaster_ec_sign_params_t* sign_params,
628                      const uint8_t* signedData, const size_t signedDataLength,
629                      const uint8_t* signature, const size_t signatureLength) {
630     if (sign_params->digest_type != DIGEST_NONE) {
631         ALOGW("Cannot handle digest type %d", sign_params->digest_type);
632         return -1;
633     }
634 
635     Unique_EC_KEY eckey(EVP_PKEY_get1_EC_KEY(pkey));
636     if (eckey.get() == NULL) {
637         logOpenSSLError("openssl_verify_ec");
638         return -1;
639     }
640 
641     if (ECDSA_verify(0, signedData, signedDataLength, signature, signatureLength, eckey.get()) <=
642         0) {
643         logOpenSSLError("openssl_verify_ec");
644         return -1;
645     }
646 
647     return 0;
648 }
649 
verify_rsa(EVP_PKEY * pkey,keymaster_rsa_sign_params_t * sign_params,const uint8_t * signedData,const size_t signedDataLength,const uint8_t * signature,const size_t signatureLength)650 static int verify_rsa(EVP_PKEY* pkey, keymaster_rsa_sign_params_t* sign_params,
651                       const uint8_t* signedData, const size_t signedDataLength,
652                       const uint8_t* signature, const size_t signatureLength) {
653     if (sign_params->digest_type != DIGEST_NONE) {
654         ALOGW("Cannot handle digest type %d", sign_params->digest_type);
655         return -1;
656     } else if (sign_params->padding_type != PADDING_NONE) {
657         ALOGW("Cannot handle padding type %d", sign_params->padding_type);
658         return -1;
659     } else if (signatureLength != signedDataLength) {
660         ALOGW("signed data length must be signature length");
661         return -1;
662     }
663 
664     Unique_RSA rsa(EVP_PKEY_get1_RSA(pkey));
665     if (rsa.get() == NULL) {
666         logOpenSSLError("openssl_verify_data");
667         return -1;
668     }
669 
670     UniquePtr<uint8_t[]> dataPtr(new uint8_t[signedDataLength]);
671     if (dataPtr.get() == NULL) {
672         logOpenSSLError("openssl_verify_data");
673         return -1;
674     }
675 
676     unsigned char* tmp = reinterpret_cast<unsigned char*>(dataPtr.get());
677     if (!RSA_public_decrypt(signatureLength, signature, tmp, rsa.get(), RSA_NO_PADDING)) {
678         logOpenSSLError("openssl_verify_data");
679         return -1;
680     }
681 
682     int result = 0;
683     for (size_t i = 0; i < signedDataLength; i++) {
684         result |= tmp[i] ^ signedData[i];
685     }
686 
687     return result == 0 ? 0 : -1;
688 }
689 
openssl_verify_data(const keymaster0_device_t *,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)690 __attribute__((visibility("default"))) int openssl_verify_data(
691     const keymaster0_device_t*, const void* params, const uint8_t* keyBlob,
692     const size_t keyBlobLength, const uint8_t* signedData, const size_t signedDataLength,
693     const uint8_t* signature, const size_t signatureLength) {
694     if (signedData == NULL || signature == NULL) {
695         ALOGW("data or signature buffers == NULL");
696         return -1;
697     }
698 
699     Unique_EVP_PKEY pkey(unwrap_key(keyBlob, keyBlobLength));
700     if (pkey.get() == NULL) {
701         return -1;
702     }
703 
704     int type = EVP_PKEY_type(pkey->type);
705     if (type == EVP_PKEY_DSA) {
706         const keymaster_dsa_sign_params_t* sign_params =
707             reinterpret_cast<const keymaster_dsa_sign_params_t*>(params);
708         return verify_dsa(pkey.get(), const_cast<keymaster_dsa_sign_params_t*>(sign_params),
709                           signedData, signedDataLength, signature, signatureLength);
710     } else if (type == EVP_PKEY_RSA) {
711         const keymaster_rsa_sign_params_t* sign_params =
712             reinterpret_cast<const keymaster_rsa_sign_params_t*>(params);
713         return verify_rsa(pkey.get(), const_cast<keymaster_rsa_sign_params_t*>(sign_params),
714                           signedData, signedDataLength, signature, signatureLength);
715     } else if (type == EVP_PKEY_EC) {
716         const keymaster_ec_sign_params_t* sign_params =
717             reinterpret_cast<const keymaster_ec_sign_params_t*>(params);
718         return verify_ec(pkey.get(), const_cast<keymaster_ec_sign_params_t*>(sign_params),
719                          signedData, signedDataLength, signature, signatureLength);
720     } else {
721         ALOGW("Unsupported key type %d", type);
722         return -1;
723     }
724 }
725 
726 /* Close an opened OpenSSL instance */
openssl_close(hw_device_t * dev)727 static int openssl_close(hw_device_t* dev) {
728     delete dev;
729     return 0;
730 }
731 
732 /*
733  * Generic device handling
734  */
openssl_open(const hw_module_t * module,const char * name,hw_device_t ** device)735 __attribute__((visibility("default"))) int openssl_open(const hw_module_t* module, const char* name,
736                                                         hw_device_t** device) {
737     if (strcmp(name, KEYSTORE_KEYMASTER) != 0)
738         return -EINVAL;
739 
740     Unique_keymaster_device_t dev(new keymaster0_device_t);
741     if (dev.get() == NULL)
742         return -ENOMEM;
743 
744     dev->common.tag = HARDWARE_DEVICE_TAG;
745     dev->common.version = 1;
746     dev->common.module = (struct hw_module_t*)module;
747     dev->common.close = openssl_close;
748 
749     dev->flags = KEYMASTER_SOFTWARE_ONLY | KEYMASTER_BLOBS_ARE_STANDALONE | KEYMASTER_SUPPORTS_DSA |
750                  KEYMASTER_SUPPORTS_EC;
751 
752     dev->generate_keypair = openssl_generate_keypair;
753     dev->import_keypair = openssl_import_keypair;
754     dev->get_keypair_public = openssl_get_keypair_public;
755     dev->delete_keypair = NULL;
756     dev->delete_all = NULL;
757     dev->sign_data = openssl_sign_data;
758     dev->verify_data = openssl_verify_data;
759 
760     ERR_load_crypto_strings();
761     ERR_load_BIO_strings();
762 
763     *device = reinterpret_cast<hw_device_t*>(dev.release());
764 
765     return 0;
766 }
767 
768 static struct hw_module_methods_t keystore_module_methods = {
769     .open = openssl_open,
770 };
771 
772 struct keystore_module softkeymaster_module __attribute__((visibility("default"))) = {
773     .common =
774         {
775          .tag = HARDWARE_MODULE_TAG,
776          .module_api_version = KEYMASTER_MODULE_API_VERSION_0_2,
777          .hal_api_version = HARDWARE_HAL_API_VERSION,
778          .id = KEYSTORE_HARDWARE_MODULE_ID,
779          .name = "Keymaster OpenSSL HAL",
780          .author = "The Android Open Source Project",
781          .methods = &keystore_module_methods,
782          .dso = 0,
783          .reserved = {},
784         },
785 };
786