1/*
2 * Copyright 2014 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#define LOG_TAG "TrustyKeymaster"
18
19#include <assert.h>
20#include <openssl/evp.h>
21#include <openssl/x509.h>
22#include <stddef.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <time.h>
27
28#include <type_traits>
29
30#include <hardware/keymaster0.h>
31#include <keymaster/authorization_set.h>
32#include <log/log.h>
33
34#include "trusty_keymaster_device.h"
35#include "trusty_keymaster_ipc.h"
36#include "keymaster_ipc.h"
37
38const uint32_t SEND_BUF_SIZE = 8192;
39const uint32_t RECV_BUF_SIZE = 8192;
40
41namespace keymaster {
42
43static keymaster_error_t translate_error(int err) {
44    switch (err) {
45    case 0:
46        return KM_ERROR_OK;
47    case -EPERM:
48    case -EACCES:
49        return KM_ERROR_SECURE_HW_ACCESS_DENIED;
50
51    case -ECANCELED:
52        return KM_ERROR_OPERATION_CANCELLED;
53
54    case -ENODEV:
55        return KM_ERROR_UNIMPLEMENTED;
56
57    case -ENOMEM:
58        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
59
60    case -EBUSY:
61        return KM_ERROR_SECURE_HW_BUSY;
62
63    case -EIO:
64        return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
65
66    case -EOVERFLOW:
67        return KM_ERROR_INVALID_INPUT_LENGTH;
68
69    default:
70        return KM_ERROR_UNKNOWN_ERROR;
71    }
72}
73
74TrustyKeymasterDevice::TrustyKeymasterDevice(const hw_module_t* module) {
75    static_assert(std::is_standard_layout<TrustyKeymasterDevice>::value,
76                  "TrustyKeymasterDevice must be standard layout");
77    static_assert(offsetof(TrustyKeymasterDevice, device_) == 0,
78                  "device_ must be the first member of KeymasterOpenSsl");
79    static_assert(offsetof(TrustyKeymasterDevice, device_.common) == 0,
80                  "common must be the first member of keymaster_device");
81
82    ALOGI("Creating device");
83    ALOGD("Device address: %p", this);
84
85    memset(&device_, 0, sizeof(device_));
86
87    device_.common.tag = HARDWARE_DEVICE_TAG;
88    device_.common.version = 1;
89    device_.common.module = const_cast<hw_module_t*>(module);
90    device_.common.close = close_device;
91
92    device_.flags = KEYMASTER_BLOBS_ARE_STANDALONE | KEYMASTER_SUPPORTS_EC;
93
94    device_.generate_keypair = generate_keypair;
95    device_.import_keypair = import_keypair;
96    device_.get_keypair_public = get_keypair_public;
97    device_.delete_keypair = NULL;
98    device_.delete_all = NULL;
99    device_.sign_data = sign_data;
100    device_.verify_data = verify_data;
101
102    device_.context = NULL;
103
104    int rc = trusty_keymaster_connect();
105    error_ = translate_error(rc);
106    if (rc < 0) {
107        ALOGE("failed to connect to keymaster (%d)", rc);
108        return;
109    }
110
111    GetVersionRequest version_request;
112    GetVersionResponse version_response;
113    error_ = Send(version_request, &version_response);
114    if (error_ == KM_ERROR_INVALID_ARGUMENT || error_ == KM_ERROR_UNIMPLEMENTED) {
115        ALOGI("\"Bad parameters\" error on GetVersion call.  Assuming version 0.");
116        message_version_ = 0;
117        error_ = KM_ERROR_OK;
118    }
119    message_version_ = MessageVersion(version_response.major_ver, version_response.minor_ver,
120                                      version_response.subminor_ver);
121    if (message_version_ < 0) {
122        // Can't translate version?  Keymaster implementation must be newer.
123        ALOGE("Keymaster version %d.%d.%d not supported.", version_response.major_ver,
124              version_response.minor_ver, version_response.subminor_ver);
125        error_ = KM_ERROR_VERSION_MISMATCH;
126    }
127}
128
129TrustyKeymasterDevice::~TrustyKeymasterDevice() {
130    trusty_keymaster_disconnect();
131}
132
133const uint64_t HUNDRED_YEARS = 1000LL * 60 * 60 * 24 * 365 * 100;
134
135int TrustyKeymasterDevice::generate_keypair(const keymaster_keypair_t key_type,
136                                            const void* key_params, uint8_t** key_blob,
137                                            size_t* key_blob_length) {
138    ALOGD("Device received generate_keypair");
139
140    if (error_ != KM_ERROR_OK)
141        return error_;
142
143    GenerateKeyRequest req(message_version_);
144    StoreNewKeyParams(&req.key_description);
145
146    switch (key_type) {
147    case TYPE_RSA: {
148        req.key_description.push_back(TAG_ALGORITHM, KM_ALGORITHM_RSA);
149        const keymaster_rsa_keygen_params_t* rsa_params =
150            static_cast<const keymaster_rsa_keygen_params_t*>(key_params);
151        ALOGD("Generating RSA pair, modulus size: %u, public exponent: %lu",
152              rsa_params->modulus_size, rsa_params->public_exponent);
153        req.key_description.push_back(TAG_KEY_SIZE, rsa_params->modulus_size);
154        req.key_description.push_back(TAG_RSA_PUBLIC_EXPONENT, rsa_params->public_exponent);
155        break;
156    }
157
158    case TYPE_EC: {
159        req.key_description.push_back(TAG_ALGORITHM, KM_ALGORITHM_EC);
160        const keymaster_ec_keygen_params_t* ec_params =
161            static_cast<const keymaster_ec_keygen_params_t*>(key_params);
162        ALOGD("Generating ECDSA pair, key size: %u", ec_params->field_size);
163        req.key_description.push_back(TAG_KEY_SIZE, ec_params->field_size);
164        break;
165    }
166    default:
167        ALOGD("Received request for unsuported key type %d", key_type);
168        return KM_ERROR_UNSUPPORTED_ALGORITHM;
169    }
170
171    GenerateKeyResponse rsp(message_version_);
172    ALOGD("Sending generate request");
173    keymaster_error_t err = Send(req, &rsp);
174    if (err != KM_ERROR_OK) {
175        ALOGE("Got error %d from send", err);
176        return err;
177    }
178
179    *key_blob_length = rsp.key_blob.key_material_size;
180    *key_blob = static_cast<uint8_t*>(malloc(*key_blob_length));
181    memcpy(*key_blob, rsp.key_blob.key_material, *key_blob_length);
182    ALOGD("Returning %d bytes in key blob\n", (int)*key_blob_length);
183
184    return KM_ERROR_OK;
185}
186
187struct EVP_PKEY_Delete {
188    void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); }
189};
190
191struct PKCS8_PRIV_KEY_INFO_Delete {
192    void operator()(PKCS8_PRIV_KEY_INFO* p) const { PKCS8_PRIV_KEY_INFO_free(p); }
193};
194
195int TrustyKeymasterDevice::import_keypair(const uint8_t* key, const size_t key_length,
196                                          uint8_t** key_blob, size_t* key_blob_length) {
197    ALOGD("Device received import_keypair");
198    if (error_ != KM_ERROR_OK)
199        return error_;
200
201    if (!key)
202        return KM_ERROR_UNEXPECTED_NULL_POINTER;
203
204    if (!key_blob || !key_blob_length)
205        return KM_ERROR_OUTPUT_PARAMETER_NULL;
206
207    ImportKeyRequest request(message_version_);
208    StoreNewKeyParams(&request.key_description);
209    keymaster_algorithm_t algorithm;
210    keymaster_error_t err = GetPkcs8KeyAlgorithm(key, key_length, &algorithm);
211    if (err != KM_ERROR_OK)
212        return err;
213    request.key_description.push_back(TAG_ALGORITHM, algorithm);
214
215    request.SetKeyMaterial(key, key_length);
216    request.key_format = KM_KEY_FORMAT_PKCS8;
217    ImportKeyResponse response(message_version_);
218    err = Send(request, &response);
219    if (err != KM_ERROR_OK)
220        return err;
221
222    *key_blob_length = response.key_blob.key_material_size;
223    *key_blob = static_cast<uint8_t*>(malloc(*key_blob_length));
224    memcpy(*key_blob, response.key_blob.key_material, *key_blob_length);
225    printf("Returning %d bytes in key blob\n", (int)*key_blob_length);
226
227    return KM_ERROR_OK;
228}
229
230keymaster_error_t TrustyKeymasterDevice::GetPkcs8KeyAlgorithm(const uint8_t* key, size_t key_length,
231                                                              keymaster_algorithm_t* algorithm) {
232    if (key == NULL) {
233        ALOGE("No key specified for import");
234        return KM_ERROR_UNEXPECTED_NULL_POINTER;
235    }
236
237    UniquePtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_Delete> pkcs8(
238        d2i_PKCS8_PRIV_KEY_INFO(NULL, &key, key_length));
239    if (pkcs8.get() == NULL) {
240        ALOGE("Could not parse PKCS8 key blob");
241        return KM_ERROR_INVALID_KEY_BLOB;
242    }
243
244    UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(EVP_PKCS82PKEY(pkcs8.get()));
245    if (pkey.get() == NULL) {
246        ALOGE("Could not extract key from PKCS8 key blob");
247        return KM_ERROR_INVALID_KEY_BLOB;
248    }
249
250    switch (EVP_PKEY_type(pkey->type)) {
251    case EVP_PKEY_RSA:
252        *algorithm = KM_ALGORITHM_RSA;
253        break;
254    case EVP_PKEY_EC:
255        *algorithm = KM_ALGORITHM_EC;
256        break;
257    default:
258        ALOGE("Unsupported algorithm %d", EVP_PKEY_type(pkey->type));
259        return KM_ERROR_UNSUPPORTED_ALGORITHM;
260    }
261
262    return KM_ERROR_OK;
263}
264
265int TrustyKeymasterDevice::get_keypair_public(const uint8_t* key_blob, const size_t key_blob_length,
266                                              uint8_t** x509_data, size_t* x509_data_length) {
267    ALOGD("Device received get_keypair_public");
268    if (error_ != KM_ERROR_OK)
269        return error_;
270
271    ExportKeyRequest request(message_version_);
272    request.SetKeyMaterial(key_blob, key_blob_length);
273    request.key_format = KM_KEY_FORMAT_X509;
274    ExportKeyResponse response(message_version_);
275    keymaster_error_t err = Send(request, &response);
276    if (err != KM_ERROR_OK)
277        return err;
278
279    *x509_data_length = response.key_data_length;
280    *x509_data = static_cast<uint8_t*>(malloc(*x509_data_length));
281    memcpy(*x509_data, response.key_data, *x509_data_length);
282    printf("Returning %d bytes in x509 key\n", (int)*x509_data_length);
283
284    return KM_ERROR_OK;
285}
286
287int TrustyKeymasterDevice::sign_data(const void* signing_params, const uint8_t* key_blob,
288                                     const size_t key_blob_length, const uint8_t* data,
289                                     const size_t data_length, uint8_t** signed_data,
290                                     size_t* signed_data_length) {
291    ALOGD("Device received sign_data, %d", error_);
292    if (error_ != KM_ERROR_OK)
293        return error_;
294
295    BeginOperationRequest begin_request(message_version_);
296    begin_request.purpose = KM_PURPOSE_SIGN;
297    begin_request.SetKeyMaterial(key_blob, key_blob_length);
298    keymaster_error_t err = StoreSigningParams(signing_params, key_blob, key_blob_length,
299                                               &begin_request.additional_params);
300    if (err != KM_ERROR_OK) {
301        ALOGE("Error extracting signing params: %d", err);
302        return err;
303    }
304
305    BeginOperationResponse begin_response(message_version_);
306    ALOGD("Sending signing request begin");
307    err = Send(begin_request, &begin_response);
308    if (err != KM_ERROR_OK) {
309        ALOGE("Error sending sign begin: %d", err);
310        return err;
311    }
312
313    UpdateOperationRequest update_request(message_version_);
314    update_request.op_handle = begin_response.op_handle;
315    update_request.input.Reinitialize(data, data_length);
316    UpdateOperationResponse update_response(message_version_);
317    ALOGD("Sending signing request update");
318    err = Send(update_request, &update_response);
319    if (err != KM_ERROR_OK) {
320        ALOGE("Error sending sign update: %d", err);
321        return err;
322    }
323
324    FinishOperationRequest finish_request(message_version_);
325    finish_request.op_handle = begin_response.op_handle;
326    FinishOperationResponse finish_response(message_version_);
327    ALOGD("Sending signing request finish");
328    err = Send(finish_request, &finish_response);
329    if (err != KM_ERROR_OK) {
330        ALOGE("Error sending sign finish: %d", err);
331        return err;
332    }
333
334    *signed_data_length = finish_response.output.available_read();
335    *signed_data = static_cast<uint8_t*>(malloc(*signed_data_length));
336    if (!finish_response.output.read(*signed_data, *signed_data_length)) {
337        ALOGE("Error reading response data: %d", err);
338        return KM_ERROR_UNKNOWN_ERROR;
339    }
340    return KM_ERROR_OK;
341}
342
343int TrustyKeymasterDevice::verify_data(const void* signing_params, const uint8_t* key_blob,
344                                       const size_t key_blob_length, const uint8_t* signed_data,
345                                       const size_t signed_data_length, const uint8_t* signature,
346                                       const size_t signature_length) {
347    ALOGD("Device received verify_data");
348    if (error_ != KM_ERROR_OK)
349        return error_;
350
351    BeginOperationRequest begin_request(message_version_);
352    begin_request.purpose = KM_PURPOSE_VERIFY;
353    begin_request.SetKeyMaterial(key_blob, key_blob_length);
354    keymaster_error_t err = StoreSigningParams(signing_params, key_blob, key_blob_length,
355                                               &begin_request.additional_params);
356    if (err != KM_ERROR_OK)
357        return err;
358
359    BeginOperationResponse begin_response(message_version_);
360    err = Send(begin_request, &begin_response);
361    if (err != KM_ERROR_OK)
362        return err;
363
364    UpdateOperationRequest update_request(message_version_);
365    update_request.op_handle = begin_response.op_handle;
366    update_request.input.Reinitialize(signed_data, signed_data_length);
367    UpdateOperationResponse update_response(message_version_);
368    err = Send(update_request, &update_response);
369    if (err != KM_ERROR_OK)
370        return err;
371
372    FinishOperationRequest finish_request(message_version_);
373    finish_request.op_handle = begin_response.op_handle;
374    finish_request.signature.Reinitialize(signature, signature_length);
375    FinishOperationResponse finish_response(message_version_);
376    err = Send(finish_request, &finish_response);
377    if (err != KM_ERROR_OK)
378        return err;
379    return KM_ERROR_OK;
380}
381
382hw_device_t* TrustyKeymasterDevice::hw_device() {
383    return &device_.common;
384}
385
386static inline TrustyKeymasterDevice* convert_device(const keymaster0_device_t* dev) {
387    return reinterpret_cast<TrustyKeymasterDevice*>(const_cast<keymaster0_device_t*>(dev));
388}
389
390/* static */
391int TrustyKeymasterDevice::close_device(hw_device_t* dev) {
392    delete reinterpret_cast<TrustyKeymasterDevice*>(dev);
393    return 0;
394}
395
396/* static */
397int TrustyKeymasterDevice::generate_keypair(const keymaster0_device_t* dev,
398                                            const keymaster_keypair_t key_type,
399                                            const void* key_params, uint8_t** keyBlob,
400                                            size_t* keyBlobLength) {
401    ALOGD("Generate keypair, sending to device: %p", convert_device(dev));
402    return convert_device(dev)->generate_keypair(key_type, key_params, keyBlob, keyBlobLength);
403}
404
405/* static */
406int TrustyKeymasterDevice::import_keypair(const keymaster0_device_t* dev, const uint8_t* key,
407                                          const size_t key_length, uint8_t** key_blob,
408                                          size_t* key_blob_length) {
409    return convert_device(dev)->import_keypair(key, key_length, key_blob, key_blob_length);
410}
411
412/* static */
413int TrustyKeymasterDevice::get_keypair_public(const keymaster0_device_t* dev,
414                                              const uint8_t* key_blob, const size_t key_blob_length,
415                                              uint8_t** x509_data, size_t* x509_data_length) {
416    return convert_device(dev)
417        ->get_keypair_public(key_blob, key_blob_length, x509_data, x509_data_length);
418}
419
420/* static */
421int TrustyKeymasterDevice::sign_data(const keymaster0_device_t* dev, const void* params,
422                                     const uint8_t* keyBlob, const size_t keyBlobLength,
423                                     const uint8_t* data, const size_t dataLength,
424                                     uint8_t** signedData, size_t* signedDataLength) {
425    return convert_device(dev)
426        ->sign_data(params, keyBlob, keyBlobLength, data, dataLength, signedData, signedDataLength);
427}
428
429/* static */
430int TrustyKeymasterDevice::verify_data(const keymaster0_device_t* dev, const void* params,
431                                       const uint8_t* keyBlob, const size_t keyBlobLength,
432                                       const uint8_t* signedData, const size_t signedDataLength,
433                                       const uint8_t* signature, const size_t signatureLength) {
434    return convert_device(dev)->verify_data(params, keyBlob, keyBlobLength, signedData,
435                                            signedDataLength, signature, signatureLength);
436}
437
438keymaster_error_t TrustyKeymasterDevice::Send(uint32_t command, const Serializable& req,
439                                              KeymasterResponse* rsp) {
440    uint32_t req_size = req.SerializedSize();
441    if (req_size > SEND_BUF_SIZE)
442        return KM_ERROR_MEMORY_ALLOCATION_FAILED;
443    uint8_t send_buf[SEND_BUF_SIZE];
444    Eraser send_buf_eraser(send_buf, SEND_BUF_SIZE);
445    req.Serialize(send_buf, send_buf + req_size);
446
447    // Send it
448    uint8_t recv_buf[RECV_BUF_SIZE];
449    Eraser recv_buf_eraser(recv_buf, RECV_BUF_SIZE);
450    uint32_t rsp_size = RECV_BUF_SIZE;
451    printf("Sending %d byte request\n", (int)req.SerializedSize());
452    int rc = trusty_keymaster_call(command, send_buf, req_size, recv_buf, &rsp_size);
453    if (rc < 0) {
454        ALOGE("tipc error: %d\n", rc);
455        // TODO(swillden): Distinguish permanent from transient errors and set error_ appropriately.
456        return translate_error(rc);
457    } else {
458        ALOGV("Received %d byte response\n", rsp_size);
459    }
460
461    const keymaster_message* msg = (keymaster_message *) recv_buf;
462    const uint8_t *p = msg->payload;
463    if (!rsp->Deserialize(&p, p + rsp_size)) {
464        ALOGE("Error deserializing response of size %d\n", (int)rsp_size);
465        return KM_ERROR_UNKNOWN_ERROR;
466    } else if (rsp->error != KM_ERROR_OK) {
467        ALOGE("Response of size %d contained error code %d\n", (int)rsp_size, (int)rsp->error);
468        return rsp->error;
469    }
470    return rsp->error;
471}
472
473keymaster_error_t TrustyKeymasterDevice::StoreSigningParams(const void* signing_params,
474                                                            const uint8_t* key_blob,
475                                                            size_t key_blob_length,
476                                                            AuthorizationSet* auth_set) {
477    uint8_t* pub_key_data;
478    size_t pub_key_data_length;
479    int err = get_keypair_public(&device_, key_blob, key_blob_length, &pub_key_data,
480                                 &pub_key_data_length);
481    if (err < 0) {
482        ALOGE("Error %d extracting public key to determine algorithm", err);
483        return KM_ERROR_INVALID_KEY_BLOB;
484    }
485    UniquePtr<uint8_t, Malloc_Delete> pub_key(pub_key_data);
486
487    const uint8_t* p = pub_key_data;
488    UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(
489        d2i_PUBKEY(nullptr /* allocate new struct */, &p, pub_key_data_length));
490
491    switch (EVP_PKEY_type(pkey->type)) {
492    case EVP_PKEY_RSA: {
493        const keymaster_rsa_sign_params_t* rsa_params =
494            reinterpret_cast<const keymaster_rsa_sign_params_t*>(signing_params);
495        if (rsa_params->digest_type != DIGEST_NONE)
496            return KM_ERROR_UNSUPPORTED_DIGEST;
497        if (rsa_params->padding_type != PADDING_NONE)
498            return KM_ERROR_UNSUPPORTED_PADDING_MODE;
499        if (!auth_set->push_back(TAG_DIGEST, KM_DIGEST_NONE) ||
500            !auth_set->push_back(TAG_PADDING, KM_PAD_NONE))
501            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
502    } break;
503    case EVP_PKEY_EC: {
504        const keymaster_ec_sign_params_t* ecdsa_params =
505            reinterpret_cast<const keymaster_ec_sign_params_t*>(signing_params);
506        if (ecdsa_params->digest_type != DIGEST_NONE)
507            return KM_ERROR_UNSUPPORTED_DIGEST;
508        if (!auth_set->push_back(TAG_DIGEST, KM_DIGEST_NONE))
509            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
510    } break;
511    default:
512        return KM_ERROR_UNSUPPORTED_ALGORITHM;
513    }
514    return KM_ERROR_OK;
515}
516
517void TrustyKeymasterDevice::StoreNewKeyParams(AuthorizationSet* auth_set) {
518    auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_SIGN);
519    auth_set->push_back(TAG_PURPOSE, KM_PURPOSE_VERIFY);
520    auth_set->push_back(TAG_ALL_USERS);
521    auth_set->push_back(TAG_NO_AUTH_REQUIRED);
522    uint64_t now = java_time(time(NULL));
523    auth_set->push_back(TAG_CREATION_DATETIME, now);
524    auth_set->push_back(TAG_ORIGINATION_EXPIRE_DATETIME, now + HUNDRED_YEARS);
525    if (message_version_ == 0) {
526        auth_set->push_back(TAG_DIGEST_OLD, KM_DIGEST_NONE);
527        auth_set->push_back(TAG_PADDING_OLD, KM_PAD_NONE);
528    } else {
529        auth_set->push_back(TAG_DIGEST, KM_DIGEST_NONE);
530        auth_set->push_back(TAG_PADDING, KM_PAD_NONE);
531    }
532}
533
534}  // namespace keymaster
535