4426a8162981a948b896fc6e2a957f1e8a6663f6
[openssl.git] / crypto / evp / evp_enc.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <assert.h>
12 #include "internal/cryptlib.h"
13 #include <openssl/evp.h>
14 #include <openssl/err.h>
15 #include <openssl/rand.h>
16 #include <openssl/rand_drbg.h>
17 #include <openssl/engine.h>
18 #include <openssl/params.h>
19 #include <openssl/core_names.h>
20 #include "internal/evp_int.h"
21 #include "internal/provider.h"
22 #include "evp_locl.h"
23
24 int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX *ctx)
25 {
26     if (ctx == NULL)
27         return 1;
28
29     if (ctx->cipher == NULL || ctx->cipher->prov == NULL)
30         goto legacy;
31
32     if (ctx->provctx != NULL) {
33         if (ctx->cipher->freectx != NULL)
34             ctx->cipher->freectx(ctx->provctx);
35         ctx->provctx = NULL;
36     }
37     if (ctx->fetched_cipher != NULL)
38         EVP_CIPHER_meth_free(ctx->fetched_cipher);
39     memset(ctx, 0, sizeof(*ctx));
40
41     return 1;
42
43     /* TODO(3.0): Remove legacy code below */
44  legacy:
45
46     if (ctx->cipher != NULL) {
47         if (ctx->cipher->cleanup && !ctx->cipher->cleanup(ctx))
48             return 0;
49         /* Cleanse cipher context data */
50         if (ctx->cipher_data && ctx->cipher->ctx_size)
51             OPENSSL_cleanse(ctx->cipher_data, ctx->cipher->ctx_size);
52     }
53     OPENSSL_free(ctx->cipher_data);
54 #ifndef OPENSSL_NO_ENGINE
55     ENGINE_finish(ctx->engine);
56 #endif
57     memset(ctx, 0, sizeof(*ctx));
58     return 1;
59 }
60
61 EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void)
62 {
63     return OPENSSL_zalloc(sizeof(EVP_CIPHER_CTX));
64 }
65
66 void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx)
67 {
68     EVP_CIPHER_CTX_reset(ctx);
69     OPENSSL_free(ctx);
70 }
71
72 int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
73                    const unsigned char *key, const unsigned char *iv, int enc)
74 {
75     if (cipher != NULL)
76         EVP_CIPHER_CTX_reset(ctx);
77     return EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, enc);
78 }
79
80 int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
81                       ENGINE *impl, const unsigned char *key,
82                       const unsigned char *iv, int enc)
83 {
84     EVP_CIPHER *provciph = NULL;
85     ENGINE *tmpimpl = NULL;
86     const EVP_CIPHER *tmpcipher;
87
88     /*
89      * enc == 1 means we are encrypting.
90      * enc == 0 means we are decrypting.
91      * enc == -1 means, use the previously initialised value for encrypt/decrypt
92      */
93     if (enc == -1) {
94         enc = ctx->encrypt;
95     } else {
96         if (enc)
97             enc = 1;
98         ctx->encrypt = enc;
99     }
100
101     if (cipher == NULL && ctx->cipher == NULL) {
102         EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET);
103         return 0;
104     }
105
106     /* TODO(3.0): Legacy work around code below. Remove this */
107
108 #ifndef OPENSSL_NO_ENGINE
109     /*
110      * Whether it's nice or not, "Inits" can be used on "Final"'d contexts so
111      * this context may already have an ENGINE! Try to avoid releasing the
112      * previous handle, re-querying for an ENGINE, and having a
113      * reinitialisation, when it may all be unnecessary.
114      */
115     if (ctx->engine && ctx->cipher
116         && (cipher == NULL || cipher->nid == ctx->cipher->nid))
117         goto skip_to_init;
118
119     if (cipher != NULL && impl == NULL) {
120          /* Ask if an ENGINE is reserved for this job */
121         tmpimpl = ENGINE_get_cipher_engine(cipher->nid);
122     }
123 #endif
124
125     /*
126      * If there are engines involved then we should use legacy handling for now.
127      */
128     if (ctx->engine != NULL
129             || impl != NULL
130             || tmpimpl != NULL) {
131         if (ctx->cipher == ctx->fetched_cipher)
132             ctx->cipher = NULL;
133         EVP_CIPHER_meth_free(ctx->fetched_cipher);
134         ctx->fetched_cipher = NULL;
135         goto legacy;
136     }
137
138     tmpcipher = (cipher == NULL) ? ctx->cipher : cipher;
139
140     if (tmpcipher->prov == NULL) {
141         switch(tmpcipher->nid) {
142         case NID_aes_256_ecb:
143         case NID_aes_192_ecb:
144         case NID_aes_128_ecb:
145         case NID_aes_256_cbc:
146         case NID_aes_192_cbc:
147         case NID_aes_128_cbc:
148         case NID_aes_256_ofb128:
149         case NID_aes_192_ofb128:
150         case NID_aes_128_ofb128:
151         case NID_aes_256_cfb128:
152         case NID_aes_192_cfb128:
153         case NID_aes_128_cfb128:
154         case NID_aes_256_cfb1:
155         case NID_aes_192_cfb1:
156         case NID_aes_128_cfb1:
157         case NID_aes_256_cfb8:
158         case NID_aes_192_cfb8:
159         case NID_aes_128_cfb8:
160         case NID_aes_256_ctr:
161         case NID_aes_192_ctr:
162         case NID_aes_128_ctr:
163             break;
164         default:
165             goto legacy;
166         }
167     }
168
169     /*
170      * Ensure a context left lying around from last time is cleared
171      * (legacy code)
172      */
173     if (cipher != NULL && ctx->cipher != NULL) {
174         OPENSSL_clear_free(ctx->cipher_data, ctx->cipher->ctx_size);
175         ctx->cipher_data = NULL;
176     }
177
178
179     /* TODO(3.0): Start of non-legacy code below */
180
181     /* Ensure a context left lying around from last time is cleared */
182     if (cipher != NULL && ctx->cipher != NULL) {
183         unsigned long flags = ctx->flags;
184
185         EVP_CIPHER_CTX_reset(ctx);
186         /* Restore encrypt and flags */
187         ctx->encrypt = enc;
188         ctx->flags = flags;
189     }
190
191     if (cipher != NULL)
192         ctx->cipher = cipher;
193     else
194         cipher = ctx->cipher;
195
196     if (cipher->prov == NULL) {
197         provciph = EVP_CIPHER_fetch(NULL, OBJ_nid2sn(cipher->nid), "");
198         if (provciph == NULL) {
199             EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
200             return 0;
201         }
202         cipher = provciph;
203         EVP_CIPHER_meth_free(ctx->fetched_cipher);
204         ctx->fetched_cipher = provciph;
205     }
206
207     ctx->cipher = cipher;
208     if (ctx->provctx == NULL) {
209         ctx->provctx = ctx->cipher->newctx();
210         if (ctx->provctx == NULL) {
211             EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
212             return 0;
213         }
214     }
215
216     if ((ctx->flags & EVP_CIPH_NO_PADDING) != 0) {
217         /*
218          * If this ctx was already set up for no padding then we need to tell
219          * the new cipher about it.
220          */
221         if (!EVP_CIPHER_CTX_set_padding(ctx, 0))
222             return 0;
223     }
224
225     switch (EVP_CIPHER_mode(ctx->cipher)) {
226     case EVP_CIPH_CFB_MODE:
227     case EVP_CIPH_OFB_MODE:
228     case EVP_CIPH_CBC_MODE:
229         /* For these modes we remember the original IV for later use */
230         if (!ossl_assert(EVP_CIPHER_CTX_iv_length(ctx) <= (int)sizeof(ctx->oiv))) {
231             EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
232             return 0;
233         }
234         if (iv != NULL)
235             memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
236     }
237
238     if (enc) {
239         if (ctx->cipher->einit == NULL) {
240             EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
241             return 0;
242         }
243
244         return ctx->cipher->einit(ctx->provctx,
245                                   key,
246                                   EVP_CIPHER_CTX_key_length(ctx),
247                                   iv,
248                                   EVP_CIPHER_CTX_iv_length(ctx));
249     }
250
251     if (ctx->cipher->dinit == NULL) {
252         EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
253         return 0;
254     }
255
256     return ctx->cipher->dinit(ctx->provctx,
257                               key,
258                               EVP_CIPHER_CTX_key_length(ctx),
259                               iv,
260                               EVP_CIPHER_CTX_iv_length(ctx));
261
262     /* TODO(3.0): Remove legacy code below */
263  legacy:
264
265     if (cipher != NULL) {
266         /*
267          * Ensure a context left lying around from last time is cleared (we
268          * previously attempted to avoid this if the same ENGINE and
269          * EVP_CIPHER could be used).
270          */
271         if (ctx->cipher) {
272             unsigned long flags = ctx->flags;
273             EVP_CIPHER_CTX_reset(ctx);
274             /* Restore encrypt and flags */
275             ctx->encrypt = enc;
276             ctx->flags = flags;
277         }
278 #ifndef OPENSSL_NO_ENGINE
279         if (impl != NULL) {
280             if (!ENGINE_init(impl)) {
281                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
282                 return 0;
283             }
284         } else {
285             impl = tmpimpl;
286         }
287         if (impl != NULL) {
288             /* There's an ENGINE for this job ... (apparently) */
289             const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid);
290
291             if (c == NULL) {
292                 /*
293                  * One positive side-effect of US's export control history,
294                  * is that we should at least be able to avoid using US
295                  * misspellings of "initialisation"?
296                  */
297                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
298                 return 0;
299             }
300             /* We'll use the ENGINE's private cipher definition */
301             cipher = c;
302             /*
303              * Store the ENGINE functional reference so we know 'cipher' came
304              * from an ENGINE and we need to release it when done.
305              */
306             ctx->engine = impl;
307         } else {
308             ctx->engine = NULL;
309         }
310 #endif
311
312         ctx->cipher = cipher;
313         if (ctx->cipher->ctx_size) {
314             ctx->cipher_data = OPENSSL_zalloc(ctx->cipher->ctx_size);
315             if (ctx->cipher_data == NULL) {
316                 ctx->cipher = NULL;
317                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE);
318                 return 0;
319             }
320         } else {
321             ctx->cipher_data = NULL;
322         }
323         ctx->key_len = cipher->key_len;
324         /* Preserve wrap enable flag, zero everything else */
325         ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW;
326         if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) {
327             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) {
328                 ctx->cipher = NULL;
329                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
330                 return 0;
331             }
332         }
333     }
334 #ifndef OPENSSL_NO_ENGINE
335  skip_to_init:
336 #endif
337     /* we assume block size is a power of 2 in *cryptUpdate */
338     OPENSSL_assert(ctx->cipher->block_size == 1
339                    || ctx->cipher->block_size == 8
340                    || ctx->cipher->block_size == 16);
341
342     if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW)
343         && EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_WRAP_MODE) {
344         EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_WRAP_MODE_NOT_ALLOWED);
345         return 0;
346     }
347
348     if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_CUSTOM_IV)) {
349         switch (EVP_CIPHER_CTX_mode(ctx)) {
350
351         case EVP_CIPH_STREAM_CIPHER:
352         case EVP_CIPH_ECB_MODE:
353             break;
354
355         case EVP_CIPH_CFB_MODE:
356         case EVP_CIPH_OFB_MODE:
357
358             ctx->num = 0;
359             /* fall-through */
360
361         case EVP_CIPH_CBC_MODE:
362
363             OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <=
364                            (int)sizeof(ctx->iv));
365             if (iv)
366                 memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
367             memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
368             break;
369
370         case EVP_CIPH_CTR_MODE:
371             ctx->num = 0;
372             /* Don't reuse IV for CTR mode */
373             if (iv)
374                 memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
375             break;
376
377         default:
378             return 0;
379         }
380     }
381
382     if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
383         if (!ctx->cipher->init(ctx, key, iv, enc))
384             return 0;
385     }
386     ctx->buf_len = 0;
387     ctx->final_used = 0;
388     ctx->block_mask = ctx->cipher->block_size - 1;
389     return 1;
390 }
391
392 int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
393                      const unsigned char *in, int inl)
394 {
395     if (ctx->encrypt)
396         return EVP_EncryptUpdate(ctx, out, outl, in, inl);
397     else
398         return EVP_DecryptUpdate(ctx, out, outl, in, inl);
399 }
400
401 int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
402 {
403     if (ctx->encrypt)
404         return EVP_EncryptFinal_ex(ctx, out, outl);
405     else
406         return EVP_DecryptFinal_ex(ctx, out, outl);
407 }
408
409 int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
410 {
411     if (ctx->encrypt)
412         return EVP_EncryptFinal(ctx, out, outl);
413     else
414         return EVP_DecryptFinal(ctx, out, outl);
415 }
416
417 int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
418                     const unsigned char *key, const unsigned char *iv)
419 {
420     return EVP_CipherInit(ctx, cipher, key, iv, 1);
421 }
422
423 int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
424                        ENGINE *impl, const unsigned char *key,
425                        const unsigned char *iv)
426 {
427     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
428 }
429
430 int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
431                     const unsigned char *key, const unsigned char *iv)
432 {
433     return EVP_CipherInit(ctx, cipher, key, iv, 0);
434 }
435
436 int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
437                        ENGINE *impl, const unsigned char *key,
438                        const unsigned char *iv)
439 {
440     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
441 }
442
443 /*
444  * According to the letter of standard difference between pointers
445  * is specified to be valid only within same object. This makes
446  * it formally challenging to determine if input and output buffers
447  * are not partially overlapping with standard pointer arithmetic.
448  */
449 #ifdef PTRDIFF_T
450 # undef PTRDIFF_T
451 #endif
452 #if defined(OPENSSL_SYS_VMS) && __INITIAL_POINTER_SIZE==64
453 /*
454  * Then we have VMS that distinguishes itself by adhering to
455  * sizeof(size_t)==4 even in 64-bit builds, which means that
456  * difference between two pointers might be truncated to 32 bits.
457  * In the context one can even wonder how comparison for
458  * equality is implemented. To be on the safe side we adhere to
459  * PTRDIFF_T even for comparison for equality.
460  */
461 # define PTRDIFF_T uint64_t
462 #else
463 # define PTRDIFF_T size_t
464 #endif
465
466 int is_partially_overlapping(const void *ptr1, const void *ptr2, int len)
467 {
468     PTRDIFF_T diff = (PTRDIFF_T)ptr1-(PTRDIFF_T)ptr2;
469     /*
470      * Check for partially overlapping buffers. [Binary logical
471      * operations are used instead of boolean to minimize number
472      * of conditional branches.]
473      */
474     int overlapped = (len > 0) & (diff != 0) & ((diff < (PTRDIFF_T)len) |
475                                                 (diff > (0 - (PTRDIFF_T)len)));
476
477     return overlapped;
478 }
479
480 static int evp_EncryptDecryptUpdate(EVP_CIPHER_CTX *ctx,
481                                     unsigned char *out, int *outl,
482                                     const unsigned char *in, int inl)
483 {
484     int i, j, bl, cmpl = inl;
485
486     if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS))
487         cmpl = (cmpl + 7) / 8;
488
489     bl = ctx->cipher->block_size;
490
491     if (inl <= 0) {
492         *outl = 0;
493         return inl == 0;
494     }
495
496     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
497         /* If block size > 1 then the cipher will have to do this check */
498         if (bl == 1 && is_partially_overlapping(out, in, cmpl)) {
499             EVPerr(EVP_F_EVP_ENCRYPTDECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);
500             return 0;
501         }
502
503         i = ctx->cipher->do_cipher(ctx, out, in, inl);
504         if (i < 0)
505             return 0;
506         else
507             *outl = i;
508         return 1;
509     }
510
511     if (is_partially_overlapping(out + ctx->buf_len, in, cmpl)) {
512         EVPerr(EVP_F_EVP_ENCRYPTDECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);
513         return 0;
514     }
515
516     if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
517         if (ctx->cipher->do_cipher(ctx, out, in, inl)) {
518             *outl = inl;
519             return 1;
520         } else {
521             *outl = 0;
522             return 0;
523         }
524     }
525     i = ctx->buf_len;
526     OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
527     if (i != 0) {
528         if (bl - i > inl) {
529             memcpy(&(ctx->buf[i]), in, inl);
530             ctx->buf_len += inl;
531             *outl = 0;
532             return 1;
533         } else {
534             j = bl - i;
535             memcpy(&(ctx->buf[i]), in, j);
536             inl -= j;
537             in += j;
538             if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl))
539                 return 0;
540             out += bl;
541             *outl = bl;
542         }
543     } else
544         *outl = 0;
545     i = inl & (bl - 1);
546     inl -= i;
547     if (inl > 0) {
548         if (!ctx->cipher->do_cipher(ctx, out, in, inl))
549             return 0;
550         *outl += inl;
551     }
552
553     if (i != 0)
554         memcpy(ctx->buf, &(in[inl]), i);
555     ctx->buf_len = i;
556     return 1;
557 }
558
559
560 int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
561                       const unsigned char *in, int inl)
562 {
563     int ret;
564     size_t soutl;
565     int blocksize;
566
567     /* Prevent accidental use of decryption context when encrypting */
568     if (!ctx->encrypt) {
569         EVPerr(EVP_F_EVP_ENCRYPTUPDATE, EVP_R_INVALID_OPERATION);
570         return 0;
571     }
572
573     if (ctx->cipher == NULL || ctx->cipher->prov == NULL)
574         goto legacy;
575
576     blocksize = EVP_CIPHER_CTX_block_size(ctx);
577
578     if (ctx->cipher->cupdate == NULL  || blocksize < 1) {
579         EVPerr(EVP_F_EVP_ENCRYPTUPDATE, EVP_R_UPDATE_ERROR);
580         return 0;
581     }
582     ret = ctx->cipher->cupdate(ctx->provctx, out, &soutl,
583                                inl + (blocksize == 1 ? 0 : blocksize), in,
584                                (size_t)inl);
585
586     if (soutl > INT_MAX) {
587         EVPerr(EVP_F_EVP_ENCRYPTUPDATE, EVP_R_UPDATE_ERROR);
588         return 0;
589     }
590     *outl = soutl;
591     return ret;
592
593     /* TODO(3.0): Remove legacy code below */
594  legacy:
595
596     return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl);
597 }
598
599 int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
600 {
601     int ret;
602     ret = EVP_EncryptFinal_ex(ctx, out, outl);
603     return ret;
604 }
605
606 int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
607 {
608     int n, ret;
609     unsigned int i, b, bl;
610     size_t soutl;
611     int blocksize;
612
613     /* Prevent accidental use of decryption context when encrypting */
614     if (!ctx->encrypt) {
615         EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX, EVP_R_INVALID_OPERATION);
616         return 0;
617     }
618
619     if (ctx->cipher == NULL || ctx->cipher->prov == NULL)
620         goto legacy;
621
622     blocksize = EVP_CIPHER_CTX_block_size(ctx);
623
624     if (blocksize < 1 || ctx->cipher->cfinal == NULL) {
625         EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX, EVP_R_FINAL_ERROR);
626         return 0;
627     }
628
629     ret = ctx->cipher->cfinal(ctx->provctx, out, &soutl,
630                               blocksize == 1 ? 0 : blocksize);
631
632     if (soutl > INT_MAX) {
633         EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX, EVP_R_FINAL_ERROR);
634         return 0;
635     }
636     *outl = soutl;
637
638     return ret;
639
640     /* TODO(3.0): Remove legacy code below */
641  legacy:
642
643     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
644         ret = ctx->cipher->do_cipher(ctx, out, NULL, 0);
645         if (ret < 0)
646             return 0;
647         else
648             *outl = ret;
649         return 1;
650     }
651
652     b = ctx->cipher->block_size;
653     OPENSSL_assert(b <= sizeof(ctx->buf));
654     if (b == 1) {
655         *outl = 0;
656         return 1;
657     }
658     bl = ctx->buf_len;
659     if (ctx->flags & EVP_CIPH_NO_PADDING) {
660         if (bl) {
661             EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX,
662                    EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
663             return 0;
664         }
665         *outl = 0;
666         return 1;
667     }
668
669     n = b - bl;
670     for (i = bl; i < b; i++)
671         ctx->buf[i] = n;
672     ret = ctx->cipher->do_cipher(ctx, out, ctx->buf, b);
673
674     if (ret)
675         *outl = b;
676
677     return ret;
678 }
679
680 int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
681                       const unsigned char *in, int inl)
682 {
683     int fix_len, cmpl = inl, ret;
684     unsigned int b;
685     size_t soutl;
686     int blocksize;
687
688     /* Prevent accidental use of encryption context when decrypting */
689     if (ctx->encrypt) {
690         EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_INVALID_OPERATION);
691         return 0;
692     }
693
694     if (ctx->cipher == NULL || ctx->cipher->prov == NULL)
695         goto legacy;
696
697     blocksize = EVP_CIPHER_CTX_block_size(ctx);
698
699     if (ctx->cipher->cupdate == NULL || blocksize < 1) {
700         EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_UPDATE_ERROR);
701         return 0;
702     }
703     ret = ctx->cipher->cupdate(ctx->provctx, out, &soutl,
704                                inl + (blocksize == 1 ? 0 : blocksize), in,
705                                (size_t)inl);
706
707     if (ret) {
708         if (soutl > INT_MAX) {
709             EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_UPDATE_ERROR);
710             return 0;
711         }
712         *outl = soutl;
713     }
714
715     return ret;
716
717     /* TODO(3.0): Remove legacy code below */
718  legacy:
719
720     b = ctx->cipher->block_size;
721
722     if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS))
723         cmpl = (cmpl + 7) / 8;
724
725     if (inl <= 0) {
726         *outl = 0;
727         return inl == 0;
728     }
729
730     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
731         if (b == 1 && is_partially_overlapping(out, in, cmpl)) {
732             EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);
733             return 0;
734         }
735
736         fix_len = ctx->cipher->do_cipher(ctx, out, in, inl);
737         if (fix_len < 0) {
738             *outl = 0;
739             return 0;
740         } else
741             *outl = fix_len;
742         return 1;
743     }
744
745     if (ctx->flags & EVP_CIPH_NO_PADDING)
746         return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl);
747
748     OPENSSL_assert(b <= sizeof(ctx->final));
749
750     if (ctx->final_used) {
751         /* see comment about PTRDIFF_T comparison above */
752         if (((PTRDIFF_T)out == (PTRDIFF_T)in)
753             || is_partially_overlapping(out, in, b)) {
754             EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);
755             return 0;
756         }
757         memcpy(out, ctx->final, b);
758         out += b;
759         fix_len = 1;
760     } else
761         fix_len = 0;
762
763     if (!evp_EncryptDecryptUpdate(ctx, out, outl, in, inl))
764         return 0;
765
766     /*
767      * if we have 'decrypted' a multiple of block size, make sure we have a
768      * copy of this last block
769      */
770     if (b > 1 && !ctx->buf_len) {
771         *outl -= b;
772         ctx->final_used = 1;
773         memcpy(ctx->final, &out[*outl], b);
774     } else
775         ctx->final_used = 0;
776
777     if (fix_len)
778         *outl += b;
779
780     return 1;
781 }
782
783 int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
784 {
785     int ret;
786     ret = EVP_DecryptFinal_ex(ctx, out, outl);
787     return ret;
788 }
789
790 int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
791 {
792     int i, n;
793     unsigned int b;
794     size_t soutl;
795     int ret;
796     int blocksize;
797
798     /* Prevent accidental use of encryption context when decrypting */
799     if (ctx->encrypt) {
800         EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_INVALID_OPERATION);
801         return 0;
802     }
803
804     if (ctx->cipher == NULL || ctx->cipher->prov == NULL)
805         goto legacy;
806
807     blocksize = EVP_CIPHER_CTX_block_size(ctx);
808
809     if (blocksize < 1 || ctx->cipher->cfinal == NULL) {
810         EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_FINAL_ERROR);
811         return 0;
812     }
813
814     ret = ctx->cipher->cfinal(ctx->provctx, out, &soutl,
815                               blocksize == 1 ? 0 : blocksize);
816
817     if (ret) {
818         if (soutl > INT_MAX) {
819             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_FINAL_ERROR);
820             return 0;
821         }
822         *outl = soutl;
823     }
824
825     return ret;
826
827     /* TODO(3.0): Remove legacy code below */
828  legacy:
829
830     *outl = 0;
831
832     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
833         i = ctx->cipher->do_cipher(ctx, out, NULL, 0);
834         if (i < 0)
835             return 0;
836         else
837             *outl = i;
838         return 1;
839     }
840
841     b = ctx->cipher->block_size;
842     if (ctx->flags & EVP_CIPH_NO_PADDING) {
843         if (ctx->buf_len) {
844             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX,
845                    EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
846             return 0;
847         }
848         *outl = 0;
849         return 1;
850     }
851     if (b > 1) {
852         if (ctx->buf_len || !ctx->final_used) {
853             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_WRONG_FINAL_BLOCK_LENGTH);
854             return 0;
855         }
856         OPENSSL_assert(b <= sizeof(ctx->final));
857
858         /*
859          * The following assumes that the ciphertext has been authenticated.
860          * Otherwise it provides a padding oracle.
861          */
862         n = ctx->final[b - 1];
863         if (n == 0 || n > (int)b) {
864             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
865             return 0;
866         }
867         for (i = 0; i < n; i++) {
868             if (ctx->final[--b] != n) {
869                 EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
870                 return 0;
871             }
872         }
873         n = ctx->cipher->block_size - n;
874         for (i = 0; i < n; i++)
875             out[i] = ctx->final[i];
876         *outl = n;
877     } else
878         *outl = 0;
879     return 1;
880 }
881
882 int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen)
883 {
884     if (c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH)
885         return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL);
886     if (EVP_CIPHER_CTX_key_length(c) == keylen)
887         return 1;
888     if ((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) {
889         c->key_len = keylen;
890         return 1;
891     }
892     EVPerr(EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH, EVP_R_INVALID_KEY_LENGTH);
893     return 0;
894 }
895
896 int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad)
897 {
898     if (pad)
899         ctx->flags &= ~EVP_CIPH_NO_PADDING;
900     else
901         ctx->flags |= EVP_CIPH_NO_PADDING;
902
903     if (ctx->cipher != NULL && ctx->cipher->prov != NULL) {
904         OSSL_PARAM params[] = {
905             OSSL_PARAM_int(OSSL_CIPHER_PARAM_PADDING, NULL),
906             OSSL_PARAM_END
907         };
908
909         params[0].data = &pad;
910
911         if (ctx->cipher->ctx_set_params == NULL) {
912             EVPerr(EVP_F_EVP_CIPHER_CTX_SET_PADDING, EVP_R_CTRL_NOT_IMPLEMENTED);
913             return 0;
914         }
915
916         if (!ctx->cipher->ctx_set_params(ctx->provctx, params))
917             return 0;
918     }
919
920     return 1;
921 }
922
923 int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
924 {
925     int ret;
926
927     if (!ctx->cipher) {
928         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_NO_CIPHER_SET);
929         return 0;
930     }
931
932     if (!ctx->cipher->ctrl) {
933         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_NOT_IMPLEMENTED);
934         return 0;
935     }
936
937     ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
938     if (ret == -1) {
939         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL,
940                EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
941         return 0;
942     }
943     return ret;
944 }
945
946 int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
947 {
948     if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
949         return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
950     if (RAND_priv_bytes(key, ctx->key_len) <= 0)
951         return 0;
952     return 1;
953 }
954
955 int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
956 {
957     if ((in == NULL) || (in->cipher == NULL)) {
958         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INPUT_NOT_INITIALIZED);
959         return 0;
960     }
961
962     if (in->cipher->prov == NULL)
963         goto legacy;
964
965     if (in->cipher->dupctx == NULL) {
966         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_NOT_ABLE_TO_COPY_CTX);
967         return 0;
968     }
969
970     EVP_CIPHER_CTX_reset(out);
971
972     *out = *in;
973     out->provctx = NULL;
974
975     if (in->fetched_cipher != NULL && !EVP_CIPHER_upref(in->fetched_cipher)) {
976         out->fetched_cipher = NULL;
977         return 0;
978     }
979
980     out->provctx = in->cipher->dupctx(in->provctx);
981     if (out->provctx == NULL) {
982         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_NOT_ABLE_TO_COPY_CTX);
983         return 0;
984     }
985
986     return 1;
987
988     /* TODO(3.0): Remove legacy code below */
989  legacy:
990
991 #ifndef OPENSSL_NO_ENGINE
992     /* Make sure it's safe to copy a cipher context using an ENGINE */
993     if (in->engine && !ENGINE_init(in->engine)) {
994         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_ENGINE_LIB);
995         return 0;
996     }
997 #endif
998
999     EVP_CIPHER_CTX_reset(out);
1000     memcpy(out, in, sizeof(*out));
1001
1002     if (in->cipher_data && in->cipher->ctx_size) {
1003         out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
1004         if (out->cipher_data == NULL) {
1005             out->cipher = NULL;
1006             EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_MALLOC_FAILURE);
1007             return 0;
1008         }
1009         memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
1010     }
1011
1012     if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
1013         if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) {
1014             out->cipher = NULL;
1015             EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INITIALIZATION_ERROR);
1016             return 0;
1017         }
1018     return 1;
1019 }
1020
1021 static void *evp_cipher_from_dispatch(int nid, const OSSL_DISPATCH *fns,
1022                                       OSSL_PROVIDER *prov)
1023 {
1024     EVP_CIPHER *cipher = NULL;
1025     int fnciphcnt = 0, fnctxcnt = 0;
1026
1027     if ((cipher = EVP_CIPHER_meth_new(nid, 0, 0)) == NULL)
1028         return NULL;
1029
1030     for (; fns->function_id != 0; fns++) {
1031         switch (fns->function_id) {
1032         case OSSL_FUNC_CIPHER_NEWCTX:
1033             if (cipher->newctx != NULL)
1034                 break;
1035             cipher->newctx = OSSL_get_OP_cipher_newctx(fns);
1036             fnctxcnt++;
1037             break;
1038         case OSSL_FUNC_CIPHER_ENCRYPT_INIT:
1039             if (cipher->einit != NULL)
1040                 break;
1041             cipher->einit = OSSL_get_OP_cipher_encrypt_init(fns);
1042             fnciphcnt++;
1043             break;
1044         case OSSL_FUNC_CIPHER_DECRYPT_INIT:
1045             if (cipher->dinit != NULL)
1046                 break;
1047             cipher->dinit = OSSL_get_OP_cipher_decrypt_init(fns);
1048             fnciphcnt++;
1049             break;
1050         case OSSL_FUNC_CIPHER_UPDATE:
1051             if (cipher->cupdate != NULL)
1052                 break;
1053             cipher->cupdate = OSSL_get_OP_cipher_update(fns);
1054             fnciphcnt++;
1055             break;
1056         case OSSL_FUNC_CIPHER_FINAL:
1057             if (cipher->cfinal != NULL)
1058                 break;
1059             cipher->cfinal = OSSL_get_OP_cipher_final(fns);
1060             fnciphcnt++;
1061             break;
1062         case OSSL_FUNC_CIPHER_CIPHER:
1063             if (cipher->ccipher != NULL)
1064                 break;
1065             cipher->ccipher = OSSL_get_OP_cipher_cipher(fns);
1066             break;
1067         case OSSL_FUNC_CIPHER_FREECTX:
1068             if (cipher->freectx != NULL)
1069                 break;
1070             cipher->freectx = OSSL_get_OP_cipher_freectx(fns);
1071             fnctxcnt++;
1072             break;
1073         case OSSL_FUNC_CIPHER_DUPCTX:
1074             if (cipher->dupctx != NULL)
1075                 break;
1076             cipher->dupctx = OSSL_get_OP_cipher_dupctx(fns);
1077             break;
1078         case OSSL_FUNC_CIPHER_KEY_LENGTH:
1079             if (cipher->key_length != NULL)
1080                 break;
1081             cipher->key_length = OSSL_get_OP_cipher_key_length(fns);
1082             break;
1083         case OSSL_FUNC_CIPHER_IV_LENGTH:
1084             if (cipher->iv_length != NULL)
1085                 break;
1086             cipher->iv_length = OSSL_get_OP_cipher_iv_length(fns);
1087             break;
1088         case OSSL_FUNC_CIPHER_BLOCK_SIZE:
1089             if (cipher->blocksize != NULL)
1090                 break;
1091             cipher->blocksize = OSSL_get_OP_cipher_block_size(fns);
1092             break;
1093         case OSSL_FUNC_CIPHER_GET_PARAMS:
1094             if (cipher->get_params != NULL)
1095                 break;
1096             cipher->get_params = OSSL_get_OP_cipher_get_params(fns);
1097             break;
1098         case OSSL_FUNC_CIPHER_CTX_GET_PARAMS:
1099             if (cipher->ctx_get_params != NULL)
1100                 break;
1101             cipher->ctx_get_params = OSSL_get_OP_cipher_ctx_get_params(fns);
1102             break;
1103         case OSSL_FUNC_CIPHER_CTX_SET_PARAMS:
1104             if (cipher->ctx_set_params != NULL)
1105                 break;
1106             cipher->ctx_set_params = OSSL_get_OP_cipher_ctx_set_params(fns);
1107             break;
1108         }
1109     }
1110     if ((fnciphcnt != 0 && fnciphcnt != 3 && fnciphcnt != 4)
1111             || (fnciphcnt == 0 && cipher->ccipher == NULL)
1112             || fnctxcnt != 2
1113             || cipher->blocksize == NULL
1114             || cipher->iv_length == NULL
1115             || cipher->key_length == NULL) {
1116         /*
1117          * In order to be a consistent set of functions we must have at least
1118          * a complete set of "encrypt" functions, or a complete set of "decrypt"
1119          * functions, or a single "cipher" function. In all cases we need a
1120          * complete set of context management functions, as well as the
1121          * blocksize, iv_length and key_length functions.
1122          */
1123         EVP_CIPHER_meth_free(cipher);
1124         EVPerr(EVP_F_EVP_CIPHER_FROM_DISPATCH, EVP_R_INVALID_PROVIDER_FUNCTIONS);
1125         return NULL;
1126     }
1127     cipher->prov = prov;
1128     if (prov != NULL)
1129         ossl_provider_upref(prov);
1130
1131     return cipher;
1132 }
1133
1134 static int evp_cipher_upref(void *cipher)
1135 {
1136     return EVP_CIPHER_upref(cipher);
1137 }
1138
1139 static void evp_cipher_free(void *cipher)
1140 {
1141     EVP_CIPHER_meth_free(cipher);
1142 }
1143
1144 static int evp_cipher_nid(void *vcipher)
1145 {
1146     EVP_CIPHER *cipher = vcipher;
1147
1148     return cipher->nid;
1149 }
1150
1151 EVP_CIPHER *EVP_CIPHER_fetch(OPENSSL_CTX *ctx, const char *algorithm,
1152                              const char *properties)
1153 {
1154     return evp_generic_fetch(ctx, OSSL_OP_CIPHER, algorithm, properties,
1155                              evp_cipher_from_dispatch, evp_cipher_upref,
1156                              evp_cipher_free, evp_cipher_nid);
1157 }