blob: 4af045adacc18d2c72d62c106fef9fe22df89633 [file] [log] [blame]
Shawn Willdenac398062015-05-20 16:36:24 -06001/*
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
Shawn Willden9a1cd6d2015-07-08 17:12:16 -060028#include <openssl/bn.h>
Shawn Willdenac398062015-05-20 16:36:24 -060029#include <openssl/ec_key.h>
30#include <openssl/ecdsa.h>
31
32#include "openssl_utils.h"
33
34using std::shared_ptr;
35using std::unique_ptr;
36
37namespace keymaster {
38
39// int Keymaster0Engine::rsa_index_ = -1;
40// int Keymaster0Engine::ec_key_index_ = -1;
41Keymaster0Engine* Keymaster0Engine::instance_ = nullptr;
42const RSA_METHOD Keymaster0Engine::rsa_method_ = {
Shawn Willden24bdfc22015-05-26 13:12:24 -060043 .common =
44 {
45 0, // references
46 1 // is_static
47 },
Shawn Willdenac398062015-05-20 16:36:24 -060048 .app_data = nullptr,
49 .init = nullptr,
50 .finish = nullptr,
51 .size = nullptr,
52 .sign = nullptr,
53 .verify = nullptr,
54
55 .encrypt = nullptr,
56 .sign_raw = nullptr,
57 .decrypt = nullptr,
58 .verify_raw = nullptr,
59
60 .private_transform = Keymaster0Engine::rsa_private_transform,
61
62 .mod_exp = nullptr,
63 .bn_mod_exp = BN_mod_exp_mont,
64
Shawn Willden24bdfc22015-05-26 13:12:24 -060065 .flags = RSA_FLAG_OPAQUE,
Shawn Willdenac398062015-05-20 16:36:24 -060066
67 .keygen = nullptr,
Adam Langley607b0e02015-09-02 15:33:52 -070068 .multi_prime_keygen = nullptr,
Shawn Willdenac398062015-05-20 16:36:24 -060069 .supports_digest = nullptr,
70};
71
Shawn Willden24bdfc22015-05-26 13:12:24 -060072const ECDSA_METHOD Keymaster0Engine::ecdsa_method_ = {
73 .common =
74 {
75 0, // references
76 1 // is_static
77 },
78 .app_data = nullptr,
79 .init = nullptr,
80 .finish = nullptr,
81 .group_order_size = nullptr,
82 .sign = Keymaster0Engine::ecdsa_sign,
83 .verify = nullptr,
84 .flags = ECDSA_FLAG_OPAQUE,
85};
86
Shawn Willdenac398062015-05-20 16:36:24 -060087Keymaster0Engine::Keymaster0Engine(const keymaster0_device_t* keymaster0_device)
Shawn Willden24bdfc22015-05-26 13:12:24 -060088 : keymaster0_device_(keymaster0_device), engine_(ENGINE_new()), supports_ec_(false) {
Shawn Willdenac398062015-05-20 16:36:24 -060089 assert(!instance_);
90 instance_ = this;
91
92 rsa_index_ = RSA_get_ex_new_index(0 /* argl */, NULL /* argp */, NULL /* new_func */,
93 keyblob_dup, keyblob_free);
Shawn Willden24bdfc22015-05-26 13:12:24 -060094 ec_key_index_ = EC_KEY_get_ex_new_index(0 /* argl */, NULL /* argp */, NULL /* new_func */,
95 keyblob_dup, keyblob_free);
96
Shawn Willdenac398062015-05-20 16:36:24 -060097 ENGINE_set_RSA_method(engine_, &rsa_method_, sizeof(rsa_method_));
Shawn Willden24bdfc22015-05-26 13:12:24 -060098
99 if ((keymaster0_device_->flags & KEYMASTER_SUPPORTS_EC) != 0) {
100 supports_ec_ = true;
101 ENGINE_set_ECDSA_method(engine_, &ecdsa_method_, sizeof(ecdsa_method_));
102 }
Shawn Willdenac398062015-05-20 16:36:24 -0600103}
104
105Keymaster0Engine::~Keymaster0Engine() {
106 if (keymaster0_device_)
107 keymaster0_device_->common.close(
108 reinterpret_cast<hw_device_t*>(const_cast<keymaster0_device_t*>(keymaster0_device_)));
109 ENGINE_free(engine_);
110 instance_ = nullptr;
111}
112
113bool Keymaster0Engine::GenerateRsaKey(uint64_t public_exponent, uint32_t public_modulus,
114 KeymasterKeyBlob* key_material) const {
115 assert(key_material);
116 keymaster_rsa_keygen_params_t params;
117 params.public_exponent = public_exponent;
118 params.modulus_size = public_modulus;
119
120 uint8_t* key_blob = 0;
121 if (keymaster0_device_->generate_keypair(keymaster0_device_, TYPE_RSA, &params, &key_blob,
122 &key_material->key_material_size) < 0) {
123 ALOGE("Error generating RSA 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
Shawn Willden24bdfc22015-05-26 13:12:24 -0600131bool Keymaster0Engine::GenerateEcKey(uint32_t key_size, KeymasterKeyBlob* key_material) const {
132 assert(key_material);
133 keymaster_ec_keygen_params_t params;
134 params.field_size = key_size;
135
136 uint8_t* key_blob = 0;
137 if (keymaster0_device_->generate_keypair(keymaster0_device_, TYPE_EC, &params, &key_blob,
138 &key_material->key_material_size) < 0) {
139 ALOGE("Error generating EC key pair with keymaster0 device");
140 return false;
141 }
142 unique_ptr<uint8_t, Malloc_Delete> key_blob_deleter(key_blob);
143 key_material->key_material = dup_buffer(key_blob, key_material->key_material_size);
144 return true;
145}
146
147bool Keymaster0Engine::ImportKey(keymaster_key_format_t key_format,
148 const KeymasterKeyBlob& to_import,
149 KeymasterKeyBlob* imported_key) const {
Shawn Willdenac398062015-05-20 16:36:24 -0600150 assert(imported_key);
151 if (key_format != KM_KEY_FORMAT_PKCS8)
152 return false;
153
154 uint8_t* key_blob = 0;
155 if (keymaster0_device_->import_keypair(keymaster0_device_, to_import.key_material,
156 to_import.key_material_size, &key_blob,
157 &imported_key->key_material_size) < 0) {
Shawn Willden24bdfc22015-05-26 13:12:24 -0600158 ALOGW("Error importing keypair with keymaster0 device");
Shawn Willdenac398062015-05-20 16:36:24 -0600159 return false;
160 }
161 unique_ptr<uint8_t, Malloc_Delete> key_blob_deleter(key_blob);
162 imported_key->key_material = dup_buffer(key_blob, imported_key->key_material_size);
163 return true;
164}
165
166static keymaster_key_blob_t* duplicate_blob(const uint8_t* key_data, size_t key_data_size) {
Shawn Willden661b2b12015-06-20 09:16:30 -0600167 unique_ptr<uint8_t[]> key_material_copy(dup_buffer(key_data, key_data_size));
Shawn Willdenac398062015-05-20 16:36:24 -0600168 if (!key_material_copy)
169 return nullptr;
170
Shawn Willden9a1cd6d2015-07-08 17:12:16 -0600171 unique_ptr<keymaster_key_blob_t> blob_copy(new (std::nothrow) keymaster_key_blob_t);
Shawn Willden661b2b12015-06-20 09:16:30 -0600172 if (!blob_copy.get())
173 return nullptr;
Shawn Willdenac398062015-05-20 16:36:24 -0600174 blob_copy->key_material_size = key_data_size;
175 blob_copy->key_material = key_material_copy.release();
176 return blob_copy.release();
177}
178
179inline keymaster_key_blob_t* duplicate_blob(const keymaster_key_blob_t& blob) {
180 return duplicate_blob(blob.key_material, blob.key_material_size);
181}
182
183RSA* Keymaster0Engine::BlobToRsaKey(const KeymasterKeyBlob& blob) const {
184 // Create new RSA key (with engine methods) and insert blob
185 unique_ptr<RSA, RSA_Delete> rsa(RSA_new_method(engine_));
186 if (!rsa)
187 return nullptr;
188
189 keymaster_key_blob_t* blob_copy = duplicate_blob(blob);
190 if (!blob_copy->key_material || !RSA_set_ex_data(rsa.get(), rsa_index_, blob_copy))
191 return nullptr;
192
193 // Copy public key into new RSA key
194 unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(GetKeymaster0PublicKey(blob));
195 if (!pkey)
196 return nullptr;
197 unique_ptr<RSA, RSA_Delete> public_rsa(EVP_PKEY_get1_RSA(pkey.get()));
198 if (!public_rsa)
199 return nullptr;
200 rsa->n = BN_dup(public_rsa->n);
201 rsa->e = BN_dup(public_rsa->e);
202 if (!rsa->n || !rsa->e)
203 return nullptr;
204
205 return rsa.release();
206}
207
Shawn Willden24bdfc22015-05-26 13:12:24 -0600208EC_KEY* Keymaster0Engine::BlobToEcKey(const KeymasterKeyBlob& blob) const {
209 // Create new EC key (with engine methods) and insert blob
210 unique_ptr<EC_KEY, EC_Delete> ec_key(EC_KEY_new_method(engine_));
211 if (!ec_key)
212 return nullptr;
213
214 keymaster_key_blob_t* blob_copy = duplicate_blob(blob);
215 if (!blob_copy->key_material || !EC_KEY_set_ex_data(ec_key.get(), ec_key_index_, blob_copy))
216 return nullptr;
217
218 // Copy public key into new EC key
219 unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(GetKeymaster0PublicKey(blob));
220 if (!pkey)
221 return nullptr;
222
223 unique_ptr<EC_KEY, EC_Delete> public_ec_key(EVP_PKEY_get1_EC_KEY(pkey.get()));
224 if (!public_ec_key)
225 return nullptr;
226
227 if (!EC_KEY_set_group(ec_key.get(), EC_KEY_get0_group(public_ec_key.get())) ||
228 !EC_KEY_set_public_key(ec_key.get(), EC_KEY_get0_public_key(public_ec_key.get())))
229 return nullptr;
230
231 return ec_key.release();
232}
233
234const keymaster_key_blob_t* Keymaster0Engine::RsaKeyToBlob(const RSA* rsa) const {
Shawn Willdenac398062015-05-20 16:36:24 -0600235 return reinterpret_cast<keymaster_key_blob_t*>(RSA_get_ex_data(rsa, rsa_index_));
236}
237
Shawn Willden24bdfc22015-05-26 13:12:24 -0600238const keymaster_key_blob_t* Keymaster0Engine::EcKeyToBlob(const EC_KEY* ec_key) const {
239 return reinterpret_cast<keymaster_key_blob_t*>(EC_KEY_get_ex_data(ec_key, ec_key_index_));
240}
241
Shawn Willdenac398062015-05-20 16:36:24 -0600242/* static */
243int Keymaster0Engine::keyblob_dup(CRYPTO_EX_DATA* /* to */, const CRYPTO_EX_DATA* /* from */,
244 void** from_d, int /* index */, long /* argl */,
245 void* /* argp */) {
246 keymaster_key_blob_t* blob = reinterpret_cast<keymaster_key_blob_t*>(*from_d);
Shawn Willden24bdfc22015-05-26 13:12:24 -0600247 if (!blob)
248 return 1;
Shawn Willdenac398062015-05-20 16:36:24 -0600249 *from_d = duplicate_blob(*blob);
250 if (*from_d)
251 return 1;
252 return 0;
253}
254
255/* static */
256void Keymaster0Engine::keyblob_free(void* /* parent */, void* ptr, CRYPTO_EX_DATA* /* data */,
257 int /* index*/, long /* argl */, void* /* argp */) {
258 keymaster_key_blob_t* blob = reinterpret_cast<keymaster_key_blob_t*>(ptr);
259 if (blob) {
260 delete[] blob->key_material;
261 delete blob;
262 }
263}
264
265/* static */
266int Keymaster0Engine::rsa_private_transform(RSA* rsa, uint8_t* out, const uint8_t* in, size_t len) {
267 ALOGV("rsa_private_transform(%p, %p, %p, %u)", rsa, out, in, (unsigned)len);
268
269 assert(instance_);
270 return instance_->RsaPrivateTransform(rsa, out, in, len);
271}
272
Shawn Willden24bdfc22015-05-26 13:12:24 -0600273/* static */
274int Keymaster0Engine::ecdsa_sign(const uint8_t* digest, size_t digest_len, uint8_t* sig,
275 unsigned int* sig_len, EC_KEY* ec_key) {
276 ALOGV("ecdsa_sign(%p, %u, %p)", digest, (unsigned)digest_len, ec_key);
277 assert(instance_);
278 return instance_->EcdsaSign(digest, digest_len, sig, sig_len, ec_key);
279}
280
Shawn Willdenac398062015-05-20 16:36:24 -0600281bool Keymaster0Engine::Keymaster0Sign(const void* signing_params, const keymaster_key_blob_t& blob,
282 const uint8_t* data, const size_t data_length,
283 unique_ptr<uint8_t[], Malloc_Delete>* signature,
284 size_t* signature_length) const {
285 uint8_t* signed_data;
286 int err = keymaster0_device_->sign_data(keymaster0_device_, signing_params, blob.key_material,
287 blob.key_material_size, data, data_length, &signed_data,
288 signature_length);
289 if (err < 0) {
290 ALOGE("Keymaster0 signing failed with error %d", err);
291 return false;
292 }
293
294 signature->reset(signed_data);
295 return true;
296}
297
298EVP_PKEY* Keymaster0Engine::GetKeymaster0PublicKey(const KeymasterKeyBlob& blob) const {
299 uint8_t* pub_key_data;
300 size_t pub_key_data_length;
301 int err = keymaster0_device_->get_keypair_public(keymaster0_device_, blob.key_material,
302 blob.key_material_size, &pub_key_data,
303 &pub_key_data_length);
304 if (err < 0) {
305 ALOGE("Error %d extracting public key", err);
306 return nullptr;
307 }
308 unique_ptr<uint8_t, Malloc_Delete> pub_key(pub_key_data);
309
310 const uint8_t* p = pub_key_data;
311 return d2i_PUBKEY(nullptr /* allocate new struct */, &p, pub_key_data_length);
312}
313
314int Keymaster0Engine::RsaPrivateTransform(RSA* rsa, uint8_t* out, const uint8_t* in,
315 size_t len) const {
Shawn Willden24bdfc22015-05-26 13:12:24 -0600316 const keymaster_key_blob_t* key_blob = RsaKeyToBlob(rsa);
Shawn Willdenac398062015-05-20 16:36:24 -0600317 if (key_blob == NULL) {
318 ALOGE("key had no key_blob!");
319 return 0;
320 }
321
322 keymaster_rsa_sign_params_t sign_params = {DIGEST_NONE, PADDING_NONE};
323 unique_ptr<uint8_t[], Malloc_Delete> signature;
324 size_t signature_length;
325 if (!Keymaster0Sign(&sign_params, *key_blob, in, len, &signature, &signature_length))
326 return 0;
327 Eraser eraser(signature.get(), signature_length);
328
329 if (signature_length > len) {
330 /* The result of the RSA operation can never be larger than the size of
331 * the modulus so we assume that the result has extra zeros on the
332 * left. This provides attackers with an oracle, but there's nothing
333 * that we can do about it here. */
334 memcpy(out, signature.get() + signature_length - len, len);
335 } else if (signature_length < len) {
336 /* If the keymaster0 implementation returns a short value we assume that
337 * it's because it removed leading zeros from the left side. This is
338 * bad because it provides attackers with an oracle but we cannot do
339 * anything about a broken keymaster0 implementation here. */
340 memset(out, 0, len);
341 memcpy(out + len - signature_length, signature.get(), signature_length);
342 } else {
343 memcpy(out, signature.get(), len);
344 }
345
346 ALOGV("rsa=%p keystore_rsa_priv_dec successful", rsa);
347 return 1;
348}
349
Shawn Willden9a1cd6d2015-07-08 17:12:16 -0600350static size_t ec_group_size_bits(EC_KEY* ec_key) {
351 const EC_GROUP* group = EC_KEY_get0_group(ec_key);
352 unique_ptr<BN_CTX, BN_CTX_Delete> bn_ctx(BN_CTX_new());
353 unique_ptr<BIGNUM, BIGNUM_Delete> order(BN_new());
354 if (!EC_GROUP_get_order(group, order.get(), bn_ctx.get())) {
355 ALOGE("Failed to get EC group order");
356 return 0;
357 }
358 return BN_num_bits(order.get());
359}
360
Shawn Willden24bdfc22015-05-26 13:12:24 -0600361int 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
Shawn Willden9a1cd6d2015-07-08 17:12:16 -0600369 // 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
Shawn Willden24bdfc22015-05-26 13:12:24 -0600374 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, &signature_length))
378 return 0;
379 Eraser eraser(signature.get(), signature_length);
380
381 if (signature_length == 0) {
382 ALOGW("No valid signature returned");
383 return 0;
384 } else if (signature_length > ECDSA_size(ec_key)) {
385 ALOGW("Signature is too large");
386 return 0;
387 } else {
388 memcpy(sig, signature.get(), signature_length);
389 *sig_len = signature_length;
390 }
391
392 ALOGV("ecdsa_sign(%p, %u, %p) => success", digest, (unsigned)digest_len, ec_key);
393 return 1;
394}
395
Shawn Willdenac398062015-05-20 16:36:24 -0600396} // namespace keymaster