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 "rsa_operation.h"
18 
19 #include <limits.h>
20 
21 #include <new>
22 
23 #include <openssl/err.h>
24 
25 #include <keymaster/logger.h>
26 
27 #include "openssl_err.h"
28 #include "openssl_utils.h"
29 #include "rsa_key.h"
30 
31 namespace keymaster {
32 
33 const size_t kPssOverhead = 2;
34 const size_t kMinPssSaltSize = 20;
35 
36 // Overhead for PKCS#1 v1.5 signature padding of undigested messages.  Digested messages have
37 // additional overhead, for the digest algorithmIdentifier required by PKCS#1.
38 const size_t kPkcs1UndigestedSignaturePaddingOverhead = 11;
39 
40 /* static */
GetRsaKey(const Key & key,keymaster_error_t * error)41 EVP_PKEY* RsaOperationFactory::GetRsaKey(const Key& key, keymaster_error_t* error) {
42     const RsaKey* rsa_key = static_cast<const RsaKey*>(&key);
43     assert(rsa_key);
44     if (!rsa_key || !rsa_key->key()) {
45         *error = KM_ERROR_UNKNOWN_ERROR;
46         return nullptr;
47     }
48 
49     UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(EVP_PKEY_new());
50     if (!rsa_key->InternalToEvp(pkey.get())) {
51         *error = KM_ERROR_UNKNOWN_ERROR;
52         return nullptr;
53     }
54     return pkey.release();
55 }
56 
57 static const keymaster_digest_t supported_digests[] = {
58     KM_DIGEST_NONE,      KM_DIGEST_MD5,       KM_DIGEST_SHA1,     KM_DIGEST_SHA_2_224,
59     KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512};
60 
SupportedDigests(size_t * digest_count) const61 const keymaster_digest_t* RsaOperationFactory::SupportedDigests(size_t* digest_count) const {
62     *digest_count = array_length(supported_digests);
63     return supported_digests;
64 }
65 
CreateRsaOperation(const Key & key,const AuthorizationSet & begin_params,keymaster_error_t * error)66 RsaOperation* RsaOperationFactory::CreateRsaOperation(const Key& key,
67                                                       const AuthorizationSet& begin_params,
68                                                       keymaster_error_t* error) {
69     keymaster_padding_t padding;
70     if (!GetAndValidatePadding(begin_params, key, &padding, error))
71         return nullptr;
72 
73     bool require_digest = (purpose() == KM_PURPOSE_SIGN || purpose() == KM_PURPOSE_VERIFY ||
74                            padding == KM_PAD_RSA_OAEP);
75 
76     keymaster_digest_t digest = KM_DIGEST_NONE;
77     if (require_digest && !GetAndValidateDigest(begin_params, key, &digest, error))
78         return nullptr;
79     if (!require_digest && begin_params.find(TAG_DIGEST) != -1) {
80         *error = KM_ERROR_UNSUPPORTED_DIGEST;
81         return nullptr;
82     }
83 
84     UniquePtr<EVP_PKEY, EVP_PKEY_Delete> rsa(GetRsaKey(key, error));
85     if (!rsa.get())
86         return nullptr;
87 
88     RsaOperation* op = InstantiateOperation(digest, padding, rsa.release());
89     if (!op)
90         *error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
91     return op;
92 }
93 
94 static const keymaster_padding_t supported_sig_padding[] = {KM_PAD_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN,
95                                                             KM_PAD_RSA_PSS};
96 const keymaster_padding_t*
SupportedPaddingModes(size_t * padding_mode_count) const97 RsaDigestingOperationFactory::SupportedPaddingModes(size_t* padding_mode_count) const {
98     *padding_mode_count = array_length(supported_sig_padding);
99     return supported_sig_padding;
100 }
101 
CreateRsaOperation(const Key & key,const AuthorizationSet & begin_params,keymaster_error_t * error)102 RsaOperation* RsaCryptingOperationFactory::CreateRsaOperation(const Key& key,
103                                                               const AuthorizationSet& begin_params,
104                                                               keymaster_error_t* error) {
105     UniquePtr<RsaOperation> op(RsaOperationFactory::CreateRsaOperation(key, begin_params, error));
106     if (op.get()) {
107         switch (op->padding()) {
108         case KM_PAD_NONE:
109         case KM_PAD_RSA_PKCS1_1_5_ENCRYPT:
110             if (op->digest() != KM_DIGEST_NONE) {
111                 *error = KM_ERROR_INCOMPATIBLE_DIGEST;
112                 return nullptr;
113             }
114             break;
115 
116         case KM_PAD_RSA_OAEP:
117             if (op->digest() == KM_DIGEST_NONE) {
118                 *error = KM_ERROR_INCOMPATIBLE_DIGEST;
119                 return nullptr;
120             }
121             break;
122 
123         default:
124             *error = KM_ERROR_UNSUPPORTED_PADDING_MODE;
125             return nullptr;
126         }
127     }
128     return op.release();
129 }
130 
131 static const keymaster_padding_t supported_crypt_padding[] = {KM_PAD_NONE, KM_PAD_RSA_OAEP,
132                                                               KM_PAD_RSA_PKCS1_1_5_ENCRYPT};
133 const keymaster_padding_t*
SupportedPaddingModes(size_t * padding_mode_count) const134 RsaCryptingOperationFactory::SupportedPaddingModes(size_t* padding_mode_count) const {
135     *padding_mode_count = array_length(supported_crypt_padding);
136     return supported_crypt_padding;
137 }
138 
~RsaOperation()139 RsaOperation::~RsaOperation() {
140     if (rsa_key_ != NULL)
141         EVP_PKEY_free(rsa_key_);
142 }
143 
Begin(const AuthorizationSet &,AuthorizationSet *)144 keymaster_error_t RsaOperation::Begin(const AuthorizationSet& /* input_params */,
145                                       AuthorizationSet* /* output_params */) {
146     return InitDigest();
147 }
148 
Update(const AuthorizationSet &,const Buffer & input,AuthorizationSet *,Buffer *,size_t * input_consumed)149 keymaster_error_t RsaOperation::Update(const AuthorizationSet& /* additional_params */,
150                                        const Buffer& input, AuthorizationSet* /* output_params */,
151                                        Buffer* /* output */, size_t* input_consumed) {
152     assert(input_consumed);
153     switch (purpose()) {
154     default:
155         return KM_ERROR_UNIMPLEMENTED;
156     case KM_PURPOSE_SIGN:
157     case KM_PURPOSE_VERIFY:
158     case KM_PURPOSE_ENCRYPT:
159     case KM_PURPOSE_DECRYPT:
160         return StoreData(input, input_consumed);
161     }
162 }
163 
StoreData(const Buffer & input,size_t * input_consumed)164 keymaster_error_t RsaOperation::StoreData(const Buffer& input, size_t* input_consumed) {
165     assert(input_consumed);
166 
167     if (!data_.reserve(EVP_PKEY_size(rsa_key_)))
168         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
169     // If the write fails, it's because input length exceeds key size.
170     if (!data_.write(input.peek_read(), input.available_read())) {
171         LOG_E("Input too long: cannot operate on %u bytes of data with %u-byte RSA key",
172               input.available_read() + data_.available_read(), EVP_PKEY_size(rsa_key_));
173         return KM_ERROR_INVALID_INPUT_LENGTH;
174     }
175 
176     *input_consumed = input.available_read();
177     return KM_ERROR_OK;
178 }
179 
SetRsaPaddingInEvpContext(EVP_PKEY_CTX * pkey_ctx)180 keymaster_error_t RsaOperation::SetRsaPaddingInEvpContext(EVP_PKEY_CTX* pkey_ctx) {
181     keymaster_error_t error;
182     int openssl_padding = GetOpensslPadding(&error);
183     if (error != KM_ERROR_OK)
184         return error;
185 
186     if (EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, openssl_padding) <= 0)
187         return TranslateLastOpenSslError();
188     return KM_ERROR_OK;
189 }
190 
InitDigest()191 keymaster_error_t RsaOperation::InitDigest() {
192     if (digest_ == KM_DIGEST_NONE) {
193         if (require_digest())
194             return KM_ERROR_INCOMPATIBLE_DIGEST;
195         return KM_ERROR_OK;
196     }
197 
198     switch (digest_) {
199     case KM_DIGEST_NONE:
200         return KM_ERROR_OK;
201     case KM_DIGEST_MD5:
202         digest_algorithm_ = EVP_md5();
203         return KM_ERROR_OK;
204     case KM_DIGEST_SHA1:
205         digest_algorithm_ = EVP_sha1();
206         return KM_ERROR_OK;
207     case KM_DIGEST_SHA_2_224:
208         digest_algorithm_ = EVP_sha224();
209         return KM_ERROR_OK;
210     case KM_DIGEST_SHA_2_256:
211         digest_algorithm_ = EVP_sha256();
212         return KM_ERROR_OK;
213     case KM_DIGEST_SHA_2_384:
214         digest_algorithm_ = EVP_sha384();
215         return KM_ERROR_OK;
216     case KM_DIGEST_SHA_2_512:
217         digest_algorithm_ = EVP_sha512();
218         return KM_ERROR_OK;
219     default:
220         return KM_ERROR_UNSUPPORTED_DIGEST;
221     }
222 }
223 
RsaDigestingOperation(keymaster_purpose_t purpose,keymaster_digest_t digest,keymaster_padding_t padding,EVP_PKEY * key)224 RsaDigestingOperation::RsaDigestingOperation(keymaster_purpose_t purpose, keymaster_digest_t digest,
225                                              keymaster_padding_t padding, EVP_PKEY* key)
226     : RsaOperation(purpose, digest, padding, key) {
227     EVP_MD_CTX_init(&digest_ctx_);
228 }
~RsaDigestingOperation()229 RsaDigestingOperation::~RsaDigestingOperation() {
230     EVP_MD_CTX_cleanup(&digest_ctx_);
231 }
232 
GetOpensslPadding(keymaster_error_t * error)233 int RsaDigestingOperation::GetOpensslPadding(keymaster_error_t* error) {
234     *error = KM_ERROR_OK;
235     switch (padding_) {
236     case KM_PAD_NONE:
237         return RSA_NO_PADDING;
238     case KM_PAD_RSA_PKCS1_1_5_SIGN:
239         return RSA_PKCS1_PADDING;
240     case KM_PAD_RSA_PSS:
241         if (digest_ == KM_DIGEST_NONE) {
242             *error = KM_ERROR_INCOMPATIBLE_PADDING_MODE;
243             return -1;
244         }
245         if (EVP_MD_size(digest_algorithm_) + kPssOverhead + kMinPssSaltSize >
246             (size_t)EVP_PKEY_size(rsa_key_)) {
247             LOG_E("Input too long: %d-byte digest cannot be used with %d-byte RSA key in PSS "
248                   "padding mode",
249                   EVP_MD_size(digest_algorithm_), EVP_PKEY_size(rsa_key_));
250             *error = KM_ERROR_INCOMPATIBLE_DIGEST;
251             return -1;
252         }
253         return RSA_PKCS1_PSS_PADDING;
254     default:
255         return -1;
256     }
257 }
258 
Begin(const AuthorizationSet & input_params,AuthorizationSet * output_params)259 keymaster_error_t RsaSignOperation::Begin(const AuthorizationSet& input_params,
260                                           AuthorizationSet* output_params) {
261     keymaster_error_t error = RsaDigestingOperation::Begin(input_params, output_params);
262     if (error != KM_ERROR_OK)
263         return error;
264 
265     if (digest_ == KM_DIGEST_NONE)
266         return KM_ERROR_OK;
267 
268     EVP_PKEY_CTX* pkey_ctx;
269     if (EVP_DigestSignInit(&digest_ctx_, &pkey_ctx, digest_algorithm_, nullptr /* engine */,
270                            rsa_key_) != 1)
271         return TranslateLastOpenSslError();
272     return SetRsaPaddingInEvpContext(pkey_ctx);
273 }
274 
Update(const AuthorizationSet & additional_params,const Buffer & input,AuthorizationSet * output_params,Buffer * output,size_t * input_consumed)275 keymaster_error_t RsaSignOperation::Update(const AuthorizationSet& additional_params,
276                                            const Buffer& input, AuthorizationSet* output_params,
277                                            Buffer* output, size_t* input_consumed) {
278     if (digest_ == KM_DIGEST_NONE)
279         // Just buffer the data.
280         return RsaOperation::Update(additional_params, input, output_params, output,
281                                     input_consumed);
282 
283     if (EVP_DigestSignUpdate(&digest_ctx_, input.peek_read(), input.available_read()) != 1)
284         return TranslateLastOpenSslError();
285     *input_consumed = input.available_read();
286     return KM_ERROR_OK;
287 }
288 
Finish(const AuthorizationSet &,const Buffer &,AuthorizationSet *,Buffer * output)289 keymaster_error_t RsaSignOperation::Finish(const AuthorizationSet& /* additional_params */,
290                                            const Buffer& /* signature */,
291                                            AuthorizationSet* /* output_params */, Buffer* output) {
292     assert(output);
293 
294     if (digest_ == KM_DIGEST_NONE)
295         return SignUndigested(output);
296     else
297         return SignDigested(output);
298 }
299 
zero_pad_left(UniquePtr<uint8_t[]> * dest,size_t padded_len,Buffer & src)300 static keymaster_error_t zero_pad_left(UniquePtr<uint8_t[]>* dest, size_t padded_len, Buffer& src) {
301     assert(padded_len > src.available_read());
302 
303     dest->reset(new uint8_t[padded_len]);
304     if (!dest->get())
305         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
306 
307     size_t padding_len = padded_len - src.available_read();
308     memset(dest->get(), 0, padding_len);
309     if (!src.read(dest->get() + padding_len, src.available_read()))
310         return KM_ERROR_UNKNOWN_ERROR;
311 
312     return KM_ERROR_OK;
313 }
314 
SignUndigested(Buffer * output)315 keymaster_error_t RsaSignOperation::SignUndigested(Buffer* output) {
316     UniquePtr<RSA, RSA_Delete> rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(rsa_key_)));
317     if (!rsa.get())
318         return TranslateLastOpenSslError();
319 
320     if (!output->Reinitialize(RSA_size(rsa.get())))
321         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
322 
323     size_t key_len = EVP_PKEY_size(rsa_key_);
324     int bytes_encrypted;
325     switch (padding_) {
326     case KM_PAD_NONE: {
327         const uint8_t* to_encrypt = data_.peek_read();
328         UniquePtr<uint8_t[]> zero_padded;
329         if (data_.available_read() > key_len) {
330             return KM_ERROR_INVALID_INPUT_LENGTH;
331         } else if (data_.available_read() < key_len) {
332             keymaster_error_t error = zero_pad_left(&zero_padded, key_len, data_);
333             if (error != KM_ERROR_OK)
334                 return error;
335             to_encrypt = zero_padded.get();
336         }
337         bytes_encrypted = RSA_private_encrypt(key_len, to_encrypt, output->peek_write(), rsa.get(),
338                                               RSA_NO_PADDING);
339         break;
340     }
341     case KM_PAD_RSA_PKCS1_1_5_SIGN:
342         // Does PKCS1 padding without digesting even make sense?  Dunno.  We'll support it.
343         if (data_.available_read() + kPkcs1UndigestedSignaturePaddingOverhead > key_len) {
344             LOG_E("Input too long: cannot sign %u-byte message with PKCS1 padding with %u-bit key",
345                   data_.available_read(), EVP_PKEY_size(rsa_key_) * 8);
346             return KM_ERROR_INVALID_INPUT_LENGTH;
347         }
348         bytes_encrypted = RSA_private_encrypt(data_.available_read(), data_.peek_read(),
349                                               output->peek_write(), rsa.get(), RSA_PKCS1_PADDING);
350         break;
351 
352     default:
353         return KM_ERROR_UNSUPPORTED_PADDING_MODE;
354     }
355 
356     if (bytes_encrypted <= 0)
357         return TranslateLastOpenSslError();
358     if (!output->advance_write(bytes_encrypted))
359         return KM_ERROR_UNKNOWN_ERROR;
360     return KM_ERROR_OK;
361 }
362 
SignDigested(Buffer * output)363 keymaster_error_t RsaSignOperation::SignDigested(Buffer* output) {
364     size_t siglen;
365     if (EVP_DigestSignFinal(&digest_ctx_, nullptr /* signature */, &siglen) != 1)
366         return TranslateLastOpenSslError();
367 
368     if (!output->Reinitialize(siglen))
369         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
370 
371     if (EVP_DigestSignFinal(&digest_ctx_, output->peek_write(), &siglen) <= 0)
372         return TranslateLastOpenSslError();
373     if (!output->advance_write(siglen))
374         return KM_ERROR_UNKNOWN_ERROR;
375 
376     return KM_ERROR_OK;
377 }
378 
Begin(const AuthorizationSet & input_params,AuthorizationSet * output_params)379 keymaster_error_t RsaVerifyOperation::Begin(const AuthorizationSet& input_params,
380                                             AuthorizationSet* output_params) {
381     keymaster_error_t error = RsaDigestingOperation::Begin(input_params, output_params);
382     if (error != KM_ERROR_OK)
383         return error;
384 
385     if (digest_ == KM_DIGEST_NONE)
386         return KM_ERROR_OK;
387 
388     EVP_PKEY_CTX* pkey_ctx;
389     if (EVP_DigestVerifyInit(&digest_ctx_, &pkey_ctx, digest_algorithm_, NULL, rsa_key_) != 1)
390         return TranslateLastOpenSslError();
391     return SetRsaPaddingInEvpContext(pkey_ctx);
392 }
393 
Update(const AuthorizationSet & additional_params,const Buffer & input,AuthorizationSet * output_params,Buffer * output,size_t * input_consumed)394 keymaster_error_t RsaVerifyOperation::Update(const AuthorizationSet& additional_params,
395                                              const Buffer& input, AuthorizationSet* output_params,
396                                              Buffer* output, size_t* input_consumed) {
397     if (digest_ == KM_DIGEST_NONE)
398         // Just buffer the data.
399         return RsaOperation::Update(additional_params, input, output_params, output,
400                                     input_consumed);
401 
402     if (EVP_DigestVerifyUpdate(&digest_ctx_, input.peek_read(), input.available_read()) != 1)
403         return TranslateLastOpenSslError();
404     *input_consumed = input.available_read();
405     return KM_ERROR_OK;
406 }
407 
Finish(const AuthorizationSet &,const Buffer & signature,AuthorizationSet *,Buffer *)408 keymaster_error_t RsaVerifyOperation::Finish(const AuthorizationSet& /* additional_params */,
409                                              const Buffer& signature,
410                                              AuthorizationSet* /* output_params */,
411                                              Buffer* /* output */) {
412     if (digest_ == KM_DIGEST_NONE)
413         return VerifyUndigested(signature);
414     else
415         return VerifyDigested(signature);
416 }
417 
VerifyUndigested(const Buffer & signature)418 keymaster_error_t RsaVerifyOperation::VerifyUndigested(const Buffer& signature) {
419     UniquePtr<RSA, RSA_Delete> rsa(EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(rsa_key_)));
420     if (!rsa.get())
421         return KM_ERROR_UNKNOWN_ERROR;
422 
423     size_t key_len = RSA_size(rsa.get());
424     int openssl_padding;
425     switch (padding_) {
426     case KM_PAD_NONE:
427         if (data_.available_read() > key_len)
428             return KM_ERROR_INVALID_INPUT_LENGTH;
429         if (key_len != signature.available_read())
430             return KM_ERROR_VERIFICATION_FAILED;
431         openssl_padding = RSA_NO_PADDING;
432         break;
433     case KM_PAD_RSA_PKCS1_1_5_SIGN:
434         if (data_.available_read() + kPkcs1UndigestedSignaturePaddingOverhead > key_len) {
435             LOG_E("Input too long: cannot verify %u-byte message with PKCS1 padding && %u-bit key",
436                   data_.available_read(), key_len * 8);
437             return KM_ERROR_INVALID_INPUT_LENGTH;
438         }
439         openssl_padding = RSA_PKCS1_PADDING;
440         break;
441     default:
442         return KM_ERROR_UNSUPPORTED_PADDING_MODE;
443     }
444 
445     UniquePtr<uint8_t[]> decrypted_data(new (std::nothrow) uint8_t[key_len]);
446     if (!decrypted_data.get())
447         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
448     int bytes_decrypted = RSA_public_decrypt(signature.available_read(), signature.peek_read(),
449                                              decrypted_data.get(), rsa.get(), openssl_padding);
450     if (bytes_decrypted < 0)
451         return KM_ERROR_VERIFICATION_FAILED;
452 
453     const uint8_t* compare_pos = decrypted_data.get();
454     size_t bytes_to_compare = bytes_decrypted;
455     uint8_t zero_check_result = 0;
456     if (padding_ == KM_PAD_NONE && data_.available_read() < bytes_to_compare) {
457         // If the data is short, for "unpadded" signing we zero-pad to the left.  So during
458         // verification we should have zeros on the left of the decrypted data.  Do a constant-time
459         // check.
460         const uint8_t* zero_end = compare_pos + bytes_to_compare - data_.available_read();
461         while (compare_pos < zero_end)
462             zero_check_result |= *compare_pos++;
463         bytes_to_compare = data_.available_read();
464     }
465     if (memcmp_s(compare_pos, data_.peek_read(), bytes_to_compare) != 0 || zero_check_result != 0)
466         return KM_ERROR_VERIFICATION_FAILED;
467     return KM_ERROR_OK;
468 }
469 
VerifyDigested(const Buffer & signature)470 keymaster_error_t RsaVerifyOperation::VerifyDigested(const Buffer& signature) {
471     if (!EVP_DigestVerifyFinal(&digest_ctx_, signature.peek_read(), signature.available_read()))
472         return KM_ERROR_VERIFICATION_FAILED;
473     return KM_ERROR_OK;
474 }
475 
SetOaepDigestIfRequired(EVP_PKEY_CTX * pkey_ctx)476 keymaster_error_t RsaCryptOperation::SetOaepDigestIfRequired(EVP_PKEY_CTX* pkey_ctx) {
477     if (padding() != KM_PAD_RSA_OAEP)
478         return KM_ERROR_OK;
479 
480     assert(digest_algorithm_ != nullptr);
481     if (!EVP_PKEY_CTX_set_rsa_oaep_md(pkey_ctx, digest_algorithm_))
482         return TranslateLastOpenSslError();
483 
484     // MGF1 MD is always SHA1.
485     if (!EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, EVP_sha1()))
486         return TranslateLastOpenSslError();
487 
488     return KM_ERROR_OK;
489 }
490 
GetOpensslPadding(keymaster_error_t * error)491 int RsaCryptOperation::GetOpensslPadding(keymaster_error_t* error) {
492     *error = KM_ERROR_OK;
493     switch (padding_) {
494     case KM_PAD_NONE:
495         return RSA_NO_PADDING;
496     case KM_PAD_RSA_PKCS1_1_5_ENCRYPT:
497         return RSA_PKCS1_PADDING;
498     case KM_PAD_RSA_OAEP:
499         return RSA_PKCS1_OAEP_PADDING;
500     default:
501         return -1;
502     }
503 }
504 
505 struct EVP_PKEY_CTX_Delete {
operator ()keymaster::EVP_PKEY_CTX_Delete506     void operator()(EVP_PKEY_CTX* p) { EVP_PKEY_CTX_free(p); }
507 };
508 
Finish(const AuthorizationSet &,const Buffer &,AuthorizationSet *,Buffer * output)509 keymaster_error_t RsaEncryptOperation::Finish(const AuthorizationSet& /* additional_params */,
510                                               const Buffer& /* signature */,
511                                               AuthorizationSet* /* output_params */,
512                                               Buffer* output) {
513     assert(output);
514 
515     UniquePtr<EVP_PKEY_CTX, EVP_PKEY_CTX_Delete> ctx(
516         EVP_PKEY_CTX_new(rsa_key_, nullptr /* engine */));
517     if (!ctx.get())
518         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
519 
520     if (EVP_PKEY_encrypt_init(ctx.get()) <= 0)
521         return TranslateLastOpenSslError();
522 
523     keymaster_error_t error = SetRsaPaddingInEvpContext(ctx.get());
524     if (error != KM_ERROR_OK)
525         return error;
526     error = SetOaepDigestIfRequired(ctx.get());
527     if (error != KM_ERROR_OK)
528         return error;
529 
530     size_t outlen;
531     if (EVP_PKEY_encrypt(ctx.get(), nullptr /* out */, &outlen, data_.peek_read(),
532                          data_.available_read()) <= 0)
533         return TranslateLastOpenSslError();
534 
535     if (!output->Reinitialize(outlen))
536         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
537 
538     const uint8_t* to_encrypt = data_.peek_read();
539     size_t to_encrypt_len = data_.available_read();
540     UniquePtr<uint8_t[]> zero_padded;
541     if (padding_ == KM_PAD_NONE && to_encrypt_len < outlen) {
542         keymaster_error_t error = zero_pad_left(&zero_padded, outlen, data_);
543         if (error != KM_ERROR_OK)
544             return error;
545         to_encrypt = zero_padded.get();
546         to_encrypt_len = outlen;
547     }
548 
549     if (EVP_PKEY_encrypt(ctx.get(), output->peek_write(), &outlen, to_encrypt, to_encrypt_len) <= 0)
550         return TranslateLastOpenSslError();
551     if (!output->advance_write(outlen))
552         return KM_ERROR_UNKNOWN_ERROR;
553 
554     return KM_ERROR_OK;
555 }
556 
Finish(const AuthorizationSet &,const Buffer &,AuthorizationSet *,Buffer * output)557 keymaster_error_t RsaDecryptOperation::Finish(const AuthorizationSet& /* additional_params */,
558                                               const Buffer& /* signature */,
559                                               AuthorizationSet* /* output_params */,
560                                               Buffer* output) {
561     assert(output);
562 
563     UniquePtr<EVP_PKEY_CTX, EVP_PKEY_CTX_Delete> ctx(
564         EVP_PKEY_CTX_new(rsa_key_, nullptr /* engine */));
565     if (!ctx.get())
566         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
567 
568     if (EVP_PKEY_decrypt_init(ctx.get()) <= 0)
569         return TranslateLastOpenSslError();
570 
571     keymaster_error_t error = SetRsaPaddingInEvpContext(ctx.get());
572     if (error != KM_ERROR_OK)
573         return error;
574     error = SetOaepDigestIfRequired(ctx.get());
575     if (error != KM_ERROR_OK)
576         return error;
577 
578     size_t outlen;
579     if (EVP_PKEY_decrypt(ctx.get(), nullptr /* out */, &outlen, data_.peek_read(),
580                          data_.available_read()) <= 0)
581         return TranslateLastOpenSslError();
582 
583     if (!output->Reinitialize(outlen))
584         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
585 
586     const uint8_t* to_decrypt = data_.peek_read();
587     size_t to_decrypt_len = data_.available_read();
588     UniquePtr<uint8_t[]> zero_padded;
589     if (padding_ == KM_PAD_NONE && to_decrypt_len < outlen) {
590         keymaster_error_t error = zero_pad_left(&zero_padded, outlen, data_);
591         if (error != KM_ERROR_OK)
592             return error;
593         to_decrypt = zero_padded.get();
594         to_decrypt_len = outlen;
595     }
596 
597     if (EVP_PKEY_decrypt(ctx.get(), output->peek_write(), &outlen, to_decrypt, to_decrypt_len) <= 0)
598         return TranslateLastOpenSslError();
599     if (!output->advance_write(outlen))
600         return KM_ERROR_UNKNOWN_ERROR;
601 
602     return KM_ERROR_OK;
603 }
604 
605 }  // namespace keymaster
606