1 /*
2  * Copyright 2015 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 
17 #include "keymaster0_engine.h"
18 
19 #include <assert.h>
20 #include <string.h>
21 
22 #include <memory>
23 
24 #define LOG_TAG "Keymaster0Engine"
25 #include <cutils/log.h>
26 
27 #include "keymaster/android_keymaster_utils.h"
28 
29 #include <openssl/bn.h>
30 #include <openssl/ec_key.h>
31 #include <openssl/ecdsa.h>
32 
33 #include "openssl_utils.h"
34 
35 using std::shared_ptr;
36 using std::unique_ptr;
37 
38 namespace keymaster {
39 
40 Keymaster0Engine* Keymaster0Engine::instance_ = nullptr;
41 
Keymaster0Engine(const keymaster0_device_t * keymaster0_device)42 Keymaster0Engine::Keymaster0Engine(const keymaster0_device_t* keymaster0_device)
43     : keymaster0_device_(keymaster0_device), engine_(ENGINE_new()), supports_ec_(false) {
44     assert(!instance_);
45     instance_ = this;
46 
47     rsa_index_ = RSA_get_ex_new_index(0 /* argl */, NULL /* argp */, NULL /* new_func */,
48                                       keyblob_dup, keyblob_free);
49     ec_key_index_ = EC_KEY_get_ex_new_index(0 /* argl */, NULL /* argp */, NULL /* new_func */,
50                                             keyblob_dup, keyblob_free);
51 
52     memset(&rsa_method_, 0, sizeof(rsa_method_));
53     rsa_method_.common.is_static = 1;
54     rsa_method_.private_transform = Keymaster0Engine::rsa_private_transform;
55     rsa_method_.flags = RSA_FLAG_OPAQUE;
56 
57     ENGINE_set_RSA_method(engine_, &rsa_method_, sizeof(rsa_method_));
58 
59     if ((keymaster0_device_->flags & KEYMASTER_SUPPORTS_EC) != 0) {
60         supports_ec_ = true;
61 
62         memset(&ecdsa_method_, 0, sizeof(ecdsa_method_));
63         ecdsa_method_.common.is_static = 1;
64         ecdsa_method_.sign = Keymaster0Engine::ecdsa_sign;
65         ecdsa_method_.flags = ECDSA_FLAG_OPAQUE;
66 
67         ENGINE_set_ECDSA_method(engine_, &ecdsa_method_, sizeof(ecdsa_method_));
68     }
69 }
70 
~Keymaster0Engine()71 Keymaster0Engine::~Keymaster0Engine() {
72     if (keymaster0_device_)
73         keymaster0_device_->common.close(
74             reinterpret_cast<hw_device_t*>(const_cast<keymaster0_device_t*>(keymaster0_device_)));
75     ENGINE_free(engine_);
76     instance_ = nullptr;
77 }
78 
GenerateRsaKey(uint64_t public_exponent,uint32_t public_modulus,KeymasterKeyBlob * key_material) const79 bool Keymaster0Engine::GenerateRsaKey(uint64_t public_exponent, uint32_t public_modulus,
80                                       KeymasterKeyBlob* key_material) const {
81     assert(key_material);
82     keymaster_rsa_keygen_params_t params;
83     params.public_exponent = public_exponent;
84     params.modulus_size = public_modulus;
85 
86     uint8_t* key_blob = 0;
87     if (keymaster0_device_->generate_keypair(keymaster0_device_, TYPE_RSA, &params, &key_blob,
88                                              &key_material->key_material_size) < 0) {
89         ALOGE("Error generating RSA key pair with keymaster0 device");
90         return false;
91     }
92     unique_ptr<uint8_t, Malloc_Delete> key_blob_deleter(key_blob);
93     key_material->key_material = dup_buffer(key_blob, key_material->key_material_size);
94     return true;
95 }
96 
GenerateEcKey(uint32_t key_size,KeymasterKeyBlob * key_material) const97 bool Keymaster0Engine::GenerateEcKey(uint32_t key_size, KeymasterKeyBlob* key_material) const {
98     assert(key_material);
99     keymaster_ec_keygen_params_t params;
100     params.field_size = key_size;
101 
102     uint8_t* key_blob = 0;
103     if (keymaster0_device_->generate_keypair(keymaster0_device_, TYPE_EC, &params, &key_blob,
104                                              &key_material->key_material_size) < 0) {
105         ALOGE("Error generating EC key pair with keymaster0 device");
106         return false;
107     }
108     unique_ptr<uint8_t, Malloc_Delete> key_blob_deleter(key_blob);
109     key_material->key_material = dup_buffer(key_blob, key_material->key_material_size);
110     return true;
111 }
112 
ImportKey(keymaster_key_format_t key_format,const KeymasterKeyBlob & to_import,KeymasterKeyBlob * imported_key) const113 bool Keymaster0Engine::ImportKey(keymaster_key_format_t key_format,
114                                  const KeymasterKeyBlob& to_import,
115                                  KeymasterKeyBlob* imported_key) const {
116     assert(imported_key);
117     if (key_format != KM_KEY_FORMAT_PKCS8)
118         return false;
119 
120     uint8_t* key_blob = 0;
121     if (keymaster0_device_->import_keypair(keymaster0_device_, to_import.key_material,
122                                            to_import.key_material_size, &key_blob,
123                                            &imported_key->key_material_size) < 0) {
124         ALOGW("Error importing keypair with keymaster0 device");
125         return false;
126     }
127     unique_ptr<uint8_t, Malloc_Delete> key_blob_deleter(key_blob);
128     imported_key->key_material = dup_buffer(key_blob, imported_key->key_material_size);
129     return true;
130 }
131 
DeleteKey(const KeymasterKeyBlob & blob) const132 bool Keymaster0Engine::DeleteKey(const KeymasterKeyBlob& blob) const {
133     if (!keymaster0_device_->delete_keypair)
134         return true;
135     return (keymaster0_device_->delete_keypair(keymaster0_device_, blob.key_material,
136                                                blob.key_material_size) == 0);
137 }
138 
DeleteAllKeys() const139 bool Keymaster0Engine::DeleteAllKeys() const {
140     if (!keymaster0_device_->delete_all)
141         return true;
142     return (keymaster0_device_->delete_all(keymaster0_device_) == 0);
143 }
144 
duplicate_blob(const uint8_t * key_data,size_t key_data_size)145 static keymaster_key_blob_t* duplicate_blob(const uint8_t* key_data, size_t key_data_size) {
146     unique_ptr<uint8_t[]> key_material_copy(dup_buffer(key_data, key_data_size));
147     if (!key_material_copy)
148         return nullptr;
149 
150     unique_ptr<keymaster_key_blob_t> blob_copy(new (std::nothrow) keymaster_key_blob_t);
151     if (!blob_copy.get())
152         return nullptr;
153     blob_copy->key_material_size = key_data_size;
154     blob_copy->key_material = key_material_copy.release();
155     return blob_copy.release();
156 }
157 
duplicate_blob(const keymaster_key_blob_t & blob)158 inline keymaster_key_blob_t* duplicate_blob(const keymaster_key_blob_t& blob) {
159     return duplicate_blob(blob.key_material, blob.key_material_size);
160 }
161 
BlobToRsaKey(const KeymasterKeyBlob & blob) const162 RSA* Keymaster0Engine::BlobToRsaKey(const KeymasterKeyBlob& blob) const {
163     // Create new RSA key (with engine methods) and insert blob
164     unique_ptr<RSA, RSA_Delete> rsa(RSA_new_method(engine_));
165     if (!rsa)
166         return nullptr;
167 
168     keymaster_key_blob_t* blob_copy = duplicate_blob(blob);
169     if (!blob_copy->key_material || !RSA_set_ex_data(rsa.get(), rsa_index_, blob_copy))
170         return nullptr;
171 
172     // Copy public key into new RSA key
173     unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(GetKeymaster0PublicKey(blob));
174     if (!pkey)
175         return nullptr;
176     unique_ptr<RSA, RSA_Delete> public_rsa(EVP_PKEY_get1_RSA(pkey.get()));
177     if (!public_rsa)
178         return nullptr;
179     rsa->n = BN_dup(public_rsa->n);
180     rsa->e = BN_dup(public_rsa->e);
181     if (!rsa->n || !rsa->e)
182         return nullptr;
183 
184     return rsa.release();
185 }
186 
BlobToEcKey(const KeymasterKeyBlob & blob) const187 EC_KEY* Keymaster0Engine::BlobToEcKey(const KeymasterKeyBlob& blob) const {
188     // Create new EC key (with engine methods) and insert blob
189     unique_ptr<EC_KEY, EC_KEY_Delete> ec_key(EC_KEY_new_method(engine_));
190     if (!ec_key)
191         return nullptr;
192 
193     keymaster_key_blob_t* blob_copy = duplicate_blob(blob);
194     if (!blob_copy->key_material || !EC_KEY_set_ex_data(ec_key.get(), ec_key_index_, blob_copy))
195         return nullptr;
196 
197     // Copy public key into new EC key
198     unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(GetKeymaster0PublicKey(blob));
199     if (!pkey)
200         return nullptr;
201 
202     unique_ptr<EC_KEY, EC_KEY_Delete> public_ec_key(EVP_PKEY_get1_EC_KEY(pkey.get()));
203     if (!public_ec_key)
204         return nullptr;
205 
206     if (!EC_KEY_set_group(ec_key.get(), EC_KEY_get0_group(public_ec_key.get())) ||
207         !EC_KEY_set_public_key(ec_key.get(), EC_KEY_get0_public_key(public_ec_key.get())))
208         return nullptr;
209 
210     return ec_key.release();
211 }
212 
RsaKeyToBlob(const RSA * rsa) const213 const keymaster_key_blob_t* Keymaster0Engine::RsaKeyToBlob(const RSA* rsa) const {
214     return reinterpret_cast<keymaster_key_blob_t*>(RSA_get_ex_data(rsa, rsa_index_));
215 }
216 
EcKeyToBlob(const EC_KEY * ec_key) const217 const keymaster_key_blob_t* Keymaster0Engine::EcKeyToBlob(const EC_KEY* ec_key) const {
218     return reinterpret_cast<keymaster_key_blob_t*>(EC_KEY_get_ex_data(ec_key, ec_key_index_));
219 }
220 
221 /* static */
keyblob_dup(CRYPTO_EX_DATA *,const CRYPTO_EX_DATA *,void ** from_d,int,long,void *)222 int Keymaster0Engine::keyblob_dup(CRYPTO_EX_DATA* /* to */, const CRYPTO_EX_DATA* /* from */,
223                                   void** from_d, int /* index */, long /* argl */,
224                                   void* /* argp */) {
225     keymaster_key_blob_t* blob = reinterpret_cast<keymaster_key_blob_t*>(*from_d);
226     if (!blob)
227         return 1;
228     *from_d = duplicate_blob(*blob);
229     if (*from_d)
230         return 1;
231     return 0;
232 }
233 
234 /* static */
keyblob_free(void *,void * ptr,CRYPTO_EX_DATA *,int,long,void *)235 void Keymaster0Engine::keyblob_free(void* /* parent */, void* ptr, CRYPTO_EX_DATA* /* data */,
236                                     int /* index*/, long /* argl */, void* /* argp */) {
237     keymaster_key_blob_t* blob = reinterpret_cast<keymaster_key_blob_t*>(ptr);
238     if (blob) {
239         delete[] blob->key_material;
240         delete blob;
241     }
242 }
243 
244 /* static */
rsa_private_transform(RSA * rsa,uint8_t * out,const uint8_t * in,size_t len)245 int Keymaster0Engine::rsa_private_transform(RSA* rsa, uint8_t* out, const uint8_t* in, size_t len) {
246     ALOGV("rsa_private_transform(%p, %p, %p, %u)", rsa, out, in, (unsigned)len);
247 
248     assert(instance_);
249     return instance_->RsaPrivateTransform(rsa, out, in, len);
250 }
251 
252 /* static */
ecdsa_sign(const uint8_t * digest,size_t digest_len,uint8_t * sig,unsigned int * sig_len,EC_KEY * ec_key)253 int Keymaster0Engine::ecdsa_sign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
254                                  unsigned int* sig_len, EC_KEY* ec_key) {
255     ALOGV("ecdsa_sign(%p, %u, %p)", digest, (unsigned)digest_len, ec_key);
256     assert(instance_);
257     return instance_->EcdsaSign(digest, digest_len, sig, sig_len, ec_key);
258 }
259 
Keymaster0Sign(const void * signing_params,const keymaster_key_blob_t & blob,const uint8_t * data,const size_t data_length,unique_ptr<uint8_t[],Malloc_Delete> * signature,size_t * signature_length) const260 bool Keymaster0Engine::Keymaster0Sign(const void* signing_params, const keymaster_key_blob_t& blob,
261                                       const uint8_t* data, const size_t data_length,
262                                       unique_ptr<uint8_t[], Malloc_Delete>* signature,
263                                       size_t* signature_length) const {
264     uint8_t* signed_data;
265     int err = keymaster0_device_->sign_data(keymaster0_device_, signing_params, blob.key_material,
266                                             blob.key_material_size, data, data_length, &signed_data,
267                                             signature_length);
268     if (err < 0) {
269         ALOGE("Keymaster0 signing failed with error %d", err);
270         return false;
271     }
272 
273     signature->reset(signed_data);
274     return true;
275 }
276 
GetKeymaster0PublicKey(const KeymasterKeyBlob & blob) const277 EVP_PKEY* Keymaster0Engine::GetKeymaster0PublicKey(const KeymasterKeyBlob& blob) const {
278     uint8_t* pub_key_data;
279     size_t pub_key_data_length;
280     int err = keymaster0_device_->get_keypair_public(keymaster0_device_, blob.key_material,
281                                                      blob.key_material_size, &pub_key_data,
282                                                      &pub_key_data_length);
283     if (err < 0) {
284         ALOGE("Error %d extracting public key", err);
285         return nullptr;
286     }
287     unique_ptr<uint8_t, Malloc_Delete> pub_key(pub_key_data);
288 
289     const uint8_t* p = pub_key_data;
290     return d2i_PUBKEY(nullptr /* allocate new struct */, &p, pub_key_data_length);
291 }
292 
data_too_large_for_public_modulus(const uint8_t * data,size_t len,const RSA * rsa)293 static bool data_too_large_for_public_modulus(const uint8_t* data, size_t len, const RSA* rsa) {
294     unique_ptr<BIGNUM, BIGNUM_Delete> input_as_bn(
295         BN_bin2bn(data, len, nullptr /* allocate result */));
296     return input_as_bn && BN_ucmp(input_as_bn.get(), rsa->n) >= 0;
297 }
298 
RsaPrivateTransform(RSA * rsa,uint8_t * out,const uint8_t * in,size_t len) const299 int Keymaster0Engine::RsaPrivateTransform(RSA* rsa, uint8_t* out, const uint8_t* in,
300                                           size_t len) const {
301     const keymaster_key_blob_t* key_blob = RsaKeyToBlob(rsa);
302     if (key_blob == NULL) {
303         ALOGE("key had no key_blob!");
304         return 0;
305     }
306 
307     keymaster_rsa_sign_params_t sign_params = {DIGEST_NONE, PADDING_NONE};
308     unique_ptr<uint8_t[], Malloc_Delete> signature;
309     size_t signature_length;
310     if (!Keymaster0Sign(&sign_params, *key_blob, in, len, &signature, &signature_length)) {
311         if (data_too_large_for_public_modulus(in, len, rsa)) {
312             ALOGE("Keymaster0 signing failed because data is too large.");
313             OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
314         } else {
315             // We don't know what error code is correct; force an "unknown error" return
316             OPENSSL_PUT_ERROR(USER, KM_ERROR_UNKNOWN_ERROR);
317         }
318         return 0;
319     }
320     Eraser eraser(signature.get(), signature_length);
321 
322     if (signature_length > len) {
323         /* The result of the RSA operation can never be larger than the size of
324          * the modulus so we assume that the result has extra zeros on the
325          * left. This provides attackers with an oracle, but there's nothing
326          * that we can do about it here. */
327         memcpy(out, signature.get() + signature_length - len, len);
328     } else if (signature_length < len) {
329         /* If the keymaster0 implementation returns a short value we assume that
330          * it's because it removed leading zeros from the left side. This is
331          * bad because it provides attackers with an oracle but we cannot do
332          * anything about a broken keymaster0 implementation here. */
333         memset(out, 0, len);
334         memcpy(out + len - signature_length, signature.get(), signature_length);
335     } else {
336         memcpy(out, signature.get(), len);
337     }
338 
339     ALOGV("rsa=%p keystore_rsa_priv_dec successful", rsa);
340     return 1;
341 }
342 
EcdsaSign(const uint8_t * digest,size_t digest_len,uint8_t * sig,unsigned int * sig_len,EC_KEY * ec_key) const343 int Keymaster0Engine::EcdsaSign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
344                                 unsigned int* sig_len, EC_KEY* ec_key) const {
345     const keymaster_key_blob_t* key_blob = EcKeyToBlob(ec_key);
346     if (key_blob == NULL) {
347         ALOGE("key had no key_blob!");
348         return 0;
349     }
350 
351     // Truncate digest if it's too long
352     size_t max_input_len = (ec_group_size_bits(ec_key) + 7) / 8;
353     if (digest_len > max_input_len)
354         digest_len = max_input_len;
355 
356     keymaster_ec_sign_params_t sign_params = {DIGEST_NONE};
357     unique_ptr<uint8_t[], Malloc_Delete> signature;
358     size_t signature_length;
359     if (!Keymaster0Sign(&sign_params, *key_blob, digest, digest_len, &signature,
360                         &signature_length)) {
361         // We don't know what error code is correct; force an "unknown error" return
362         OPENSSL_PUT_ERROR(USER, KM_ERROR_UNKNOWN_ERROR);
363         return 0;
364     }
365     Eraser eraser(signature.get(), signature_length);
366 
367     if (signature_length == 0) {
368         ALOGW("No valid signature returned");
369         return 0;
370     } else if (signature_length > ECDSA_size(ec_key)) {
371         ALOGW("Signature is too large");
372         return 0;
373     } else {
374         memcpy(sig, signature.get(), signature_length);
375         *sig_len = signature_length;
376     }
377 
378     ALOGV("ecdsa_sign(%p, %u, %p) => success", digest, (unsigned)digest_len, ec_key);
379     return 1;
380 }
381 
382 }  // namespace keymaster
383