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