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