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