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