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