Fix signed integer overflow in evp_enc
[openssl.git] / crypto / evp / evp_enc.c
1 /*
2  * Copyright 1995-2021 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 /* We need to use some engine deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
12
13 #include <stdio.h>
14 #include <limits.h>
15 #include <assert.h>
16 #include <openssl/evp.h>
17 #include <openssl/err.h>
18 #include <openssl/rand.h>
19 #ifndef FIPS_MODULE
20 # include <openssl/engine.h>
21 #endif
22 #include <openssl/params.h>
23 #include <openssl/core_names.h>
24 #include "internal/cryptlib.h"
25 #include "internal/provider.h"
26 #include "internal/core.h"
27 #include "crypto/evp.h"
28 #include "evp_local.h"
29
30 int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX *ctx)
31 {
32     if (ctx == NULL)
33         return 1;
34
35     if (ctx->cipher == NULL || ctx->cipher->prov == NULL)
36         goto legacy;
37
38     if (ctx->algctx != NULL) {
39         if (ctx->cipher->freectx != NULL)
40             ctx->cipher->freectx(ctx->algctx);
41         ctx->algctx = NULL;
42     }
43     if (ctx->fetched_cipher != NULL)
44         EVP_CIPHER_free(ctx->fetched_cipher);
45     memset(ctx, 0, sizeof(*ctx));
46     ctx->iv_len = -1;
47
48     return 1;
49
50     /* Remove legacy code below when legacy support is removed. */
51  legacy:
52
53     if (ctx->cipher != NULL) {
54         if (ctx->cipher->cleanup && !ctx->cipher->cleanup(ctx))
55             return 0;
56         /* Cleanse cipher context data */
57         if (ctx->cipher_data && ctx->cipher->ctx_size)
58             OPENSSL_cleanse(ctx->cipher_data, ctx->cipher->ctx_size);
59     }
60     OPENSSL_free(ctx->cipher_data);
61 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
62     ENGINE_finish(ctx->engine);
63 #endif
64     memset(ctx, 0, sizeof(*ctx));
65     ctx->iv_len = -1;
66     return 1;
67 }
68
69 EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void)
70 {
71     EVP_CIPHER_CTX *ctx;
72
73     ctx = OPENSSL_zalloc(sizeof(EVP_CIPHER_CTX));
74     if (ctx == NULL)
75         return NULL;
76
77     ctx->iv_len = -1;
78     return ctx;
79 }
80
81 void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx)
82 {
83     if (ctx == NULL)
84         return;
85     EVP_CIPHER_CTX_reset(ctx);
86     OPENSSL_free(ctx);
87 }
88
89 static int evp_cipher_init_internal(EVP_CIPHER_CTX *ctx,
90                                     const EVP_CIPHER *cipher,
91                                     ENGINE *impl, const unsigned char *key,
92                                     const unsigned char *iv, int enc,
93                                     const OSSL_PARAM params[])
94 {
95     int n;
96 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
97     ENGINE *tmpimpl = NULL;
98 #endif
99
100     /*
101      * enc == 1 means we are encrypting.
102      * enc == 0 means we are decrypting.
103      * enc == -1 means, use the previously initialised value for encrypt/decrypt
104      */
105     if (enc == -1) {
106         enc = ctx->encrypt;
107     } else {
108         if (enc)
109             enc = 1;
110         ctx->encrypt = enc;
111     }
112
113     if (cipher == NULL && ctx->cipher == NULL) {
114         ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET);
115         return 0;
116     }
117
118     /* Code below to be removed when legacy support is dropped. */
119
120 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
121     /*
122      * Whether it's nice or not, "Inits" can be used on "Final"'d contexts so
123      * this context may already have an ENGINE! Try to avoid releasing the
124      * previous handle, re-querying for an ENGINE, and having a
125      * reinitialisation, when it may all be unnecessary.
126      */
127     if (ctx->engine && ctx->cipher
128         && (cipher == NULL || cipher->nid == ctx->cipher->nid))
129         goto skip_to_init;
130
131     if (cipher != NULL && impl == NULL) {
132          /* Ask if an ENGINE is reserved for this job */
133         tmpimpl = ENGINE_get_cipher_engine(cipher->nid);
134     }
135 #endif
136
137     /*
138      * If there are engines involved then we should use legacy handling for now.
139      */
140     if (ctx->engine != NULL
141 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
142             || tmpimpl != NULL
143 #endif
144             || impl != NULL) {
145         if (ctx->cipher == ctx->fetched_cipher)
146             ctx->cipher = NULL;
147         EVP_CIPHER_free(ctx->fetched_cipher);
148         ctx->fetched_cipher = NULL;
149         goto legacy;
150     }
151     /*
152      * Ensure a context left lying around from last time is cleared
153      * (legacy code)
154      */
155     if (cipher != NULL && ctx->cipher != NULL) {
156         OPENSSL_clear_free(ctx->cipher_data, ctx->cipher->ctx_size);
157         ctx->cipher_data = NULL;
158     }
159
160
161     /* Start of non-legacy code below */
162
163     /* Ensure a context left lying around from last time is cleared */
164     if (cipher != NULL && ctx->cipher != NULL) {
165         unsigned long flags = ctx->flags;
166
167         EVP_CIPHER_CTX_reset(ctx);
168         /* Restore encrypt and flags */
169         ctx->encrypt = enc;
170         ctx->flags = flags;
171     }
172
173     if (cipher == NULL)
174         cipher = ctx->cipher;
175
176     if (cipher->prov == NULL) {
177 #ifdef FIPS_MODULE
178         /* We only do explicit fetches inside the FIPS module */
179         ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
180         return 0;
181 #else
182         EVP_CIPHER *provciph =
183             EVP_CIPHER_fetch(NULL,
184                              cipher->nid == NID_undef ? "NULL"
185                                                       : OBJ_nid2sn(cipher->nid),
186                              "");
187
188         if (provciph == NULL)
189             return 0;
190         cipher = provciph;
191         EVP_CIPHER_free(ctx->fetched_cipher);
192         ctx->fetched_cipher = provciph;
193 #endif
194     }
195
196     if (cipher->prov != NULL) {
197         if (!EVP_CIPHER_up_ref((EVP_CIPHER *)cipher)) {
198             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
199             return 0;
200         }
201         EVP_CIPHER_free(ctx->fetched_cipher);
202         ctx->fetched_cipher = (EVP_CIPHER *)cipher;
203     }
204     ctx->cipher = cipher;
205     if (ctx->algctx == NULL) {
206         ctx->algctx = ctx->cipher->newctx(ossl_provider_ctx(cipher->prov));
207         if (ctx->algctx == NULL) {
208             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
209             return 0;
210         }
211     }
212
213     if ((ctx->flags & EVP_CIPH_NO_PADDING) != 0) {
214         /*
215          * If this ctx was already set up for no padding then we need to tell
216          * the new cipher about it.
217          */
218         if (!EVP_CIPHER_CTX_set_padding(ctx, 0))
219             return 0;
220     }
221
222     if (enc) {
223         if (ctx->cipher->einit == NULL) {
224             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
225             return 0;
226         }
227
228         return ctx->cipher->einit(ctx->algctx,
229                                   key,
230                                   key == NULL ? 0
231                                               : EVP_CIPHER_CTX_get_key_length(ctx),
232                                   iv,
233                                   iv == NULL ? 0
234                                              : EVP_CIPHER_CTX_get_iv_length(ctx),
235                                   params);
236     }
237
238     if (ctx->cipher->dinit == NULL) {
239         ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
240         return 0;
241     }
242
243     return ctx->cipher->dinit(ctx->algctx,
244                               key,
245                               key == NULL ? 0
246                                           : EVP_CIPHER_CTX_get_key_length(ctx),
247                               iv,
248                               iv == NULL ? 0
249                                          : EVP_CIPHER_CTX_get_iv_length(ctx),
250                                   params);
251
252     /* Code below to be removed when legacy support is dropped. */
253  legacy:
254
255     if (cipher != NULL) {
256         /*
257          * Ensure a context left lying around from last time is cleared (we
258          * previously attempted to avoid this if the same ENGINE and
259          * EVP_CIPHER could be used).
260          */
261         if (ctx->cipher) {
262             unsigned long flags = ctx->flags;
263             EVP_CIPHER_CTX_reset(ctx);
264             /* Restore encrypt and flags */
265             ctx->encrypt = enc;
266             ctx->flags = flags;
267         }
268 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
269         if (impl != NULL) {
270             if (!ENGINE_init(impl)) {
271                 ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
272                 return 0;
273             }
274         } else {
275             impl = tmpimpl;
276         }
277         if (impl != NULL) {
278             /* There's an ENGINE for this job ... (apparently) */
279             const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid);
280
281             if (c == NULL) {
282                 /*
283                  * One positive side-effect of US's export control history,
284                  * is that we should at least be able to avoid using US
285                  * misspellings of "initialisation"?
286                  */
287                 ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
288                 return 0;
289             }
290             /* We'll use the ENGINE's private cipher definition */
291             cipher = c;
292             /*
293              * Store the ENGINE functional reference so we know 'cipher' came
294              * from an ENGINE and we need to release it when done.
295              */
296             ctx->engine = impl;
297         } else {
298             ctx->engine = NULL;
299         }
300 #endif
301
302         ctx->cipher = cipher;
303         if (ctx->cipher->ctx_size) {
304             ctx->cipher_data = OPENSSL_zalloc(ctx->cipher->ctx_size);
305             if (ctx->cipher_data == NULL) {
306                 ctx->cipher = NULL;
307                 ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
308                 return 0;
309             }
310         } else {
311             ctx->cipher_data = NULL;
312         }
313         ctx->key_len = cipher->key_len;
314         /* Preserve wrap enable flag, zero everything else */
315         ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW;
316         if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) {
317             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) {
318                 ctx->cipher = NULL;
319                 ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
320                 return 0;
321             }
322         }
323     }
324 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
325  skip_to_init:
326 #endif
327     if (ctx->cipher == NULL)
328         return 0;
329
330     /* we assume block size is a power of 2 in *cryptUpdate */
331     OPENSSL_assert(ctx->cipher->block_size == 1
332                    || ctx->cipher->block_size == 8
333                    || ctx->cipher->block_size == 16);
334
335     if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW)
336         && EVP_CIPHER_CTX_get_mode(ctx) == EVP_CIPH_WRAP_MODE) {
337         ERR_raise(ERR_LIB_EVP, EVP_R_WRAP_MODE_NOT_ALLOWED);
338         return 0;
339     }
340
341     if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx))
342                 & EVP_CIPH_CUSTOM_IV) == 0) {
343         switch (EVP_CIPHER_CTX_get_mode(ctx)) {
344
345         case EVP_CIPH_STREAM_CIPHER:
346         case EVP_CIPH_ECB_MODE:
347             break;
348
349         case EVP_CIPH_CFB_MODE:
350         case EVP_CIPH_OFB_MODE:
351
352             ctx->num = 0;
353             /* fall-through */
354
355         case EVP_CIPH_CBC_MODE:
356             n = EVP_CIPHER_CTX_get_iv_length(ctx);
357             if (!ossl_assert(n >= 0 && n <= (int)sizeof(ctx->iv)))
358                     return 0;
359             if (iv != NULL)
360                 memcpy(ctx->oiv, iv, n);
361             memcpy(ctx->iv, ctx->oiv, n);
362             break;
363
364         case EVP_CIPH_CTR_MODE:
365             ctx->num = 0;
366             /* Don't reuse IV for CTR mode */
367             if (iv != NULL) {
368                 if ((n = EVP_CIPHER_CTX_get_iv_length(ctx)) <= 0)
369                     return 0;
370                 memcpy(ctx->iv, iv, n);
371             }
372             break;
373
374         default:
375             return 0;
376         }
377     }
378
379     if (key != NULL || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
380         if (!ctx->cipher->init(ctx, key, iv, enc))
381             return 0;
382     }
383     ctx->buf_len = 0;
384     ctx->final_used = 0;
385     ctx->block_mask = ctx->cipher->block_size - 1;
386     return 1;
387 }
388
389 int EVP_CipherInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
390                        const unsigned char *key, const unsigned char *iv,
391                        int enc, const OSSL_PARAM params[])
392 {
393     return evp_cipher_init_internal(ctx, cipher, NULL, key, iv, enc, params);
394 }
395
396 int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
397                    const unsigned char *key, const unsigned char *iv, int enc)
398 {
399     if (cipher != NULL)
400         EVP_CIPHER_CTX_reset(ctx);
401     return evp_cipher_init_internal(ctx, cipher, NULL, key, iv, enc, NULL);
402 }
403
404 int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
405                       ENGINE *impl, const unsigned char *key,
406                       const unsigned char *iv, int enc)
407 {
408     return evp_cipher_init_internal(ctx, cipher, impl, key, iv, enc, NULL);
409 }
410
411 int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
412                      const unsigned char *in, int inl)
413 {
414     if (ctx->encrypt)
415         return EVP_EncryptUpdate(ctx, out, outl, in, inl);
416     else
417         return EVP_DecryptUpdate(ctx, out, outl, in, inl);
418 }
419
420 int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
421 {
422     if (ctx->encrypt)
423         return EVP_EncryptFinal_ex(ctx, out, outl);
424     else
425         return EVP_DecryptFinal_ex(ctx, out, outl);
426 }
427
428 int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
429 {
430     if (ctx->encrypt)
431         return EVP_EncryptFinal(ctx, out, outl);
432     else
433         return EVP_DecryptFinal(ctx, out, outl);
434 }
435
436 int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
437                     const unsigned char *key, const unsigned char *iv)
438 {
439     return EVP_CipherInit(ctx, cipher, key, iv, 1);
440 }
441
442 int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
443                        ENGINE *impl, const unsigned char *key,
444                        const unsigned char *iv)
445 {
446     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
447 }
448
449 int EVP_EncryptInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
450                         const unsigned char *key, const unsigned char *iv,
451                         const OSSL_PARAM params[])
452 {
453     return EVP_CipherInit_ex2(ctx, cipher, key, iv, 1, params);
454 }
455
456 int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
457                     const unsigned char *key, const unsigned char *iv)
458 {
459     return EVP_CipherInit(ctx, cipher, key, iv, 0);
460 }
461
462 int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
463                        ENGINE *impl, const unsigned char *key,
464                        const unsigned char *iv)
465 {
466     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
467 }
468
469 int EVP_DecryptInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
470                         const unsigned char *key, const unsigned char *iv,
471                         const OSSL_PARAM params[])
472 {
473     return EVP_CipherInit_ex2(ctx, cipher, key, iv, 0, params);
474 }
475
476 /*
477  * According to the letter of standard difference between pointers
478  * is specified to be valid only within same object. This makes
479  * it formally challenging to determine if input and output buffers
480  * are not partially overlapping with standard pointer arithmetic.
481  */
482 #ifdef PTRDIFF_T
483 # undef PTRDIFF_T
484 #endif
485 #if defined(OPENSSL_SYS_VMS) && __INITIAL_POINTER_SIZE==64
486 /*
487  * Then we have VMS that distinguishes itself by adhering to
488  * sizeof(size_t)==4 even in 64-bit builds, which means that
489  * difference between two pointers might be truncated to 32 bits.
490  * In the context one can even wonder how comparison for
491  * equality is implemented. To be on the safe side we adhere to
492  * PTRDIFF_T even for comparison for equality.
493  */
494 # define PTRDIFF_T uint64_t
495 #else
496 # define PTRDIFF_T size_t
497 #endif
498
499 int ossl_is_partially_overlapping(const void *ptr1, const void *ptr2, int len)
500 {
501     PTRDIFF_T diff = (PTRDIFF_T)ptr1-(PTRDIFF_T)ptr2;
502     /*
503      * Check for partially overlapping buffers. [Binary logical
504      * operations are used instead of boolean to minimize number
505      * of conditional branches.]
506      */
507     int overlapped = (len > 0) & (diff != 0) & ((diff < (PTRDIFF_T)len) |
508                                                 (diff > (0 - (PTRDIFF_T)len)));
509
510     return overlapped;
511 }
512
513 static int evp_EncryptDecryptUpdate(EVP_CIPHER_CTX *ctx,
514                                     unsigned char *out, int *outl,
515                                     const unsigned char *in, int inl)
516 {
517     int i, j, bl, cmpl = inl;
518
519     if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS))
520         cmpl = (cmpl + 7) / 8;
521
522     bl = ctx->cipher->block_size;
523
524     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
525         /* If block size > 1 then the cipher will have to do this check */
526         if (bl == 1 && ossl_is_partially_overlapping(out, in, cmpl)) {
527             ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING);
528             return 0;
529         }
530
531         i = ctx->cipher->do_cipher(ctx, out, in, inl);
532         if (i < 0)
533             return 0;
534         else
535             *outl = i;
536         return 1;
537     }
538
539     if (inl <= 0) {
540         *outl = 0;
541         return inl == 0;
542     }
543     if (ossl_is_partially_overlapping(out + ctx->buf_len, in, cmpl)) {
544         ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING);
545         return 0;
546     }
547
548     if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
549         if (ctx->cipher->do_cipher(ctx, out, in, inl)) {
550             *outl = inl;
551             return 1;
552         } else {
553             *outl = 0;
554             return 0;
555         }
556     }
557     i = ctx->buf_len;
558     OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
559     if (i != 0) {
560         if (bl - i > inl) {
561             memcpy(&(ctx->buf[i]), in, inl);
562             ctx->buf_len += inl;
563             *outl = 0;
564             return 1;
565         } else {
566             j = bl - i;
567
568             /*
569              * Once we've processed the first j bytes from in, the amount of
570              * data left that is a multiple of the block length is:
571              * (inl - j) & ~(bl - 1)
572              * We must ensure that this amount of data, plus the one block that
573              * we process from ctx->buf does not exceed INT_MAX
574              */
575             if (((inl - j) & ~(bl - 1)) > INT_MAX - bl) {
576                 ERR_raise(ERR_LIB_EVP, EVP_R_OUTPUT_WOULD_OVERFLOW);
577                 return 0;
578             }
579             memcpy(&(ctx->buf[i]), in, j);
580             inl -= j;
581             in += j;
582             if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl))
583                 return 0;
584             out += bl;
585             *outl = bl;
586         }
587     } else
588         *outl = 0;
589     i = inl & (bl - 1);
590     inl -= i;
591     if (inl > 0) {
592         if (!ctx->cipher->do_cipher(ctx, out, in, inl))
593             return 0;
594         *outl += inl;
595     }
596
597     if (i != 0)
598         memcpy(ctx->buf, &(in[inl]), i);
599     ctx->buf_len = i;
600     return 1;
601 }
602
603
604 int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
605                       const unsigned char *in, int inl)
606 {
607     int ret;
608     size_t soutl, inl_ = (size_t)inl;
609     int blocksize;
610
611     if (outl != NULL) {
612         *outl = 0;
613     } else {
614         ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
615         return 0;
616     }
617
618     /* Prevent accidental use of decryption context when encrypting */
619     if (!ctx->encrypt) {
620         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION);
621         return 0;
622     }
623
624     if (ctx->cipher == NULL) {
625         ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET);
626         return 0;
627     }
628
629     if (ctx->cipher->prov == NULL)
630         goto legacy;
631
632     blocksize = ctx->cipher->block_size;
633
634     if (ctx->cipher->cupdate == NULL  || blocksize < 1) {
635         ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
636         return 0;
637     }
638
639     ret = ctx->cipher->cupdate(ctx->algctx, out, &soutl,
640                                inl_ + (size_t)(blocksize == 1 ? 0 : blocksize),
641                                in, inl_);
642
643     if (ret) {
644         if (soutl > INT_MAX) {
645             ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
646             return 0;
647         }
648         *outl = soutl;
649     }
650
651     return ret;
652
653     /* Code below to be removed when legacy support is dropped. */
654  legacy:
655
656     return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl);
657 }
658
659 int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
660 {
661     int ret;
662     ret = EVP_EncryptFinal_ex(ctx, out, outl);
663     return ret;
664 }
665
666 int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
667 {
668     int n, ret;
669     unsigned int i, b, bl;
670     size_t soutl;
671     int blocksize;
672
673     if (outl != NULL) {
674         *outl = 0;
675     } else {
676         ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
677         return 0;
678     }
679
680     /* Prevent accidental use of decryption context when encrypting */
681     if (!ctx->encrypt) {
682         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION);
683         return 0;
684     }
685
686     if (ctx->cipher == NULL) {
687         ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET);
688         return 0;
689     }
690     if (ctx->cipher->prov == NULL)
691         goto legacy;
692
693     blocksize = EVP_CIPHER_CTX_get_block_size(ctx);
694
695     if (blocksize < 1 || ctx->cipher->cfinal == NULL) {
696         ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
697         return 0;
698     }
699
700     ret = ctx->cipher->cfinal(ctx->algctx, out, &soutl,
701                               blocksize == 1 ? 0 : blocksize);
702
703     if (ret) {
704         if (soutl > INT_MAX) {
705             ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
706             return 0;
707         }
708         *outl = soutl;
709     }
710
711     return ret;
712
713     /* Code below to be removed when legacy support is dropped. */
714  legacy:
715
716     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
717         ret = ctx->cipher->do_cipher(ctx, out, NULL, 0);
718         if (ret < 0)
719             return 0;
720         else
721             *outl = ret;
722         return 1;
723     }
724
725     b = ctx->cipher->block_size;
726     OPENSSL_assert(b <= sizeof(ctx->buf));
727     if (b == 1) {
728         *outl = 0;
729         return 1;
730     }
731     bl = ctx->buf_len;
732     if (ctx->flags & EVP_CIPH_NO_PADDING) {
733         if (bl) {
734             ERR_raise(ERR_LIB_EVP, EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
735             return 0;
736         }
737         *outl = 0;
738         return 1;
739     }
740
741     n = b - bl;
742     for (i = bl; i < b; i++)
743         ctx->buf[i] = n;
744     ret = ctx->cipher->do_cipher(ctx, out, ctx->buf, b);
745
746     if (ret)
747         *outl = b;
748
749     return ret;
750 }
751
752 int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
753                       const unsigned char *in, int inl)
754 {
755     int fix_len, cmpl = inl, ret;
756     unsigned int b;
757     size_t soutl, inl_ = (size_t)inl;
758     int blocksize;
759
760     if (outl != NULL) {
761         *outl = 0;
762     } else {
763         ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
764         return 0;
765     }
766
767     /* Prevent accidental use of encryption context when decrypting */
768     if (ctx->encrypt) {
769         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION);
770         return 0;
771     }
772
773     if (ctx->cipher == NULL) {
774         ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET);
775         return 0;
776     }
777     if (ctx->cipher->prov == NULL)
778         goto legacy;
779
780     blocksize = EVP_CIPHER_CTX_get_block_size(ctx);
781
782     if (ctx->cipher->cupdate == NULL || blocksize < 1) {
783         ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
784         return 0;
785     }
786     ret = ctx->cipher->cupdate(ctx->algctx, out, &soutl,
787                                inl_ + (size_t)(blocksize == 1 ? 0 : blocksize),
788                                in, inl_);
789
790     if (ret) {
791         if (soutl > INT_MAX) {
792             ERR_raise(ERR_LIB_EVP, EVP_R_UPDATE_ERROR);
793             return 0;
794         }
795         *outl = soutl;
796     }
797
798     return ret;
799
800     /* Code below to be removed when legacy support is dropped. */
801  legacy:
802
803     b = ctx->cipher->block_size;
804
805     if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS))
806         cmpl = (cmpl + 7) / 8;
807
808     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
809         if (b == 1 && ossl_is_partially_overlapping(out, in, cmpl)) {
810             ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING);
811             return 0;
812         }
813
814         fix_len = ctx->cipher->do_cipher(ctx, out, in, inl);
815         if (fix_len < 0) {
816             *outl = 0;
817             return 0;
818         } else
819             *outl = fix_len;
820         return 1;
821     }
822
823     if (inl <= 0) {
824         *outl = 0;
825         return inl == 0;
826     }
827
828     if (ctx->flags & EVP_CIPH_NO_PADDING)
829         return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl);
830
831     OPENSSL_assert(b <= sizeof(ctx->final));
832
833     if (ctx->final_used) {
834         /* see comment about PTRDIFF_T comparison above */
835         if (((PTRDIFF_T)out == (PTRDIFF_T)in)
836             || ossl_is_partially_overlapping(out, in, b)) {
837             ERR_raise(ERR_LIB_EVP, EVP_R_PARTIALLY_OVERLAPPING);
838             return 0;
839         }
840         /*
841          * final_used is only ever set if buf_len is 0. Therefore the maximum
842          * length output we will ever see from evp_EncryptDecryptUpdate is
843          * the maximum multiple of the block length that is <= inl, or just:
844          * inl & ~(b - 1)
845          * Since final_used has been set then the final output length is:
846          * (inl & ~(b - 1)) + b
847          * This must never exceed INT_MAX
848          */
849         if ((inl & ~(b - 1)) > INT_MAX - b) {
850             ERR_raise(ERR_LIB_EVP, EVP_R_OUTPUT_WOULD_OVERFLOW);
851             return 0;
852         }
853         memcpy(out, ctx->final, b);
854         out += b;
855         fix_len = 1;
856     } else
857         fix_len = 0;
858
859     if (!evp_EncryptDecryptUpdate(ctx, out, outl, in, inl))
860         return 0;
861
862     /*
863      * if we have 'decrypted' a multiple of block size, make sure we have a
864      * copy of this last block
865      */
866     if (b > 1 && !ctx->buf_len) {
867         *outl -= b;
868         ctx->final_used = 1;
869         memcpy(ctx->final, &out[*outl], b);
870     } else
871         ctx->final_used = 0;
872
873     if (fix_len)
874         *outl += b;
875
876     return 1;
877 }
878
879 int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
880 {
881     int ret;
882     ret = EVP_DecryptFinal_ex(ctx, out, outl);
883     return ret;
884 }
885
886 int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
887 {
888     int i, n;
889     unsigned int b;
890     size_t soutl;
891     int ret;
892     int blocksize;
893
894     if (outl != NULL) {
895         *outl = 0;
896     } else {
897         ERR_raise(ERR_LIB_EVP, ERR_R_PASSED_NULL_PARAMETER);
898         return 0;
899     }
900
901     /* Prevent accidental use of encryption context when decrypting */
902     if (ctx->encrypt) {
903         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_OPERATION);
904         return 0;
905     }
906
907     if (ctx->cipher == NULL) {
908         ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET);
909         return 0;
910     }
911
912     if (ctx->cipher->prov == NULL)
913         goto legacy;
914
915     blocksize = EVP_CIPHER_CTX_get_block_size(ctx);
916
917     if (blocksize < 1 || ctx->cipher->cfinal == NULL) {
918         ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
919         return 0;
920     }
921
922     ret = ctx->cipher->cfinal(ctx->algctx, out, &soutl,
923                               blocksize == 1 ? 0 : blocksize);
924
925     if (ret) {
926         if (soutl > INT_MAX) {
927             ERR_raise(ERR_LIB_EVP, EVP_R_FINAL_ERROR);
928             return 0;
929         }
930         *outl = soutl;
931     }
932
933     return ret;
934
935     /* Code below to be removed when legacy support is dropped. */
936  legacy:
937
938     *outl = 0;
939     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
940         i = ctx->cipher->do_cipher(ctx, out, NULL, 0);
941         if (i < 0)
942             return 0;
943         else
944             *outl = i;
945         return 1;
946     }
947
948     b = ctx->cipher->block_size;
949     if (ctx->flags & EVP_CIPH_NO_PADDING) {
950         if (ctx->buf_len) {
951             ERR_raise(ERR_LIB_EVP, EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
952             return 0;
953         }
954         *outl = 0;
955         return 1;
956     }
957     if (b > 1) {
958         if (ctx->buf_len || !ctx->final_used) {
959             ERR_raise(ERR_LIB_EVP, EVP_R_WRONG_FINAL_BLOCK_LENGTH);
960             return 0;
961         }
962         OPENSSL_assert(b <= sizeof(ctx->final));
963
964         /*
965          * The following assumes that the ciphertext has been authenticated.
966          * Otherwise it provides a padding oracle.
967          */
968         n = ctx->final[b - 1];
969         if (n == 0 || n > (int)b) {
970             ERR_raise(ERR_LIB_EVP, EVP_R_BAD_DECRYPT);
971             return 0;
972         }
973         for (i = 0; i < n; i++) {
974             if (ctx->final[--b] != n) {
975                 ERR_raise(ERR_LIB_EVP, EVP_R_BAD_DECRYPT);
976                 return 0;
977             }
978         }
979         n = ctx->cipher->block_size - n;
980         for (i = 0; i < n; i++)
981             out[i] = ctx->final[i];
982         *outl = n;
983     } else
984         *outl = 0;
985     return 1;
986 }
987
988 int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen)
989 {
990     if (c->cipher->prov != NULL) {
991         int ok;
992         OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
993         size_t len;
994
995         if (EVP_CIPHER_CTX_get_key_length(c) == keylen)
996             return 1;
997
998         /* Check the cipher actually understands this parameter */
999         if (OSSL_PARAM_locate_const(EVP_CIPHER_settable_ctx_params(c->cipher),
1000                                     OSSL_CIPHER_PARAM_KEYLEN) == NULL) {
1001             ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH);
1002             return 0;
1003         }
1004
1005         params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &len);
1006         if (!OSSL_PARAM_set_int(params, keylen))
1007             return 0;
1008         ok = evp_do_ciph_ctx_setparams(c->cipher, c->algctx, params);
1009         if (ok <= 0)
1010             return 0;
1011         c->key_len = keylen;
1012         return 1;
1013     }
1014
1015     /* Code below to be removed when legacy support is dropped. */
1016
1017     /*
1018      * Note there have never been any built-in ciphers that define this flag
1019      * since it was first introduced.
1020      */
1021     if (c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH)
1022         return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL);
1023     if (EVP_CIPHER_CTX_get_key_length(c) == keylen)
1024         return 1;
1025     if ((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) {
1026         c->key_len = keylen;
1027         return 1;
1028     }
1029     ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_KEY_LENGTH);
1030     return 0;
1031 }
1032
1033 int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad)
1034 {
1035     int ok;
1036     OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END };
1037     unsigned int pd = pad;
1038
1039     if (pad)
1040         ctx->flags &= ~EVP_CIPH_NO_PADDING;
1041     else
1042         ctx->flags |= EVP_CIPH_NO_PADDING;
1043
1044     if (ctx->cipher != NULL && ctx->cipher->prov == NULL)
1045         return 1;
1046     params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_PADDING, &pd);
1047     ok = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params);
1048
1049     return ok != 0;
1050 }
1051
1052 int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
1053 {
1054     int ret = EVP_CTRL_RET_UNSUPPORTED;
1055     int set_params = 1;
1056     size_t sz = arg;
1057     unsigned int i;
1058     OSSL_PARAM params[4] = {
1059         OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END
1060     };
1061
1062     if (ctx == NULL || ctx->cipher == NULL) {
1063         ERR_raise(ERR_LIB_EVP, EVP_R_NO_CIPHER_SET);
1064         return 0;
1065     }
1066
1067     if (ctx->cipher->prov == NULL)
1068         goto legacy;
1069
1070     switch (type) {
1071     case EVP_CTRL_SET_KEY_LENGTH:
1072         params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_KEYLEN, &sz);
1073         ctx->key_len = -1;
1074         break;
1075     case EVP_CTRL_RAND_KEY:      /* Used by DES */
1076         set_params = 0;
1077         params[0] =
1078             OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_RANDOM_KEY,
1079                                               ptr, sz);
1080         break;
1081
1082     case EVP_CTRL_INIT:
1083         /*
1084          * EVP_CTRL_INIT is purely legacy, no provider counterpart.
1085          * As a matter of fact, this should be dead code, but some caller
1086          * might still do a direct control call with this command, so...
1087          * Legacy methods return 1 except for exceptional circumstances, so
1088          * we do the same here to not be disruptive.
1089          */
1090         return 1;
1091     case EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS: /* Used by DASYNC */
1092     default:
1093         goto end;
1094     case EVP_CTRL_AEAD_SET_IVLEN:
1095         if (arg < 0)
1096             return 0;
1097         params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_IVLEN, &sz);
1098         ctx->iv_len = -1;
1099         break;
1100     case EVP_CTRL_CCM_SET_L:
1101         if (arg < 2 || arg > 8)
1102             return 0;
1103         sz = 15 - arg;
1104         params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_IVLEN, &sz);
1105         ctx->iv_len = -1;
1106         break;
1107     case EVP_CTRL_AEAD_SET_IV_FIXED:
1108         params[0] = OSSL_PARAM_construct_octet_string(
1109                         OSSL_CIPHER_PARAM_AEAD_TLS1_IV_FIXED, ptr, sz);
1110         break;
1111     case EVP_CTRL_GCM_IV_GEN:
1112         set_params = 0;
1113         if (arg < 0)
1114             sz = 0; /* special case that uses the iv length */
1115         params[0] = OSSL_PARAM_construct_octet_string(
1116                         OSSL_CIPHER_PARAM_AEAD_TLS1_GET_IV_GEN, ptr, sz);
1117         break;
1118     case EVP_CTRL_GCM_SET_IV_INV:
1119         if (arg < 0)
1120             return 0;
1121         params[0] = OSSL_PARAM_construct_octet_string(
1122                         OSSL_CIPHER_PARAM_AEAD_TLS1_SET_IV_INV, ptr, sz);
1123         break;
1124     case EVP_CTRL_GET_RC5_ROUNDS:
1125         set_params = 0; /* Fall thru */
1126     case EVP_CTRL_SET_RC5_ROUNDS:
1127         if (arg < 0)
1128             return 0;
1129         i = (unsigned int)arg;
1130         params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_ROUNDS, &i);
1131         break;
1132     case EVP_CTRL_SET_SPEED:
1133         if (arg < 0)
1134             return 0;
1135         i = (unsigned int)arg;
1136         params[0] = OSSL_PARAM_construct_uint(OSSL_CIPHER_PARAM_SPEED, &i);
1137         break;
1138     case EVP_CTRL_AEAD_GET_TAG:
1139         set_params = 0; /* Fall thru */
1140     case EVP_CTRL_AEAD_SET_TAG:
1141         params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG,
1142                                                       ptr, sz);
1143         break;
1144     case EVP_CTRL_AEAD_TLS1_AAD:
1145         /* This one does a set and a get - since it returns a size */
1146         params[0] =
1147             OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD,
1148                                               ptr, sz);
1149         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params);
1150         if (ret <= 0)
1151             goto end;
1152         params[0] =
1153             OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_TLS1_AAD_PAD, &sz);
1154         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params);
1155         if (ret <= 0)
1156             goto end;
1157         return sz;
1158 #ifndef OPENSSL_NO_RC2
1159     case EVP_CTRL_GET_RC2_KEY_BITS:
1160         set_params = 0; /* Fall thru */
1161     case EVP_CTRL_SET_RC2_KEY_BITS:
1162         params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_RC2_KEYBITS, &sz);
1163         break;
1164 #endif /* OPENSSL_NO_RC2 */
1165 #if !defined(OPENSSL_NO_MULTIBLOCK)
1166     case EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE:
1167         params[0] = OSSL_PARAM_construct_size_t(
1168                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_SEND_FRAGMENT, &sz);
1169         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params);
1170         if (ret <= 0)
1171             return 0;
1172
1173         params[0] = OSSL_PARAM_construct_size_t(
1174                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_BUFSIZE, &sz);
1175         params[1] = OSSL_PARAM_construct_end();
1176         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params);
1177         if (ret <= 0)
1178             return 0;
1179         return sz;
1180     case EVP_CTRL_TLS1_1_MULTIBLOCK_AAD: {
1181         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *p =
1182             (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *)ptr;
1183
1184         if (arg < (int)sizeof(EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM))
1185             return 0;
1186
1187         params[0] = OSSL_PARAM_construct_octet_string(
1188                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD, (void*)p->inp, p->len);
1189         params[1] = OSSL_PARAM_construct_uint(
1190                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE, &p->interleave);
1191         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params);
1192         if (ret <= 0)
1193             return ret;
1194         /* Retrieve the return values changed by the set */
1195         params[0] = OSSL_PARAM_construct_size_t(
1196                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD_PACKLEN, &sz);
1197         params[1] = OSSL_PARAM_construct_uint(
1198                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE, &p->interleave);
1199         params[2] = OSSL_PARAM_construct_end();
1200         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params);
1201         if (ret <= 0)
1202             return 0;
1203         return sz;
1204     }
1205     case EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT: {
1206         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *p =
1207             (EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM *)ptr;
1208
1209         params[0] = OSSL_PARAM_construct_octet_string(
1210                         OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC, p->out, p->len);
1211
1212         params[1] = OSSL_PARAM_construct_octet_string(
1213                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_IN, (void*)p->inp,
1214                 p->len);
1215         params[2] = OSSL_PARAM_construct_uint(
1216                 OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE, &p->interleave);
1217         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params);
1218         if (ret <= 0)
1219             return ret;
1220         params[0] = OSSL_PARAM_construct_size_t(
1221                         OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_LEN, &sz);
1222         params[1] = OSSL_PARAM_construct_end();
1223         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params);
1224         if (ret <= 0)
1225             return 0;
1226         return sz;
1227     }
1228 #endif /* OPENSSL_NO_MULTIBLOCK */
1229     case EVP_CTRL_AEAD_SET_MAC_KEY:
1230         if (arg < 0)
1231             return -1;
1232         params[0] = OSSL_PARAM_construct_octet_string(
1233                 OSSL_CIPHER_PARAM_AEAD_MAC_KEY, ptr, sz);
1234         break;
1235     }
1236
1237     if (set_params)
1238         ret = evp_do_ciph_ctx_setparams(ctx->cipher, ctx->algctx, params);
1239     else
1240         ret = evp_do_ciph_ctx_getparams(ctx->cipher, ctx->algctx, params);
1241     goto end;
1242
1243     /* Code below to be removed when legacy support is dropped. */
1244 legacy:
1245     if (ctx->cipher->ctrl == NULL) {
1246         ERR_raise(ERR_LIB_EVP, EVP_R_CTRL_NOT_IMPLEMENTED);
1247         return 0;
1248     }
1249
1250     ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
1251
1252  end:
1253     if (ret == EVP_CTRL_RET_UNSUPPORTED) {
1254         ERR_raise(ERR_LIB_EVP, EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
1255         return 0;
1256     }
1257     return ret;
1258 }
1259
1260 int EVP_CIPHER_get_params(EVP_CIPHER *cipher, OSSL_PARAM params[])
1261 {
1262     if (cipher != NULL && cipher->get_params != NULL)
1263         return cipher->get_params(params);
1264     return 0;
1265 }
1266
1267 int EVP_CIPHER_CTX_set_params(EVP_CIPHER_CTX *ctx, const OSSL_PARAM params[])
1268 {
1269     int r = 0;
1270     const OSSL_PARAM *p;
1271
1272     if (ctx->cipher != NULL && ctx->cipher->set_ctx_params != NULL) {
1273         r = ctx->cipher->set_ctx_params(ctx->algctx, params);
1274         if (r > 0) {
1275             p = OSSL_PARAM_locate_const(params, OSSL_CIPHER_PARAM_KEYLEN);
1276             if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->key_len)) {
1277                 r = 0;
1278                 ctx->key_len = -1;
1279             }
1280         }
1281         if (r > 0) {
1282             p = OSSL_PARAM_locate_const(params, OSSL_CIPHER_PARAM_IVLEN);
1283             if (p != NULL && !OSSL_PARAM_get_int(p, &ctx->iv_len)) {
1284                 r = 0;
1285                 ctx->iv_len = -1;
1286             }
1287         }
1288     }
1289     return r;
1290 }
1291
1292 int EVP_CIPHER_CTX_get_params(EVP_CIPHER_CTX *ctx, OSSL_PARAM params[])
1293 {
1294     if (ctx->cipher != NULL && ctx->cipher->get_ctx_params != NULL)
1295         return ctx->cipher->get_ctx_params(ctx->algctx, params);
1296     return 0;
1297 }
1298
1299 const OSSL_PARAM *EVP_CIPHER_gettable_params(const EVP_CIPHER *cipher)
1300 {
1301     if (cipher != NULL && cipher->gettable_params != NULL)
1302         return cipher->gettable_params(
1303                    ossl_provider_ctx(EVP_CIPHER_get0_provider(cipher)));
1304     return NULL;
1305 }
1306
1307 const OSSL_PARAM *EVP_CIPHER_settable_ctx_params(const EVP_CIPHER *cipher)
1308 {
1309     void *provctx;
1310
1311     if (cipher != NULL && cipher->settable_ctx_params != NULL) {
1312         provctx = ossl_provider_ctx(EVP_CIPHER_get0_provider(cipher));
1313         return cipher->settable_ctx_params(NULL, provctx);
1314     }
1315     return NULL;
1316 }
1317
1318 const OSSL_PARAM *EVP_CIPHER_gettable_ctx_params(const EVP_CIPHER *cipher)
1319 {
1320     void *provctx;
1321
1322     if (cipher != NULL && cipher->gettable_ctx_params != NULL) {
1323         provctx = ossl_provider_ctx(EVP_CIPHER_get0_provider(cipher));
1324         return cipher->gettable_ctx_params(NULL, provctx);
1325     }
1326     return NULL;
1327 }
1328
1329 const OSSL_PARAM *EVP_CIPHER_CTX_settable_params(EVP_CIPHER_CTX *cctx)
1330 {
1331     void *alg;
1332
1333     if (cctx != NULL && cctx->cipher->settable_ctx_params != NULL) {
1334         alg = ossl_provider_ctx(EVP_CIPHER_get0_provider(cctx->cipher));
1335         return cctx->cipher->settable_ctx_params(cctx->algctx, alg);
1336     }
1337     return NULL;
1338 }
1339
1340 const OSSL_PARAM *EVP_CIPHER_CTX_gettable_params(EVP_CIPHER_CTX *cctx)
1341 {
1342     void *provctx;
1343
1344     if (cctx != NULL && cctx->cipher->gettable_ctx_params != NULL) {
1345         provctx = ossl_provider_ctx(EVP_CIPHER_get0_provider(cctx->cipher));
1346         return cctx->cipher->gettable_ctx_params(cctx->algctx, provctx);
1347     }
1348     return NULL;
1349 }
1350
1351 #ifndef FIPS_MODULE
1352 static OSSL_LIB_CTX *EVP_CIPHER_CTX_get_libctx(EVP_CIPHER_CTX *ctx)
1353 {
1354     const EVP_CIPHER *cipher = ctx->cipher;
1355     const OSSL_PROVIDER *prov;
1356
1357     if (cipher == NULL)
1358         return NULL;
1359
1360     prov = EVP_CIPHER_get0_provider(cipher);
1361     return ossl_provider_libctx(prov);
1362 }
1363 #endif
1364
1365 int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
1366 {
1367     if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
1368         return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
1369
1370 #ifdef FIPS_MODULE
1371     return 0;
1372 #else
1373     {
1374         int kl;
1375         OSSL_LIB_CTX *libctx = EVP_CIPHER_CTX_get_libctx(ctx);
1376
1377         kl = EVP_CIPHER_CTX_get_key_length(ctx);
1378         if (kl <= 0 || RAND_priv_bytes_ex(libctx, key, kl, 0) <= 0)
1379             return 0;
1380         return 1;
1381     }
1382 #endif /* FIPS_MODULE */
1383 }
1384
1385 EVP_CIPHER_CTX *EVP_CIPHER_CTX_dup(const EVP_CIPHER_CTX *in)
1386 {
1387     EVP_CIPHER_CTX *out = EVP_CIPHER_CTX_new();
1388
1389     if (out != NULL && !EVP_CIPHER_CTX_copy(out, in)) {
1390         EVP_CIPHER_CTX_free(out);
1391         out = NULL;
1392     }
1393     return out;
1394 }
1395
1396 int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
1397 {
1398     if ((in == NULL) || (in->cipher == NULL)) {
1399         ERR_raise(ERR_LIB_EVP, EVP_R_INPUT_NOT_INITIALIZED);
1400         return 0;
1401     }
1402
1403     if (in->cipher->prov == NULL)
1404         goto legacy;
1405
1406     if (in->cipher->dupctx == NULL) {
1407         ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX);
1408         return 0;
1409     }
1410
1411     EVP_CIPHER_CTX_reset(out);
1412
1413     *out = *in;
1414     out->algctx = NULL;
1415
1416     if (in->fetched_cipher != NULL && !EVP_CIPHER_up_ref(in->fetched_cipher)) {
1417         out->fetched_cipher = NULL;
1418         return 0;
1419     }
1420
1421     out->algctx = in->cipher->dupctx(in->algctx);
1422     if (out->algctx == NULL) {
1423         ERR_raise(ERR_LIB_EVP, EVP_R_NOT_ABLE_TO_COPY_CTX);
1424         return 0;
1425     }
1426
1427     return 1;
1428
1429     /* Code below to be removed when legacy support is dropped. */
1430  legacy:
1431
1432 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
1433     /* Make sure it's safe to copy a cipher context using an ENGINE */
1434     if (in->engine && !ENGINE_init(in->engine)) {
1435         ERR_raise(ERR_LIB_EVP, ERR_R_ENGINE_LIB);
1436         return 0;
1437     }
1438 #endif
1439
1440     EVP_CIPHER_CTX_reset(out);
1441     memcpy(out, in, sizeof(*out));
1442
1443     if (in->cipher_data && in->cipher->ctx_size) {
1444         out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
1445         if (out->cipher_data == NULL) {
1446             out->cipher = NULL;
1447             ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
1448             return 0;
1449         }
1450         memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
1451     }
1452
1453     if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
1454         if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) {
1455             out->cipher = NULL;
1456             ERR_raise(ERR_LIB_EVP, EVP_R_INITIALIZATION_ERROR);
1457             return 0;
1458         }
1459     return 1;
1460 }
1461
1462 EVP_CIPHER *evp_cipher_new(void)
1463 {
1464     EVP_CIPHER *cipher = OPENSSL_zalloc(sizeof(EVP_CIPHER));
1465
1466     if (cipher != NULL) {
1467         cipher->lock = CRYPTO_THREAD_lock_new();
1468         if (cipher->lock == NULL) {
1469             OPENSSL_free(cipher);
1470             return NULL;
1471         }
1472         cipher->refcnt = 1;
1473     }
1474     return cipher;
1475 }
1476
1477 /*
1478  * FIPS module note: since internal fetches will be entirely
1479  * provider based, we know that none of its code depends on legacy
1480  * NIDs or any functionality that use them.
1481  */
1482 #ifndef FIPS_MODULE
1483 /* After removal of legacy support get rid of the need for legacy NIDs */
1484 static void set_legacy_nid(const char *name, void *vlegacy_nid)
1485 {
1486     int nid;
1487     int *legacy_nid = vlegacy_nid;
1488     /*
1489      * We use lowest level function to get the associated method, because
1490      * higher level functions such as EVP_get_cipherbyname() have changed
1491      * to look at providers too.
1492      */
1493     const void *legacy_method = OBJ_NAME_get(name, OBJ_NAME_TYPE_CIPHER_METH);
1494
1495     if (*legacy_nid == -1)       /* We found a clash already */
1496         return;
1497     if (legacy_method == NULL)
1498         return;
1499     nid = EVP_CIPHER_get_nid(legacy_method);
1500     if (*legacy_nid != NID_undef && *legacy_nid != nid) {
1501         *legacy_nid = -1;
1502         return;
1503     }
1504     *legacy_nid = nid;
1505 }
1506 #endif
1507
1508 static void *evp_cipher_from_algorithm(const int name_id,
1509                                        const OSSL_ALGORITHM *algodef,
1510                                        OSSL_PROVIDER *prov)
1511 {
1512     const OSSL_DISPATCH *fns = algodef->implementation;
1513     EVP_CIPHER *cipher = NULL;
1514     int fnciphcnt = 0, fnctxcnt = 0;
1515
1516     if ((cipher = evp_cipher_new()) == NULL) {
1517         ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
1518         return NULL;
1519     }
1520
1521 #ifndef FIPS_MODULE
1522     cipher->nid = NID_undef;
1523     if (!evp_names_do_all(prov, name_id, set_legacy_nid, &cipher->nid)
1524             || cipher->nid == -1) {
1525         ERR_raise(ERR_LIB_EVP, ERR_R_INTERNAL_ERROR);
1526         EVP_CIPHER_free(cipher);
1527         return NULL;
1528     }
1529 #endif
1530
1531     cipher->name_id = name_id;
1532     if ((cipher->type_name = ossl_algorithm_get1_first_name(algodef)) == NULL) {
1533         EVP_CIPHER_free(cipher);
1534         return NULL;
1535     }
1536     cipher->description = algodef->algorithm_description;
1537
1538     for (; fns->function_id != 0; fns++) {
1539         switch (fns->function_id) {
1540         case OSSL_FUNC_CIPHER_NEWCTX:
1541             if (cipher->newctx != NULL)
1542                 break;
1543             cipher->newctx = OSSL_FUNC_cipher_newctx(fns);
1544             fnctxcnt++;
1545             break;
1546         case OSSL_FUNC_CIPHER_ENCRYPT_INIT:
1547             if (cipher->einit != NULL)
1548                 break;
1549             cipher->einit = OSSL_FUNC_cipher_encrypt_init(fns);
1550             fnciphcnt++;
1551             break;
1552         case OSSL_FUNC_CIPHER_DECRYPT_INIT:
1553             if (cipher->dinit != NULL)
1554                 break;
1555             cipher->dinit = OSSL_FUNC_cipher_decrypt_init(fns);
1556             fnciphcnt++;
1557             break;
1558         case OSSL_FUNC_CIPHER_UPDATE:
1559             if (cipher->cupdate != NULL)
1560                 break;
1561             cipher->cupdate = OSSL_FUNC_cipher_update(fns);
1562             fnciphcnt++;
1563             break;
1564         case OSSL_FUNC_CIPHER_FINAL:
1565             if (cipher->cfinal != NULL)
1566                 break;
1567             cipher->cfinal = OSSL_FUNC_cipher_final(fns);
1568             fnciphcnt++;
1569             break;
1570         case OSSL_FUNC_CIPHER_CIPHER:
1571             if (cipher->ccipher != NULL)
1572                 break;
1573             cipher->ccipher = OSSL_FUNC_cipher_cipher(fns);
1574             break;
1575         case OSSL_FUNC_CIPHER_FREECTX:
1576             if (cipher->freectx != NULL)
1577                 break;
1578             cipher->freectx = OSSL_FUNC_cipher_freectx(fns);
1579             fnctxcnt++;
1580             break;
1581         case OSSL_FUNC_CIPHER_DUPCTX:
1582             if (cipher->dupctx != NULL)
1583                 break;
1584             cipher->dupctx = OSSL_FUNC_cipher_dupctx(fns);
1585             break;
1586         case OSSL_FUNC_CIPHER_GET_PARAMS:
1587             if (cipher->get_params != NULL)
1588                 break;
1589             cipher->get_params = OSSL_FUNC_cipher_get_params(fns);
1590             break;
1591         case OSSL_FUNC_CIPHER_GET_CTX_PARAMS:
1592             if (cipher->get_ctx_params != NULL)
1593                 break;
1594             cipher->get_ctx_params = OSSL_FUNC_cipher_get_ctx_params(fns);
1595             break;
1596         case OSSL_FUNC_CIPHER_SET_CTX_PARAMS:
1597             if (cipher->set_ctx_params != NULL)
1598                 break;
1599             cipher->set_ctx_params = OSSL_FUNC_cipher_set_ctx_params(fns);
1600             break;
1601         case OSSL_FUNC_CIPHER_GETTABLE_PARAMS:
1602             if (cipher->gettable_params != NULL)
1603                 break;
1604             cipher->gettable_params = OSSL_FUNC_cipher_gettable_params(fns);
1605             break;
1606         case OSSL_FUNC_CIPHER_GETTABLE_CTX_PARAMS:
1607             if (cipher->gettable_ctx_params != NULL)
1608                 break;
1609             cipher->gettable_ctx_params =
1610                 OSSL_FUNC_cipher_gettable_ctx_params(fns);
1611             break;
1612         case OSSL_FUNC_CIPHER_SETTABLE_CTX_PARAMS:
1613             if (cipher->settable_ctx_params != NULL)
1614                 break;
1615             cipher->settable_ctx_params =
1616                 OSSL_FUNC_cipher_settable_ctx_params(fns);
1617             break;
1618         }
1619     }
1620     if ((fnciphcnt != 0 && fnciphcnt != 3 && fnciphcnt != 4)
1621             || (fnciphcnt == 0 && cipher->ccipher == NULL)
1622             || fnctxcnt != 2) {
1623         /*
1624          * In order to be a consistent set of functions we must have at least
1625          * a complete set of "encrypt" functions, or a complete set of "decrypt"
1626          * functions, or a single "cipher" function. In all cases we need both
1627          * the "newctx" and "freectx" functions.
1628          */
1629         EVP_CIPHER_free(cipher);
1630         ERR_raise(ERR_LIB_EVP, EVP_R_INVALID_PROVIDER_FUNCTIONS);
1631         return NULL;
1632     }
1633     cipher->prov = prov;
1634     if (prov != NULL)
1635         ossl_provider_up_ref(prov);
1636
1637     if (!evp_cipher_cache_constants(cipher)) {
1638         EVP_CIPHER_free(cipher);
1639         ERR_raise(ERR_LIB_EVP, EVP_R_CACHE_CONSTANTS_FAILED);
1640         cipher = NULL;
1641     }
1642
1643     return cipher;
1644 }
1645
1646 static int evp_cipher_up_ref(void *cipher)
1647 {
1648     return EVP_CIPHER_up_ref(cipher);
1649 }
1650
1651 static void evp_cipher_free(void *cipher)
1652 {
1653     EVP_CIPHER_free(cipher);
1654 }
1655
1656 EVP_CIPHER *EVP_CIPHER_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
1657                              const char *properties)
1658 {
1659     EVP_CIPHER *cipher =
1660         evp_generic_fetch(ctx, OSSL_OP_CIPHER, algorithm, properties,
1661                           evp_cipher_from_algorithm, evp_cipher_up_ref,
1662                           evp_cipher_free);
1663
1664     return cipher;
1665 }
1666
1667 int EVP_CIPHER_up_ref(EVP_CIPHER *cipher)
1668 {
1669     int ref = 0;
1670
1671     if (cipher->origin == EVP_ORIG_DYNAMIC)
1672         CRYPTO_UP_REF(&cipher->refcnt, &ref, cipher->lock);
1673     return 1;
1674 }
1675
1676 void evp_cipher_free_int(EVP_CIPHER *cipher)
1677 {
1678     OPENSSL_free(cipher->type_name);
1679     ossl_provider_free(cipher->prov);
1680     CRYPTO_THREAD_lock_free(cipher->lock);
1681     OPENSSL_free(cipher);
1682 }
1683
1684 void EVP_CIPHER_free(EVP_CIPHER *cipher)
1685 {
1686     int i;
1687
1688     if (cipher == NULL || cipher->origin != EVP_ORIG_DYNAMIC)
1689         return;
1690
1691     CRYPTO_DOWN_REF(&cipher->refcnt, &i, cipher->lock);
1692     if (i > 0)
1693         return;
1694     evp_cipher_free_int(cipher);
1695 }
1696
1697 void EVP_CIPHER_do_all_provided(OSSL_LIB_CTX *libctx,
1698                                 void (*fn)(EVP_CIPHER *mac, void *arg),
1699                                 void *arg)
1700 {
1701     evp_generic_do_all(libctx, OSSL_OP_CIPHER,
1702                        (void (*)(void *, void *))fn, arg,
1703                        evp_cipher_from_algorithm, evp_cipher_up_ref,
1704                        evp_cipher_free);
1705 }