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