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