1/*
2**
3** Copyright 2017, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17#include "keymaster_passthrough_operation.h"
18#include <keymaster/legacy_support/keymaster_passthrough_engine.h>
19#include <keymaster/legacy_support/keymaster_passthrough_key.h>
20
21#include <hardware/keymaster1.h>
22#include <hardware/keymaster2.h>
23
24#include <assert.h>
25
26#include <algorithm>
27#include <memory>
28#include <type_traits>
29
30#define LOG_TAG "Keymaster2Engine"
31#include <cutils/log.h>
32
33using std::shared_ptr;
34using std::unique_ptr;
35
36namespace keymaster {
37
38template <typename KeymasterDeviceType>
39class TKeymasterPassthroughEngine : public KeymasterPassthroughEngine {
40    using opfactory_t = KeymasterPassthroughOperationFactory<KeymasterDeviceType>;
41
42  public:
43    /**
44     * The engine takes ownership of the device, and will close it during destruction.
45     */
46    explicit TKeymasterPassthroughEngine(const KeymasterDeviceType* km_device)
47        : km_device_(km_device) {
48        rsa_encrypt_op_factory_.reset(
49            new opfactory_t(KM_ALGORITHM_RSA, KM_PURPOSE_ENCRYPT, km_device_));
50        rsa_decrypt_op_factory_.reset(
51            new opfactory_t(KM_ALGORITHM_RSA, KM_PURPOSE_DECRYPT, km_device_));
52        rsa_sign_op_factory_.reset(new opfactory_t(KM_ALGORITHM_RSA, KM_PURPOSE_SIGN, km_device_));
53        rsa_verify_op_factory_.reset(
54            new opfactory_t(KM_ALGORITHM_RSA, KM_PURPOSE_VERIFY, km_device_));
55        ec_encrypt_op_factory_.reset(
56            new opfactory_t(KM_ALGORITHM_EC, KM_PURPOSE_ENCRYPT, km_device_));
57        ec_decrypt_op_factory_.reset(
58            new opfactory_t(KM_ALGORITHM_EC, KM_PURPOSE_DECRYPT, km_device_));
59        ec_sign_op_factory_.reset(new opfactory_t(KM_ALGORITHM_EC, KM_PURPOSE_SIGN, km_device_));
60        ec_verify_op_factory_.reset(
61            new opfactory_t(KM_ALGORITHM_EC, KM_PURPOSE_VERIFY, km_device_));
62        ec_derive_op_factory_.reset(
63            new opfactory_t(KM_ALGORITHM_EC, KM_PURPOSE_DERIVE_KEY, km_device_));
64        aes_encrypt_op_factory_.reset(
65            new opfactory_t(KM_ALGORITHM_AES, KM_PURPOSE_ENCRYPT, km_device_));
66        aes_decrypt_op_factory_.reset(
67            new opfactory_t(KM_ALGORITHM_AES, KM_PURPOSE_DECRYPT, km_device_));
68        triple_des_encrypt_op_factory_.reset(
69            new opfactory_t(KM_ALGORITHM_TRIPLE_DES, KM_PURPOSE_ENCRYPT, km_device_));
70        triple_des_decrypt_op_factory_.reset(
71            new opfactory_t(KM_ALGORITHM_TRIPLE_DES, KM_PURPOSE_DECRYPT, km_device_));
72        hmac_sign_op_factory_.reset(
73            new opfactory_t(KM_ALGORITHM_HMAC, KM_PURPOSE_SIGN, km_device_));
74        hmac_verify_op_factory_.reset(
75            new opfactory_t(KM_ALGORITHM_HMAC, KM_PURPOSE_VERIFY, km_device_));
76    }
77    virtual ~TKeymasterPassthroughEngine() {
78        // QUIRK: we only take ownership if this is a KM2 device.
79        //        For KM1 the Keymaster1Engine takes ownership
80        if (std::is_same<KeymasterDeviceType, keymaster2_device_t>::value)
81            km_device_->common.close(
82                    reinterpret_cast<hw_device_t*>(const_cast<KeymasterDeviceType*>(km_device_)));
83    }
84
85    keymaster_error_t GenerateKey(const AuthorizationSet& key_description,
86                                  KeymasterKeyBlob* key_material, AuthorizationSet* hw_enforced,
87                                  AuthorizationSet* sw_enforced) const override;
88
89    keymaster_error_t ImportKey(const AuthorizationSet& key_description,
90                                keymaster_key_format_t input_key_material_format,
91                                const KeymasterKeyBlob& input_key_material,
92                                KeymasterKeyBlob* output_key_blob, AuthorizationSet* hw_enforced,
93                                AuthorizationSet* sw_enforced) const override;
94    keymaster_error_t ExportKey(keymaster_key_format_t format,
95                                const KeymasterKeyBlob& blob,
96                                const KeymasterBlob& client_id,
97                                const KeymasterBlob& app_data,
98                                KeymasterBlob* export_data) const override {
99        keymaster_blob_t my_export_data = {};
100        keymaster_error_t error = km_device_->export_key(km_device_, format, &blob, &client_id,
101                                                         &app_data, &my_export_data);
102        if (error != KM_ERROR_OK)
103            return error;
104        *export_data = KeymasterBlob(my_export_data.data, my_export_data.data_length);
105        free(const_cast<uint8_t*>(my_export_data.data));
106        if (export_data->data == nullptr) {
107            return KM_ERROR_MEMORY_ALLOCATION_FAILED;
108        }
109        return error;
110    }
111    keymaster_error_t DeleteKey(const KeymasterKeyBlob& blob) const override {
112        return km_device_->delete_key(km_device_, &blob);
113    }
114    keymaster_error_t DeleteAllKeys() const override {
115        return km_device_->delete_all_keys(km_device_);
116    }
117    OperationFactory* GetOperationFactory(keymaster_purpose_t purpose,
118                                          keymaster_algorithm_t algorithm) const override {
119        switch(algorithm) {
120        case KM_ALGORITHM_RSA:
121            switch(purpose) {
122            case KM_PURPOSE_ENCRYPT:
123                return rsa_encrypt_op_factory_.get();
124            case KM_PURPOSE_DECRYPT:
125                return rsa_decrypt_op_factory_.get();
126            case KM_PURPOSE_SIGN:
127                return rsa_sign_op_factory_.get();
128            case KM_PURPOSE_VERIFY:
129                return rsa_verify_op_factory_.get();
130            default:
131                return nullptr;
132            }
133        case KM_ALGORITHM_EC:
134            switch(purpose) {
135            case KM_PURPOSE_ENCRYPT:
136                return ec_encrypt_op_factory_.get();
137            case KM_PURPOSE_DECRYPT:
138                return ec_decrypt_op_factory_.get();
139            case KM_PURPOSE_SIGN:
140                return ec_sign_op_factory_.get();
141            case KM_PURPOSE_VERIFY:
142                return ec_verify_op_factory_.get();
143            case KM_PURPOSE_DERIVE_KEY:
144                return ec_derive_op_factory_.get();
145            default:
146                return nullptr;
147            }
148        case KM_ALGORITHM_AES:
149            switch(purpose) {
150            case KM_PURPOSE_ENCRYPT:
151                return aes_encrypt_op_factory_.get();
152            case KM_PURPOSE_DECRYPT:
153                return aes_decrypt_op_factory_.get();
154            default:
155                return nullptr;
156            }
157        case KM_ALGORITHM_TRIPLE_DES:
158            switch (purpose) {
159            case KM_PURPOSE_ENCRYPT:
160                return triple_des_encrypt_op_factory_.get();
161            case KM_PURPOSE_DECRYPT:
162                return triple_des_decrypt_op_factory_.get();
163            default:
164                return nullptr;
165            }
166        case KM_ALGORITHM_HMAC:
167            switch (purpose) {
168            case KM_PURPOSE_SIGN:
169                return hmac_sign_op_factory_.get();
170            case KM_PURPOSE_VERIFY:
171                return hmac_verify_op_factory_.get();
172            default:
173                return nullptr;
174            }
175        }
176    }
177
178    const KeymasterDeviceType* device() const { return km_device_; }
179
180  private:
181    TKeymasterPassthroughEngine(const KeymasterPassthroughEngine&) = delete;  // Uncopyable
182    void operator=(const KeymasterPassthroughEngine&) = delete;    // Unassignable
183
184    const KeymasterDeviceType* const km_device_;
185    std::unique_ptr<opfactory_t> rsa_encrypt_op_factory_;
186    std::unique_ptr<opfactory_t> rsa_decrypt_op_factory_;
187    std::unique_ptr<opfactory_t> rsa_sign_op_factory_;
188    std::unique_ptr<opfactory_t> rsa_verify_op_factory_;
189    std::unique_ptr<opfactory_t> ec_encrypt_op_factory_;
190    std::unique_ptr<opfactory_t> ec_decrypt_op_factory_;
191    std::unique_ptr<opfactory_t> ec_sign_op_factory_;
192    std::unique_ptr<opfactory_t> ec_verify_op_factory_;
193    std::unique_ptr<opfactory_t> ec_derive_op_factory_;
194    std::unique_ptr<opfactory_t> aes_encrypt_op_factory_;
195    std::unique_ptr<opfactory_t> aes_decrypt_op_factory_;
196    std::unique_ptr<opfactory_t> triple_des_encrypt_op_factory_;
197    std::unique_ptr<opfactory_t> triple_des_decrypt_op_factory_;
198    std::unique_ptr<opfactory_t> hmac_sign_op_factory_;
199    std::unique_ptr<opfactory_t> hmac_verify_op_factory_;
200};
201
202static void ConvertCharacteristics(const keymaster_key_characteristics_t& characteristics,
203                                   AuthorizationSet* hw_enforced, AuthorizationSet* sw_enforced) {
204    if (hw_enforced)
205        hw_enforced->Reinitialize(characteristics.hw_enforced);
206    if (sw_enforced)
207        sw_enforced->Reinitialize(characteristics.sw_enforced);
208}
209
210template<>
211keymaster_error_t
212TKeymasterPassthroughEngine<keymaster1_device_t>::GenerateKey(const AuthorizationSet& key_description,
213                                                KeymasterKeyBlob* key_blob,
214                                                AuthorizationSet* hw_enforced,
215                                                AuthorizationSet* sw_enforced) const {
216    assert(key_blob);
217
218    keymaster_key_characteristics_t* characteristics = nullptr;
219    keymaster_key_blob_t blob = {};
220    keymaster_error_t error = km_device_->generate_key(km_device_, &key_description,
221                                                               &blob, &characteristics);
222    if (error != KM_ERROR_OK)
223        return error;
224    unique_ptr<uint8_t, Malloc_Delete> blob_deleter(const_cast<uint8_t*>(blob.key_material));
225    key_blob->key_material = dup_buffer(blob.key_material, blob.key_material_size);
226    key_blob->key_material_size = blob.key_material_size;
227
228    ConvertCharacteristics(*characteristics, hw_enforced, sw_enforced);
229    keymaster_free_characteristics(characteristics);
230    free (characteristics);
231    return error;
232}
233template<>
234keymaster_error_t
235TKeymasterPassthroughEngine<keymaster2_device_t>::GenerateKey(const AuthorizationSet& key_description,
236                                                KeymasterKeyBlob* key_blob,
237                                                AuthorizationSet* hw_enforced,
238                                                AuthorizationSet* sw_enforced) const {
239    assert(key_blob);
240
241    keymaster_key_characteristics_t characteristics = {};
242    keymaster_key_blob_t blob = {};
243    keymaster_error_t error = km_device_->generate_key(km_device_, &key_description,
244                                                               &blob, &characteristics);
245    if (error != KM_ERROR_OK)
246        return error;
247    unique_ptr<uint8_t, Malloc_Delete> blob_deleter(const_cast<uint8_t*>(blob.key_material));
248    key_blob->key_material = dup_buffer(blob.key_material, blob.key_material_size);
249    key_blob->key_material_size = blob.key_material_size;
250
251    ConvertCharacteristics(characteristics, hw_enforced, sw_enforced);
252    keymaster_free_characteristics(&characteristics);
253    return error;
254}
255
256template<>
257keymaster_error_t
258TKeymasterPassthroughEngine<keymaster1_device_t>::ImportKey(const AuthorizationSet& key_description,
259                                              keymaster_key_format_t input_key_material_format,
260                                              const KeymasterKeyBlob& input_key_material,
261                                              KeymasterKeyBlob* output_key_blob,
262                                              AuthorizationSet* hw_enforced,
263                                              AuthorizationSet* sw_enforced) const {
264    assert(output_key_blob);
265
266    keymaster_key_characteristics_t* characteristics = {};
267    const keymaster_blob_t input_key = {input_key_material.key_material,
268                                        input_key_material.key_material_size};
269    keymaster_key_blob_t blob = {};
270    keymaster_error_t error = km_device_->import_key(km_device_, &key_description,
271                                                     input_key_material_format, &input_key,
272                                                     &blob, &characteristics);
273    if (error != KM_ERROR_OK)
274        return error;
275    unique_ptr<uint8_t, Malloc_Delete> blob_deleter(const_cast<uint8_t*>(blob.key_material));
276
277    *output_key_blob = KeymasterKeyBlob(blob);
278
279    ConvertCharacteristics(*characteristics, hw_enforced, sw_enforced);
280    keymaster_free_characteristics(characteristics);
281    free(characteristics);
282    return error;
283}
284
285template<>
286keymaster_error_t
287TKeymasterPassthroughEngine<keymaster2_device_t>::ImportKey(const AuthorizationSet& key_description,
288                                              keymaster_key_format_t input_key_material_format,
289                                              const KeymasterKeyBlob& input_key_material,
290                                              KeymasterKeyBlob* output_key_blob,
291                                              AuthorizationSet* hw_enforced,
292                                              AuthorizationSet* sw_enforced) const {
293    assert(output_key_blob);
294
295    keymaster_key_characteristics_t characteristics = {};
296    const keymaster_blob_t input_key = {input_key_material.key_material,
297                                        input_key_material.key_material_size};
298    keymaster_key_blob_t blob = {};
299    keymaster_error_t error = km_device_->import_key(km_device_, &key_description,
300                                                     input_key_material_format, &input_key,
301                                                     &blob, &characteristics);
302    if (error != KM_ERROR_OK)
303        return error;
304    unique_ptr<uint8_t, Malloc_Delete> blob_deleter(const_cast<uint8_t*>(blob.key_material));
305    // TODO why duplicate the blob if we have ownership here anyway?
306    output_key_blob->key_material = dup_buffer(blob.key_material, blob.key_material_size);
307    output_key_blob->key_material_size = blob.key_material_size;
308
309    ConvertCharacteristics(characteristics, hw_enforced, sw_enforced);
310    keymaster_free_characteristics(&characteristics);
311    return error;
312}
313
314typedef UniquePtr<KeymasterPassthroughEngine> engine_ptr_t;
315
316engine_ptr_t
317KeymasterPassthroughEngine::createInstance(const keymaster1_device_t* dev) {
318    return engine_ptr_t(new TKeymasterPassthroughEngine<keymaster1_device_t>(dev));
319}
320engine_ptr_t
321KeymasterPassthroughEngine::createInstance(const keymaster2_device_t* dev) {
322    return engine_ptr_t(new TKeymasterPassthroughEngine<keymaster2_device_t>(dev));
323}
324
325}  // namespace keymaster
326