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 "aes_operation.h"
18 
19 #include <stdio.h>
20 
21 #include <new>
22 
23 #include <UniquePtr.h>
24 
25 #include <openssl/aes.h>
26 #include <openssl/err.h>
27 #include <openssl/rand.h>
28 
29 #include <keymaster/logger.h>
30 
31 #include "aes_key.h"
32 #include "openssl_err.h"
33 
34 namespace keymaster {
35 
36 static const size_t GCM_NONCE_SIZE = 12;
37 
allows_padding(keymaster_block_mode_t block_mode)38 inline bool allows_padding(keymaster_block_mode_t block_mode) {
39     switch (block_mode) {
40     case KM_MODE_CTR:
41     case KM_MODE_GCM:
42         return false;
43     case KM_MODE_ECB:
44     case KM_MODE_CBC:
45         return true;
46     }
47     assert(false /* Can't get here */);
48     return false;
49 }
50 
GetAndValidateGcmTagLength(const AuthorizationSet & begin_params,const AuthorizationSet & key_params,size_t * tag_length)51 static keymaster_error_t GetAndValidateGcmTagLength(const AuthorizationSet& begin_params,
52                                                     const AuthorizationSet& key_params,
53                                                     size_t* tag_length) {
54     uint32_t tag_length_bits;
55     if (!begin_params.GetTagValue(TAG_MAC_LENGTH, &tag_length_bits)) {
56         return KM_ERROR_MISSING_MAC_LENGTH;
57     }
58 
59     uint32_t min_tag_length_bits;
60     if (!key_params.GetTagValue(TAG_MIN_MAC_LENGTH, &min_tag_length_bits)) {
61         LOG_E("AES GCM key must have KM_TAG_MIN_MAC_LENGTH", 0);
62         return KM_ERROR_INVALID_KEY_BLOB;
63     }
64 
65     if (tag_length_bits % 8 != 0 || tag_length_bits > kMaxGcmTagLength ||
66         tag_length_bits < kMinGcmTagLength) {
67         return KM_ERROR_UNSUPPORTED_MAC_LENGTH;
68     }
69 
70     if (tag_length_bits < min_tag_length_bits) {
71         return KM_ERROR_INVALID_MAC_LENGTH;
72     }
73 
74     *tag_length = tag_length_bits / 8;
75     return KM_ERROR_OK;
76 }
77 
CreateOperation(const Key & key,const AuthorizationSet & begin_params,keymaster_error_t * error)78 Operation* AesOperationFactory::CreateOperation(const Key& key,
79                                                 const AuthorizationSet& begin_params,
80                                                 keymaster_error_t* error) {
81     *error = KM_ERROR_OK;
82     const SymmetricKey* symmetric_key = static_cast<const SymmetricKey*>(&key);
83 
84     switch (symmetric_key->key_data_size()) {
85     case 16:
86     case 24:
87     case 32:
88         break;
89     default:
90         *error = KM_ERROR_UNSUPPORTED_KEY_SIZE;
91         return nullptr;
92     }
93 
94     keymaster_block_mode_t block_mode;
95     if (!begin_params.GetTagValue(TAG_BLOCK_MODE, &block_mode)) {
96         LOG_E("%d block modes specified in begin params", begin_params.GetTagCount(TAG_BLOCK_MODE));
97         *error = KM_ERROR_UNSUPPORTED_BLOCK_MODE;
98         return nullptr;
99     } else if (!supported(block_mode)) {
100         LOG_E("Block mode %d not supported", block_mode);
101         *error = KM_ERROR_UNSUPPORTED_BLOCK_MODE;
102         return nullptr;
103     } else if (!key.authorizations().Contains(TAG_BLOCK_MODE, block_mode)) {
104         LOG_E("Block mode %d was specified, but not authorized by key", block_mode);
105         *error = KM_ERROR_INCOMPATIBLE_BLOCK_MODE;
106         return nullptr;
107     }
108 
109     size_t tag_length = 0;
110     if (block_mode == KM_MODE_GCM) {
111         *error = GetAndValidateGcmTagLength(begin_params, key.authorizations(), &tag_length);
112         if (*error != KM_ERROR_OK) {
113             return nullptr;
114         }
115     }
116 
117     keymaster_padding_t padding;
118     if (!GetAndValidatePadding(begin_params, key, &padding, error)) {
119         return nullptr;
120     }
121     if (!allows_padding(block_mode) && padding != KM_PAD_NONE) {
122         LOG_E("Mode does not support padding", 0);
123         *error = KM_ERROR_INCOMPATIBLE_PADDING_MODE;
124         return nullptr;
125     }
126 
127     bool caller_nonce = key.authorizations().GetTagValue(TAG_CALLER_NONCE);
128 
129     Operation* op = nullptr;
130     switch (purpose()) {
131     case KM_PURPOSE_ENCRYPT:
132         op = new (std::nothrow)
133             AesEvpEncryptOperation(block_mode, padding, caller_nonce, tag_length,
134                                    symmetric_key->key_data(), symmetric_key->key_data_size());
135         break;
136     case KM_PURPOSE_DECRYPT:
137         op = new (std::nothrow)
138             AesEvpDecryptOperation(block_mode, padding, tag_length, symmetric_key->key_data(),
139                                    symmetric_key->key_data_size());
140         break;
141     default:
142         *error = KM_ERROR_UNSUPPORTED_PURPOSE;
143         return nullptr;
144     }
145 
146     if (!op)
147         *error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
148     return op;
149 }
150 
151 static const keymaster_block_mode_t supported_block_modes[] = {KM_MODE_ECB, KM_MODE_CBC,
152                                                                KM_MODE_CTR, KM_MODE_GCM};
153 
154 const keymaster_block_mode_t*
SupportedBlockModes(size_t * block_mode_count) const155 AesOperationFactory::SupportedBlockModes(size_t* block_mode_count) const {
156     *block_mode_count = array_length(supported_block_modes);
157     return supported_block_modes;
158 }
159 
160 static const keymaster_padding_t supported_padding_modes[] = {KM_PAD_NONE, KM_PAD_PKCS7};
161 const keymaster_padding_t*
SupportedPaddingModes(size_t * padding_mode_count) const162 AesOperationFactory::SupportedPaddingModes(size_t* padding_mode_count) const {
163     *padding_mode_count = array_length(supported_padding_modes);
164     return supported_padding_modes;
165 }
166 
AesEvpOperation(keymaster_purpose_t purpose,keymaster_block_mode_t block_mode,keymaster_padding_t padding,bool caller_iv,size_t tag_length,const uint8_t * key,size_t key_size)167 AesEvpOperation::AesEvpOperation(keymaster_purpose_t purpose, keymaster_block_mode_t block_mode,
168                                  keymaster_padding_t padding, bool caller_iv, size_t tag_length,
169                                  const uint8_t* key, size_t key_size)
170     : Operation(purpose), block_mode_(block_mode), caller_iv_(caller_iv), tag_length_(tag_length),
171       data_started_(false), key_size_(key_size), padding_(padding) {
172     memcpy(key_, key, key_size_);
173     EVP_CIPHER_CTX_init(&ctx_);
174 }
175 
~AesEvpOperation()176 AesEvpOperation::~AesEvpOperation() {
177     EVP_CIPHER_CTX_cleanup(&ctx_);
178     memset_s(aad_block_buf_.get(), AES_BLOCK_SIZE, 0);
179 }
180 
Begin(const AuthorizationSet &,AuthorizationSet *)181 keymaster_error_t AesEvpOperation::Begin(const AuthorizationSet& /* input_params */,
182                                          AuthorizationSet* /* output_params */) {
183     if (block_mode_ == KM_MODE_GCM) {
184         aad_block_buf_length_ = 0;
185         aad_block_buf_.reset(new (std::nothrow) uint8_t[AES_BLOCK_SIZE]);
186         if (!aad_block_buf_.get())
187             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
188     }
189 
190     return InitializeCipher();
191 }
192 
Update(const AuthorizationSet & additional_params,const Buffer & input,AuthorizationSet *,Buffer * output,size_t * input_consumed)193 keymaster_error_t AesEvpOperation::Update(const AuthorizationSet& additional_params,
194                                           const Buffer& input,
195                                           AuthorizationSet* /* output_params */, Buffer* output,
196                                           size_t* input_consumed) {
197     keymaster_error_t error;
198     if (block_mode_ == KM_MODE_GCM)
199         if (!HandleAad(additional_params, input, &error))
200             return error;
201 
202     if (!InternalUpdate(input.peek_read(), input.available_read(), output, &error))
203         return error;
204     *input_consumed = input.available_read();
205 
206     return KM_ERROR_OK;
207 }
208 
is_bad_decrypt(unsigned long error)209 inline bool is_bad_decrypt(unsigned long error) {
210     return (ERR_GET_LIB(error) == ERR_LIB_CIPHER &&  //
211             ERR_GET_REASON(error) == CIPHER_R_BAD_DECRYPT);
212 }
213 
Finish(const AuthorizationSet & additional_params,const Buffer & input,const Buffer &,AuthorizationSet * output_params,Buffer * output)214 keymaster_error_t AesEvpOperation::Finish(const AuthorizationSet& additional_params,
215                                           const Buffer& input, const Buffer& /* signature */,
216                                           AuthorizationSet* output_params, Buffer* output) {
217     keymaster_error_t error;
218     if (!UpdateForFinish(additional_params, input, output_params, output, &error))
219         return error;
220 
221     if (!output->reserve(AES_BLOCK_SIZE))
222         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
223 
224     if (block_mode_ == KM_MODE_GCM && aad_block_buf_length_ > 0 && !ProcessBufferedAadBlock(&error))
225         return error;
226 
227     int output_written = -1;
228     if (!EVP_CipherFinal_ex(&ctx_, output->peek_write(), &output_written)) {
229         if (tag_length_ > 0)
230             return KM_ERROR_VERIFICATION_FAILED;
231         LOG_E("Error encrypting final block: %s", ERR_error_string(ERR_peek_last_error(), NULL));
232         return TranslateLastOpenSslError();
233     }
234 
235     assert(output_written <= AES_BLOCK_SIZE);
236     if (!output->advance_write(output_written))
237         return KM_ERROR_UNKNOWN_ERROR;
238     return KM_ERROR_OK;
239 }
240 
need_iv() const241 bool AesEvpOperation::need_iv() const {
242     switch (block_mode_) {
243     case KM_MODE_CBC:
244     case KM_MODE_CTR:
245     case KM_MODE_GCM:
246         return true;
247     case KM_MODE_ECB:
248         return false;
249     default:
250         // Shouldn't get here.
251         assert(false);
252         return false;
253     }
254 }
255 
InitializeCipher()256 keymaster_error_t AesEvpOperation::InitializeCipher() {
257     const EVP_CIPHER* cipher;
258     switch (block_mode_) {
259     case KM_MODE_ECB:
260         switch (key_size_) {
261         case 16:
262             cipher = EVP_aes_128_ecb();
263             break;
264         case 24:
265             cipher = EVP_aes_192_ecb();
266             break;
267         case 32:
268             cipher = EVP_aes_256_ecb();
269             break;
270         default:
271             return KM_ERROR_UNSUPPORTED_KEY_SIZE;
272         }
273         break;
274     case KM_MODE_CBC:
275         switch (key_size_) {
276         case 16:
277             cipher = EVP_aes_128_cbc();
278             break;
279         case 24:
280             cipher = EVP_aes_192_cbc();
281             break;
282         case 32:
283             cipher = EVP_aes_256_cbc();
284             break;
285         default:
286             return KM_ERROR_UNSUPPORTED_KEY_SIZE;
287         }
288         break;
289     case KM_MODE_CTR:
290         switch (key_size_) {
291         case 16:
292             cipher = EVP_aes_128_ctr();
293             break;
294         case 24:
295             cipher = EVP_aes_192_ctr();
296             break;
297         case 32:
298             cipher = EVP_aes_256_ctr();
299             break;
300         default:
301             return KM_ERROR_UNSUPPORTED_KEY_SIZE;
302         }
303         break;
304     case KM_MODE_GCM:
305         switch (key_size_) {
306         case 16:
307             cipher = EVP_aes_128_gcm();
308             break;
309         case 24:
310             cipher = EVP_aes_192_gcm();
311             break;
312         case 32:
313             cipher = EVP_aes_256_gcm();
314             break;
315         default:
316             return KM_ERROR_UNSUPPORTED_KEY_SIZE;
317         }
318         break;
319     default:
320         return KM_ERROR_UNSUPPORTED_BLOCK_MODE;
321     }
322 
323     if (!EVP_CipherInit_ex(&ctx_, cipher, NULL /* engine */, key_, iv_.get(), evp_encrypt_mode()))
324         return TranslateLastOpenSslError();
325 
326     switch (padding_) {
327     case KM_PAD_NONE:
328         EVP_CIPHER_CTX_set_padding(&ctx_, 0 /* disable padding */);
329         break;
330     case KM_PAD_PKCS7:
331         // This is the default for OpenSSL EVP cipher operations.
332         break;
333     default:
334         return KM_ERROR_UNSUPPORTED_PADDING_MODE;
335     }
336 
337     if (block_mode_ == KM_MODE_GCM) {
338         aad_block_buf_length_ = 0;
339         aad_block_buf_.reset(new (std::nothrow) uint8_t[AES_BLOCK_SIZE]);
340         if (!aad_block_buf_.get())
341             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
342     }
343 
344     return KM_ERROR_OK;
345 }
346 
GetIv(const AuthorizationSet & input_params)347 keymaster_error_t AesEvpOperation::GetIv(const AuthorizationSet& input_params) {
348     keymaster_blob_t iv_blob;
349     if (!input_params.GetTagValue(TAG_NONCE, &iv_blob)) {
350         LOG_E("No IV provided", 0);
351         return KM_ERROR_INVALID_ARGUMENT;
352     }
353     if (block_mode_ != KM_MODE_GCM && iv_blob.data_length != AES_BLOCK_SIZE) {
354         LOG_E("Expected %d-byte IV for AES operation, but got %d bytes", AES_BLOCK_SIZE,
355               iv_blob.data_length);
356         return KM_ERROR_INVALID_NONCE;
357     }
358     if (block_mode_ == KM_MODE_GCM && iv_blob.data_length != GCM_NONCE_SIZE) {
359         LOG_E("Expected %d-byte nonce for AES-GCM operation, but got %d bytes", GCM_NONCE_SIZE,
360               iv_blob.data_length);
361         return KM_ERROR_INVALID_NONCE;
362     }
363     iv_.reset(dup_array(iv_blob.data, iv_blob.data_length));
364     if (!iv_.get())
365         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
366     iv_length_ = iv_blob.data_length;
367     return KM_ERROR_OK;
368 }
369 
370 /*
371  * Process Incoming Associated Authentication Data.
372  *
373  * This method is more complex than might be expected, because the underlying library silently does
374  * the wrong thing when given partial AAD blocks, so we have to take care to process AAD in
375  * AES_BLOCK_SIZE increments, buffering (in aad_block_buf_) when given smaller amounts of data.
376  */
HandleAad(const AuthorizationSet & input_params,const Buffer & input,keymaster_error_t * error)377 bool AesEvpOperation::HandleAad(const AuthorizationSet& input_params, const Buffer& input,
378                                 keymaster_error_t* error) {
379     assert(tag_length_ > 0);
380     assert(error);
381 
382     keymaster_blob_t aad;
383     if (input_params.GetTagValue(TAG_ASSOCIATED_DATA, &aad)) {
384         if (data_started_) {
385             *error = KM_ERROR_INVALID_TAG;
386             return false;
387         }
388 
389         if (aad_block_buf_length_ > 0) {
390             FillBufferedAadBlock(&aad);
391             if (aad_block_buf_length_ == AES_BLOCK_SIZE && !ProcessBufferedAadBlock(error))
392                 return false;
393         }
394 
395         size_t blocks_to_process = aad.data_length / AES_BLOCK_SIZE;
396         if (blocks_to_process && !ProcessAadBlocks(aad.data, blocks_to_process, error))
397             return false;
398         aad.data += blocks_to_process * AES_BLOCK_SIZE;
399         aad.data_length -= blocks_to_process * AES_BLOCK_SIZE;
400 
401         FillBufferedAadBlock(&aad);
402         assert(aad.data_length == 0);
403     }
404 
405     if (input.available_read()) {
406         data_started_ = true;
407         // Data has begun, no more AAD is allowed.  Process any buffered AAD.
408         if (aad_block_buf_length_ > 0 && !ProcessBufferedAadBlock(error))
409             return false;
410     }
411 
412     return true;
413 }
414 
ProcessBufferedAadBlock(keymaster_error_t * error)415 bool AesEvpOperation::ProcessBufferedAadBlock(keymaster_error_t* error) {
416     int output_written;
417     if (EVP_CipherUpdate(&ctx_, nullptr /* out */, &output_written, aad_block_buf_.get(),
418                          aad_block_buf_length_)) {
419         aad_block_buf_length_ = 0;
420         return true;
421     }
422     *error = TranslateLastOpenSslError();
423     return false;
424 }
425 
ProcessAadBlocks(const uint8_t * data,size_t blocks,keymaster_error_t * error)426 bool AesEvpOperation::ProcessAadBlocks(const uint8_t* data, size_t blocks,
427                                        keymaster_error_t* error) {
428     int output_written;
429     if (EVP_CipherUpdate(&ctx_, nullptr /* out */, &output_written, data, blocks * AES_BLOCK_SIZE))
430         return true;
431     *error = TranslateLastOpenSslError();
432     return false;
433 }
434 
min(size_t a,size_t b)435 inline size_t min(size_t a, size_t b) {
436     return (a < b) ? a : b;
437 }
438 
FillBufferedAadBlock(keymaster_blob_t * aad)439 void AesEvpOperation::FillBufferedAadBlock(keymaster_blob_t* aad) {
440     size_t to_buffer = min(AES_BLOCK_SIZE - aad_block_buf_length_, aad->data_length);
441     memcpy(aad_block_buf_.get() + aad_block_buf_length_, aad->data, to_buffer);
442     aad->data += to_buffer;
443     aad->data_length -= to_buffer;
444     aad_block_buf_length_ += to_buffer;
445 }
446 
InternalUpdate(const uint8_t * input,size_t input_length,Buffer * output,keymaster_error_t * error)447 bool AesEvpOperation::InternalUpdate(const uint8_t* input, size_t input_length, Buffer* output,
448                                      keymaster_error_t* error) {
449     assert(output);
450     assert(error);
451 
452     if (!input_length)
453         return true;
454 
455     if (!output->reserve(input_length + AES_BLOCK_SIZE)) {
456         *error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
457         return false;
458     }
459 
460     int output_written = -1;
461     if (!EVP_CipherUpdate(&ctx_, output->peek_write(), &output_written, input, input_length)) {
462         *error = TranslateLastOpenSslError();
463         return false;
464     }
465     return output->advance_write(output_written);
466 }
467 
UpdateForFinish(const AuthorizationSet & additional_params,const Buffer & input,AuthorizationSet * output_params,Buffer * output,keymaster_error_t * error)468 bool AesEvpOperation::UpdateForFinish(const AuthorizationSet& additional_params,
469                                       const Buffer& input, AuthorizationSet* output_params,
470                                       Buffer* output, keymaster_error_t* error) {
471     if (input.available_read() || !additional_params.empty()) {
472         size_t input_consumed;
473         *error = Update(additional_params, input, output_params, output, &input_consumed);
474         if (*error != KM_ERROR_OK)
475             return false;
476         if (input_consumed != input.available_read()) {
477             *error = KM_ERROR_INVALID_INPUT_LENGTH;
478             return false;
479         }
480     }
481 
482     return true;
483 }
484 
Begin(const AuthorizationSet & input_params,AuthorizationSet * output_params)485 keymaster_error_t AesEvpEncryptOperation::Begin(const AuthorizationSet& input_params,
486                                                 AuthorizationSet* output_params) {
487     if (!output_params)
488         return KM_ERROR_OUTPUT_PARAMETER_NULL;
489 
490     if (need_iv()) {
491         keymaster_error_t error = KM_ERROR_OK;
492         if (input_params.find(TAG_NONCE) == -1)
493             error = GenerateIv();
494         else if (caller_iv_)
495             error = GetIv(input_params);
496         else
497             error = KM_ERROR_CALLER_NONCE_PROHIBITED;
498 
499         if (error == KM_ERROR_OK)
500             output_params->push_back(TAG_NONCE, iv_.get(), iv_length_);
501         else
502             return error;
503     }
504 
505     return AesEvpOperation::Begin(input_params, output_params);
506 }
507 
Finish(const AuthorizationSet & additional_params,const Buffer & input,const Buffer & signature,AuthorizationSet * output_params,Buffer * output)508 keymaster_error_t AesEvpEncryptOperation::Finish(const AuthorizationSet& additional_params,
509                                                  const Buffer& input, const Buffer& signature,
510                                                  AuthorizationSet* output_params, Buffer* output) {
511     if (!output->reserve(input.available_read() + AES_BLOCK_SIZE + tag_length_))
512         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
513 
514     keymaster_error_t error =
515         AesEvpOperation::Finish(additional_params, input, signature, output_params, output);
516     if (error != KM_ERROR_OK)
517         return error;
518 
519     if (tag_length_ > 0) {
520         if (!output->reserve(tag_length_))
521             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
522 
523         if (!EVP_CIPHER_CTX_ctrl(&ctx_, EVP_CTRL_GCM_GET_TAG, tag_length_, output->peek_write()))
524             return TranslateLastOpenSslError();
525         if (!output->advance_write(tag_length_))
526             return KM_ERROR_UNKNOWN_ERROR;
527     }
528 
529     return KM_ERROR_OK;
530 }
531 
GenerateIv()532 keymaster_error_t AesEvpEncryptOperation::GenerateIv() {
533     iv_length_ = (block_mode_ == KM_MODE_GCM) ? GCM_NONCE_SIZE : AES_BLOCK_SIZE;
534     iv_.reset(new (std::nothrow) uint8_t[iv_length_]);
535     if (!iv_.get())
536         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
537     if (RAND_bytes(iv_.get(), iv_length_) != 1)
538         return TranslateLastOpenSslError();
539     return KM_ERROR_OK;
540 }
541 
Begin(const AuthorizationSet & input_params,AuthorizationSet * output_params)542 keymaster_error_t AesEvpDecryptOperation::Begin(const AuthorizationSet& input_params,
543                                                 AuthorizationSet* output_params) {
544     if (need_iv()) {
545         keymaster_error_t error = GetIv(input_params);
546         if (error != KM_ERROR_OK)
547             return error;
548     }
549 
550     if (tag_length_ > 0) {
551         tag_buf_length_ = 0;
552         tag_buf_.reset(new (std::nothrow) uint8_t[tag_length_]);
553         if (!tag_buf_.get())
554             return KM_ERROR_MEMORY_ALLOCATION_FAILED;
555     }
556 
557     return AesEvpOperation::Begin(input_params, output_params);
558 }
559 
Update(const AuthorizationSet & additional_params,const Buffer & input,AuthorizationSet *,Buffer * output,size_t * input_consumed)560 keymaster_error_t AesEvpDecryptOperation::Update(const AuthorizationSet& additional_params,
561                                                  const Buffer& input,
562                                                  AuthorizationSet* /* output_params */,
563                                                  Buffer* output, size_t* input_consumed) {
564     if (!output || !input_consumed)
565         return KM_ERROR_OUTPUT_PARAMETER_NULL;
566 
567     // Barring error, we'll consume it all.
568     *input_consumed = input.available_read();
569 
570     keymaster_error_t error;
571     if (block_mode_ == KM_MODE_GCM) {
572         if (!HandleAad(additional_params, input, &error))
573             return error;
574         return ProcessAllButTagLengthBytes(input, output);
575     }
576 
577     if (!InternalUpdate(input.peek_read(), input.available_read(), output, &error))
578         return error;
579     return KM_ERROR_OK;
580 }
581 
ProcessAllButTagLengthBytes(const Buffer & input,Buffer * output)582 keymaster_error_t AesEvpDecryptOperation::ProcessAllButTagLengthBytes(const Buffer& input,
583                                                                       Buffer* output) {
584     if (input.available_read() <= tag_buf_unused()) {
585         BufferCandidateTagData(input.peek_read(), input.available_read());
586         return KM_ERROR_OK;
587     }
588 
589     const size_t data_available = tag_buf_length_ + input.available_read();
590 
591     const size_t to_process = data_available - tag_length_;
592     const size_t to_process_from_tag_buf = min(to_process, tag_buf_length_);
593     const size_t to_process_from_input = to_process - to_process_from_tag_buf;
594 
595     if (!output->reserve(to_process + AES_BLOCK_SIZE))
596         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
597 
598     keymaster_error_t error;
599     if (!ProcessTagBufContentsAsData(to_process_from_tag_buf, output, &error))
600         return error;
601 
602     if (!InternalUpdate(input.peek_read(), to_process_from_input, output, &error))
603         return error;
604 
605     BufferCandidateTagData(input.peek_read() + to_process_from_input,
606                            input.available_read() - to_process_from_input);
607     assert(tag_buf_unused() == 0);
608 
609     return KM_ERROR_OK;
610 }
611 
ProcessTagBufContentsAsData(size_t to_process,Buffer * output,keymaster_error_t * error)612 bool AesEvpDecryptOperation::ProcessTagBufContentsAsData(size_t to_process, Buffer* output,
613                                                          keymaster_error_t* error) {
614     assert(to_process <= tag_buf_length_);
615     if (!InternalUpdate(tag_buf_.get(), to_process, output, error))
616         return false;
617     if (to_process < tag_buf_length_)
618         memmove(tag_buf_.get(), tag_buf_.get() + to_process, tag_buf_length_ - to_process);
619     tag_buf_length_ -= to_process;
620     return true;
621 }
622 
BufferCandidateTagData(const uint8_t * data,size_t data_length)623 void AesEvpDecryptOperation::BufferCandidateTagData(const uint8_t* data, size_t data_length) {
624     assert(data_length <= tag_length_ - tag_buf_length_);
625     memcpy(tag_buf_.get() + tag_buf_length_, data, data_length);
626     tag_buf_length_ += data_length;
627 }
628 
Finish(const AuthorizationSet & additional_params,const Buffer & input,const Buffer & signature,AuthorizationSet * output_params,Buffer * output)629 keymaster_error_t AesEvpDecryptOperation::Finish(const AuthorizationSet& additional_params,
630                                                  const Buffer& input, const Buffer& signature,
631                                                  AuthorizationSet* output_params, Buffer* output) {
632     keymaster_error_t error;
633     if (!UpdateForFinish(additional_params, input, output_params, output, &error))
634         return error;
635 
636     if (tag_buf_length_ < tag_length_)
637         return KM_ERROR_INVALID_INPUT_LENGTH;
638     else if (tag_length_ > 0 &&
639              !EVP_CIPHER_CTX_ctrl(&ctx_, EVP_CTRL_GCM_SET_TAG, tag_length_, tag_buf_.get()))
640         return TranslateLastOpenSslError();
641 
642     AuthorizationSet empty_params;
643     Buffer empty_input;
644     return AesEvpOperation::Finish(empty_params, empty_input, signature, output_params, output);
645 }
646 
Abort()647 keymaster_error_t AesEvpOperation::Abort() {
648     return KM_ERROR_OK;
649 }
650 
651 }  // namespace keymaster
652