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 #include <keymaster/km_openssl/ecdsa_operation.h>
18 
19 #include <openssl/ecdsa.h>
20 
21 #include <keymaster/km_openssl/ec_key.h>
22 #include <keymaster/km_openssl/openssl_err.h>
23 #include <keymaster/km_openssl/openssl_utils.h>
24 
25 namespace keymaster {
26 
27 static const keymaster_digest_t supported_digests[] = {KM_DIGEST_NONE,      KM_DIGEST_SHA1,
28                                                        KM_DIGEST_SHA_2_224, KM_DIGEST_SHA_2_256,
29                                                        KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512};
30 
CreateOperation(Key && key,const AuthorizationSet & begin_params,keymaster_error_t * error)31 OperationPtr EcdsaOperationFactory::CreateOperation(Key&& key, const AuthorizationSet& begin_params,
32                                                     keymaster_error_t* error) {
33     const EcKey& ecdsa_key = static_cast<EcKey&>(key);
34 
35     UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(EVP_PKEY_new());
36     if (!ecdsa_key.InternalToEvp(pkey.get())) {
37         *error = KM_ERROR_UNKNOWN_ERROR;
38         return nullptr;
39     }
40 
41     keymaster_digest_t digest;
42     if (!GetAndValidateDigest(begin_params, ecdsa_key, &digest, error, true)) {
43         return nullptr;
44     }
45 
46     *error = KM_ERROR_OK;
47     auto op = OperationPtr(InstantiateOperation(key.hw_enforced_move(), key.sw_enforced_move(),
48                                                 digest, pkey.release()));
49     if (!op) *error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
50     return op;
51 }
52 
SupportedDigests(size_t * digest_count) const53 const keymaster_digest_t* EcdsaOperationFactory::SupportedDigests(size_t* digest_count) const {
54     *digest_count = array_length(supported_digests);
55     return supported_digests;
56 }
57 
~EcdsaOperation()58 EcdsaOperation::~EcdsaOperation() {
59     if (ecdsa_key_ != nullptr)
60         EVP_PKEY_free(ecdsa_key_);
61     EVP_MD_CTX_cleanup(&digest_ctx_);
62 }
63 
InitDigest()64 keymaster_error_t EcdsaOperation::InitDigest() {
65     switch (digest_) {
66     case KM_DIGEST_NONE:
67         return KM_ERROR_OK;
68     case KM_DIGEST_MD5:
69         return KM_ERROR_UNSUPPORTED_DIGEST;
70     case KM_DIGEST_SHA1:
71         digest_algorithm_ = EVP_sha1();
72         return KM_ERROR_OK;
73     case KM_DIGEST_SHA_2_224:
74         digest_algorithm_ = EVP_sha224();
75         return KM_ERROR_OK;
76     case KM_DIGEST_SHA_2_256:
77         digest_algorithm_ = EVP_sha256();
78         return KM_ERROR_OK;
79     case KM_DIGEST_SHA_2_384:
80         digest_algorithm_ = EVP_sha384();
81         return KM_ERROR_OK;
82     case KM_DIGEST_SHA_2_512:
83         digest_algorithm_ = EVP_sha512();
84         return KM_ERROR_OK;
85     default:
86         return KM_ERROR_UNSUPPORTED_DIGEST;
87     }
88 }
89 
min(size_t a,size_t b)90 inline size_t min(size_t a, size_t b) {
91     return (a < b) ? a : b;
92 }
93 
StoreData(const Buffer & input,size_t * input_consumed)94 keymaster_error_t EcdsaOperation::StoreData(const Buffer& input, size_t* input_consumed) {
95     if (!data_.reserve((EVP_PKEY_bits(ecdsa_key_) + 7) / 8))
96         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
97 
98     if (!data_.write(input.peek_read(), min(data_.available_write(), input.available_read())))
99         return KM_ERROR_UNKNOWN_ERROR;
100 
101     *input_consumed = input.available_read();
102     return KM_ERROR_OK;
103 }
104 
Begin(const AuthorizationSet &,AuthorizationSet *)105 keymaster_error_t EcdsaSignOperation::Begin(const AuthorizationSet& /* input_params */,
106                                             AuthorizationSet* /* output_params */) {
107     auto rc = GenerateRandom(reinterpret_cast<uint8_t*>(&operation_handle_),
108                              (size_t)sizeof(operation_handle_));
109     if (rc != KM_ERROR_OK) return rc;
110 
111     keymaster_error_t error = InitDigest();
112     if (error != KM_ERROR_OK)
113         return error;
114 
115     if (digest_ == KM_DIGEST_NONE)
116         return KM_ERROR_OK;
117 
118     EVP_PKEY_CTX* pkey_ctx;
119     if (EVP_DigestSignInit(&digest_ctx_, &pkey_ctx, digest_algorithm_, nullptr /* engine */,
120                            ecdsa_key_) != 1)
121         return TranslateLastOpenSslError();
122     return KM_ERROR_OK;
123 }
124 
Update(const AuthorizationSet &,const Buffer & input,AuthorizationSet *,Buffer *,size_t * input_consumed)125 keymaster_error_t EcdsaSignOperation::Update(const AuthorizationSet& /* additional_params */,
126                                              const Buffer& input,
127                                              AuthorizationSet* /* output_params */,
128                                              Buffer* /* output */, size_t* input_consumed) {
129     if (digest_ == KM_DIGEST_NONE)
130         return StoreData(input, input_consumed);
131 
132     if (EVP_DigestSignUpdate(&digest_ctx_, input.peek_read(), input.available_read()) != 1)
133         return TranslateLastOpenSslError();
134     *input_consumed = input.available_read();
135     return KM_ERROR_OK;
136 }
137 
Finish(const AuthorizationSet & additional_params,const Buffer & input,const Buffer &,AuthorizationSet *,Buffer * output)138 keymaster_error_t EcdsaSignOperation::Finish(const AuthorizationSet& additional_params,
139                                              const Buffer& input, const Buffer& /* signature */,
140                                              AuthorizationSet* /* output_params */,
141                                              Buffer* output) {
142     if (!output)
143         return KM_ERROR_OUTPUT_PARAMETER_NULL;
144 
145     keymaster_error_t error = UpdateForFinish(additional_params, input);
146     if (error != KM_ERROR_OK)
147         return error;
148 
149     size_t siglen;
150     if (digest_ == KM_DIGEST_NONE) {
151         UniquePtr<EC_KEY, EC_KEY_Delete> ecdsa(EVP_PKEY_get1_EC_KEY(ecdsa_key_));
152         if (!ecdsa.get())
153             return TranslateLastOpenSslError();
154 
155         output->Reinitialize(ECDSA_size(ecdsa.get()));
156         unsigned int siglen_tmp;
157         if (!ECDSA_sign(0 /* type -- ignored */, data_.peek_read(), data_.available_read(),
158                         output->peek_write(), &siglen_tmp, ecdsa.get()))
159             return TranslateLastOpenSslError();
160         siglen = siglen_tmp;
161     } else {
162         if (EVP_DigestSignFinal(&digest_ctx_, nullptr /* signature */, &siglen) != 1)
163             return TranslateLastOpenSslError();
164         if (!output->Reinitialize(siglen))
165             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
166         if (EVP_DigestSignFinal(&digest_ctx_, output->peek_write(), &siglen) <= 0)
167             return TranslateLastOpenSslError();
168     }
169     if (!output->advance_write(siglen))
170         return KM_ERROR_UNKNOWN_ERROR;
171     return KM_ERROR_OK;
172 }
173 
Begin(const AuthorizationSet &,AuthorizationSet *)174 keymaster_error_t EcdsaVerifyOperation::Begin(const AuthorizationSet& /* input_params */,
175                                               AuthorizationSet* /* output_params */) {
176     auto rc = GenerateRandom(reinterpret_cast<uint8_t*>(&operation_handle_),
177                              (size_t)sizeof(operation_handle_));
178     if (rc != KM_ERROR_OK) return rc;
179 
180     keymaster_error_t error = InitDigest();
181     if (error != KM_ERROR_OK)
182         return error;
183 
184     if (digest_ == KM_DIGEST_NONE)
185         return KM_ERROR_OK;
186 
187     EVP_PKEY_CTX* pkey_ctx;
188     if (EVP_DigestVerifyInit(&digest_ctx_, &pkey_ctx, digest_algorithm_, nullptr /* engine */,
189                              ecdsa_key_) != 1)
190         return TranslateLastOpenSslError();
191     return KM_ERROR_OK;
192 }
193 
Update(const AuthorizationSet &,const Buffer & input,AuthorizationSet *,Buffer *,size_t * input_consumed)194 keymaster_error_t EcdsaVerifyOperation::Update(const AuthorizationSet& /* additional_params */,
195                                                const Buffer& input,
196                                                AuthorizationSet* /* output_params */,
197                                                Buffer* /* output */, size_t* input_consumed) {
198     if (digest_ == KM_DIGEST_NONE)
199         return StoreData(input, input_consumed);
200 
201     if (EVP_DigestVerifyUpdate(&digest_ctx_, input.peek_read(), input.available_read()) != 1)
202         return TranslateLastOpenSslError();
203     *input_consumed = input.available_read();
204     return KM_ERROR_OK;
205 }
206 
Finish(const AuthorizationSet & additional_params,const Buffer & input,const Buffer & signature,AuthorizationSet *,Buffer *)207 keymaster_error_t EcdsaVerifyOperation::Finish(const AuthorizationSet& additional_params,
208                                                const Buffer& input, const Buffer& signature,
209                                                AuthorizationSet* /* output_params */,
210                                                Buffer* /* output */) {
211     keymaster_error_t error = UpdateForFinish(additional_params, input);
212     if (error != KM_ERROR_OK)
213         return error;
214 
215     if (digest_ == KM_DIGEST_NONE) {
216         UniquePtr<EC_KEY, EC_KEY_Delete> ecdsa(EVP_PKEY_get1_EC_KEY(ecdsa_key_));
217         if (!ecdsa.get())
218             return TranslateLastOpenSslError();
219 
220         int result =
221             ECDSA_verify(0 /* type -- ignored */, data_.peek_read(), data_.available_read(),
222                          signature.peek_read(), signature.available_read(), ecdsa.get());
223         if (result < 0)
224             return TranslateLastOpenSslError();
225         else if (result == 0)
226             return KM_ERROR_VERIFICATION_FAILED;
227     } else if (!EVP_DigestVerifyFinal(&digest_ctx_, signature.peek_read(),
228                                       signature.available_read()))
229         return KM_ERROR_VERIFICATION_FAILED;
230 
231     return KM_ERROR_OK;
232 }
233 
234 }  // namespace keymaster
235