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