Implement AES CTR ciphers in the default provider
[openssl.git] / crypto / evp / evp_enc.c
1 /*
2  * Copyright 1995-2018 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_meth_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 #ifndef OPENSSL_NO_ENGINE
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     EVP_CIPHER *provciph = NULL;
85     ENGINE *tmpimpl = NULL;
86     const EVP_CIPHER *tmpcipher;
87
88     /*
89      * enc == 1 means we are encrypting.
90      * enc == 0 means we are decrypting.
91      * enc == -1 means, use the previously initialised value for encrypt/decrypt
92      */
93     if (enc == -1) {
94         enc = ctx->encrypt;
95     } else {
96         if (enc)
97             enc = 1;
98         ctx->encrypt = enc;
99     }
100
101     if (cipher == NULL && ctx->cipher == NULL) {
102         EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET);
103         return 0;
104     }
105
106     /* TODO(3.0): Legacy work around code below. Remove this */
107
108 #ifndef OPENSSL_NO_ENGINE
109     /*
110      * Whether it's nice or not, "Inits" can be used on "Final"'d contexts so
111      * this context may already have an ENGINE! Try to avoid releasing the
112      * previous handle, re-querying for an ENGINE, and having a
113      * reinitialisation, when it may all be unnecessary.
114      */
115     if (ctx->engine && ctx->cipher
116         && (cipher == NULL || cipher->nid == ctx->cipher->nid))
117         goto skip_to_init;
118
119     if (cipher != NULL && impl == NULL) {
120          /* Ask if an ENGINE is reserved for this job */
121         tmpimpl = ENGINE_get_cipher_engine(cipher->nid);
122     }
123 #endif
124
125     /*
126      * If there are engines involved then we should use legacy handling for now.
127      */
128     if (ctx->engine != NULL
129             || impl != NULL
130             || tmpimpl != NULL) {
131         if (ctx->cipher == ctx->fetched_cipher)
132             ctx->cipher = NULL;
133         EVP_CIPHER_meth_free(ctx->fetched_cipher);
134         ctx->fetched_cipher = NULL;
135         goto legacy;
136     }
137
138     tmpcipher = (cipher == NULL) ? ctx->cipher : cipher;
139
140     if (tmpcipher->prov == NULL) {
141         switch(tmpcipher->nid) {
142         case NID_aes_256_ecb:
143         case NID_aes_192_ecb:
144         case NID_aes_128_ecb:
145         case NID_aes_256_cbc:
146         case NID_aes_192_cbc:
147         case NID_aes_128_cbc:
148         case NID_aes_256_ofb128:
149         case NID_aes_192_ofb128:
150         case NID_aes_128_ofb128:
151         case NID_aes_256_cfb128:
152         case NID_aes_192_cfb128:
153         case NID_aes_128_cfb128:
154         case NID_aes_256_cfb1:
155         case NID_aes_192_cfb1:
156         case NID_aes_128_cfb1:
157         case NID_aes_256_cfb8:
158         case NID_aes_192_cfb8:
159         case NID_aes_128_cfb8:
160         case NID_aes_256_ctr:
161         case NID_aes_192_ctr:
162         case NID_aes_128_ctr:
163             break;
164         default:
165             goto legacy;
166         }
167     }
168
169     /*
170      * Ensure a context left lying around from last time is cleared
171      * (legacy code)
172      */
173     if (cipher != NULL && ctx->cipher != NULL) {
174         OPENSSL_clear_free(ctx->cipher_data, ctx->cipher->ctx_size);
175         ctx->cipher_data = NULL;
176     }
177
178
179     /* TODO(3.0): Start of non-legacy code below */
180
181     /* Ensure a context left lying around from last time is cleared */
182     if (cipher != NULL && ctx->cipher != NULL) {
183         unsigned long flags = ctx->flags;
184
185         EVP_CIPHER_CTX_reset(ctx);
186         /* Restore encrypt and flags */
187         ctx->encrypt = enc;
188         ctx->flags = flags;
189     }
190
191     if (cipher != NULL)
192         ctx->cipher = cipher;
193     else
194         cipher = ctx->cipher;
195
196     if (cipher->prov == NULL) {
197         provciph = EVP_CIPHER_fetch(NULL, OBJ_nid2sn(cipher->nid), "");
198         if (provciph == NULL) {
199             EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
200             return 0;
201         }
202         cipher = provciph;
203         EVP_CIPHER_meth_free(ctx->fetched_cipher);
204         ctx->fetched_cipher = provciph;
205     }
206
207     ctx->cipher = cipher;
208     if (ctx->provctx == NULL) {
209         ctx->provctx = ctx->cipher->newctx();
210         if (ctx->provctx == NULL) {
211             EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
212             return 0;
213         }
214     }
215
216     if ((ctx->flags & EVP_CIPH_NO_PADDING) != 0) {
217         /*
218          * If this ctx was already set up for no padding then we need to tell
219          * the new cipher about it.
220          */
221         if (!EVP_CIPHER_CTX_set_padding(ctx, 0))
222             return 0;
223     }
224
225     switch (EVP_CIPHER_mode(ctx->cipher)) {
226     case EVP_CIPH_CFB_MODE:
227     case EVP_CIPH_OFB_MODE:
228     case EVP_CIPH_CBC_MODE:
229         /* For these modes we remember the original IV for later use */
230         if (!ossl_assert(EVP_CIPHER_CTX_iv_length(ctx) <= (int)sizeof(ctx->oiv))) {
231             EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
232             return 0;
233         }
234         if (iv != NULL)
235             memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
236     }
237
238     if (enc) {
239         if (ctx->cipher->einit == NULL) {
240             EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
241             return 0;
242         }
243
244         return ctx->cipher->einit(ctx->provctx, key, iv);
245     }
246
247     if (ctx->cipher->dinit == NULL) {
248         EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
249         return 0;
250     }
251
252     return ctx->cipher->dinit(ctx->provctx, key, iv);
253
254     /* TODO(3.0): Remove legacy code below */
255  legacy:
256
257     if (cipher != NULL) {
258         /*
259          * Ensure a context left lying around from last time is cleared (we
260          * previously attempted to avoid this if the same ENGINE and
261          * EVP_CIPHER could be used).
262          */
263         if (ctx->cipher) {
264             unsigned long flags = ctx->flags;
265             EVP_CIPHER_CTX_reset(ctx);
266             /* Restore encrypt and flags */
267             ctx->encrypt = enc;
268             ctx->flags = flags;
269         }
270 #ifndef OPENSSL_NO_ENGINE
271         if (impl != NULL) {
272             if (!ENGINE_init(impl)) {
273                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
274                 return 0;
275             }
276         } else {
277             impl = tmpimpl;
278         }
279         if (impl != NULL) {
280             /* There's an ENGINE for this job ... (apparently) */
281             const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid);
282
283             if (c == NULL) {
284                 /*
285                  * One positive side-effect of US's export control history,
286                  * is that we should at least be able to avoid using US
287                  * misspellings of "initialisation"?
288                  */
289                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
290                 return 0;
291             }
292             /* We'll use the ENGINE's private cipher definition */
293             cipher = c;
294             /*
295              * Store the ENGINE functional reference so we know 'cipher' came
296              * from an ENGINE and we need to release it when done.
297              */
298             ctx->engine = impl;
299         } else {
300             ctx->engine = NULL;
301         }
302 #endif
303
304         ctx->cipher = cipher;
305         if (ctx->cipher->ctx_size) {
306             ctx->cipher_data = OPENSSL_zalloc(ctx->cipher->ctx_size);
307             if (ctx->cipher_data == NULL) {
308                 ctx->cipher = NULL;
309                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE);
310                 return 0;
311             }
312         } else {
313             ctx->cipher_data = NULL;
314         }
315         ctx->key_len = cipher->key_len;
316         /* Preserve wrap enable flag, zero everything else */
317         ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW;
318         if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) {
319             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) {
320                 ctx->cipher = NULL;
321                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
322                 return 0;
323             }
324         }
325     }
326 #ifndef OPENSSL_NO_ENGINE
327  skip_to_init:
328 #endif
329     /* we assume block size is a power of 2 in *cryptUpdate */
330     OPENSSL_assert(ctx->cipher->block_size == 1
331                    || ctx->cipher->block_size == 8
332                    || ctx->cipher->block_size == 16);
333
334     if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW)
335         && EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_WRAP_MODE) {
336         EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_WRAP_MODE_NOT_ALLOWED);
337         return 0;
338     }
339
340     if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_CUSTOM_IV)) {
341         switch (EVP_CIPHER_CTX_mode(ctx)) {
342
343         case EVP_CIPH_STREAM_CIPHER:
344         case EVP_CIPH_ECB_MODE:
345             break;
346
347         case EVP_CIPH_CFB_MODE:
348         case EVP_CIPH_OFB_MODE:
349
350             ctx->num = 0;
351             /* fall-through */
352
353         case EVP_CIPH_CBC_MODE:
354
355             OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <=
356                            (int)sizeof(ctx->iv));
357             if (iv)
358                 memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
359             memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
360             break;
361
362         case EVP_CIPH_CTR_MODE:
363             ctx->num = 0;
364             /* Don't reuse IV for CTR mode */
365             if (iv)
366                 memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
367             break;
368
369         default:
370             return 0;
371         }
372     }
373
374     if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
375         if (!ctx->cipher->init(ctx, key, iv, enc))
376             return 0;
377     }
378     ctx->buf_len = 0;
379     ctx->final_used = 0;
380     ctx->block_mask = ctx->cipher->block_size - 1;
381     return 1;
382 }
383
384 int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
385                      const unsigned char *in, int inl)
386 {
387     if (ctx->encrypt)
388         return EVP_EncryptUpdate(ctx, out, outl, in, inl);
389     else
390         return EVP_DecryptUpdate(ctx, out, outl, in, inl);
391 }
392
393 int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
394 {
395     if (ctx->encrypt)
396         return EVP_EncryptFinal_ex(ctx, out, outl);
397     else
398         return EVP_DecryptFinal_ex(ctx, out, outl);
399 }
400
401 int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
402 {
403     if (ctx->encrypt)
404         return EVP_EncryptFinal(ctx, out, outl);
405     else
406         return EVP_DecryptFinal(ctx, out, outl);
407 }
408
409 int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
410                     const unsigned char *key, const unsigned char *iv)
411 {
412     return EVP_CipherInit(ctx, cipher, key, iv, 1);
413 }
414
415 int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
416                        ENGINE *impl, const unsigned char *key,
417                        const unsigned char *iv)
418 {
419     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
420 }
421
422 int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
423                     const unsigned char *key, const unsigned char *iv)
424 {
425     return EVP_CipherInit(ctx, cipher, key, iv, 0);
426 }
427
428 int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
429                        ENGINE *impl, const unsigned char *key,
430                        const unsigned char *iv)
431 {
432     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
433 }
434
435 /*
436  * According to the letter of standard difference between pointers
437  * is specified to be valid only within same object. This makes
438  * it formally challenging to determine if input and output buffers
439  * are not partially overlapping with standard pointer arithmetic.
440  */
441 #ifdef PTRDIFF_T
442 # undef PTRDIFF_T
443 #endif
444 #if defined(OPENSSL_SYS_VMS) && __INITIAL_POINTER_SIZE==64
445 /*
446  * Then we have VMS that distinguishes itself by adhering to
447  * sizeof(size_t)==4 even in 64-bit builds, which means that
448  * difference between two pointers might be truncated to 32 bits.
449  * In the context one can even wonder how comparison for
450  * equality is implemented. To be on the safe side we adhere to
451  * PTRDIFF_T even for comparison for equality.
452  */
453 # define PTRDIFF_T uint64_t
454 #else
455 # define PTRDIFF_T size_t
456 #endif
457
458 int is_partially_overlapping(const void *ptr1, const void *ptr2, int len)
459 {
460     PTRDIFF_T diff = (PTRDIFF_T)ptr1-(PTRDIFF_T)ptr2;
461     /*
462      * Check for partially overlapping buffers. [Binary logical
463      * operations are used instead of boolean to minimize number
464      * of conditional branches.]
465      */
466     int overlapped = (len > 0) & (diff != 0) & ((diff < (PTRDIFF_T)len) |
467                                                 (diff > (0 - (PTRDIFF_T)len)));
468
469     return overlapped;
470 }
471
472 static int evp_EncryptDecryptUpdate(EVP_CIPHER_CTX *ctx,
473                                     unsigned char *out, int *outl,
474                                     const unsigned char *in, int inl)
475 {
476     int i, j, bl, cmpl = inl;
477
478     if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS))
479         cmpl = (cmpl + 7) / 8;
480
481     bl = ctx->cipher->block_size;
482
483     if (inl <= 0) {
484         *outl = 0;
485         return inl == 0;
486     }
487
488     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
489         /* If block size > 1 then the cipher will have to do this check */
490         if (bl == 1 && is_partially_overlapping(out, in, cmpl)) {
491             EVPerr(EVP_F_EVP_ENCRYPTDECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);
492             return 0;
493         }
494
495         i = ctx->cipher->do_cipher(ctx, out, in, inl);
496         if (i < 0)
497             return 0;
498         else
499             *outl = i;
500         return 1;
501     }
502
503     if (is_partially_overlapping(out + ctx->buf_len, in, cmpl)) {
504         EVPerr(EVP_F_EVP_ENCRYPTDECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);
505         return 0;
506     }
507
508     if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
509         if (ctx->cipher->do_cipher(ctx, out, in, inl)) {
510             *outl = inl;
511             return 1;
512         } else {
513             *outl = 0;
514             return 0;
515         }
516     }
517     i = ctx->buf_len;
518     OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
519     if (i != 0) {
520         if (bl - i > inl) {
521             memcpy(&(ctx->buf[i]), in, inl);
522             ctx->buf_len += inl;
523             *outl = 0;
524             return 1;
525         } else {
526             j = bl - i;
527             memcpy(&(ctx->buf[i]), in, j);
528             inl -= j;
529             in += j;
530             if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl))
531                 return 0;
532             out += bl;
533             *outl = bl;
534         }
535     } else
536         *outl = 0;
537     i = inl & (bl - 1);
538     inl -= i;
539     if (inl > 0) {
540         if (!ctx->cipher->do_cipher(ctx, out, in, inl))
541             return 0;
542         *outl += inl;
543     }
544
545     if (i != 0)
546         memcpy(ctx->buf, &(in[inl]), i);
547     ctx->buf_len = i;
548     return 1;
549 }
550
551
552 int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
553                       const unsigned char *in, int inl)
554 {
555     int ret;
556     size_t soutl;
557
558     /* Prevent accidental use of decryption context when encrypting */
559     if (!ctx->encrypt) {
560         EVPerr(EVP_F_EVP_ENCRYPTUPDATE, EVP_R_INVALID_OPERATION);
561         return 0;
562     }
563
564     if (ctx->cipher == NULL || ctx->cipher->prov == NULL)
565         goto legacy;
566
567     if (ctx->cipher->cupdate == NULL) {
568         EVPerr(EVP_F_EVP_ENCRYPTUPDATE, EVP_R_UPDATE_ERROR);
569         return 0;
570     }
571     ret = ctx->cipher->cupdate(ctx->provctx, out, &soutl, in, (size_t)inl);
572
573     if (soutl > INT_MAX) {
574         EVPerr(EVP_F_EVP_ENCRYPTUPDATE, EVP_R_UPDATE_ERROR);
575         return 0;
576     }
577     *outl = soutl;
578     return ret;
579
580     /* TODO(3.0): Remove legacy code below */
581  legacy:
582
583     return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl);
584 }
585
586 int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
587 {
588     int ret;
589     ret = EVP_EncryptFinal_ex(ctx, out, outl);
590     return ret;
591 }
592
593 int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
594 {
595     int n, ret;
596     unsigned int i, b, bl;
597     size_t soutl;
598
599     /* Prevent accidental use of decryption context when encrypting */
600     if (!ctx->encrypt) {
601         EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX, EVP_R_INVALID_OPERATION);
602         return 0;
603     }
604
605     if (ctx->cipher == NULL || ctx->cipher->prov == NULL)
606         goto legacy;
607
608     if (ctx->cipher->cfinal == NULL) {
609         EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX, EVP_R_FINAL_ERROR);
610         return 0;
611     }
612
613     ret = ctx->cipher->cfinal(ctx->provctx, out, &soutl);
614
615     if (soutl > INT_MAX) {
616         EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX, EVP_R_FINAL_ERROR);
617         return 0;
618     }
619     *outl = soutl;
620
621     return ret;
622
623     /* TODO(3.0): Remove legacy code below */
624  legacy:
625
626     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
627         ret = ctx->cipher->do_cipher(ctx, out, NULL, 0);
628         if (ret < 0)
629             return 0;
630         else
631             *outl = ret;
632         return 1;
633     }
634
635     b = ctx->cipher->block_size;
636     OPENSSL_assert(b <= sizeof(ctx->buf));
637     if (b == 1) {
638         *outl = 0;
639         return 1;
640     }
641     bl = ctx->buf_len;
642     if (ctx->flags & EVP_CIPH_NO_PADDING) {
643         if (bl) {
644             EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX,
645                    EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
646             return 0;
647         }
648         *outl = 0;
649         return 1;
650     }
651
652     n = b - bl;
653     for (i = bl; i < b; i++)
654         ctx->buf[i] = n;
655     ret = ctx->cipher->do_cipher(ctx, out, ctx->buf, b);
656
657     if (ret)
658         *outl = b;
659
660     return ret;
661 }
662
663 int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
664                       const unsigned char *in, int inl)
665 {
666     int fix_len, cmpl = inl, ret;
667     unsigned int b;
668     size_t soutl;
669
670     /* Prevent accidental use of encryption context when decrypting */
671     if (ctx->encrypt) {
672         EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_INVALID_OPERATION);
673         return 0;
674     }
675
676     if (ctx->cipher == NULL || ctx->cipher->prov == NULL)
677         goto legacy;
678
679     if (ctx->cipher->cupdate == NULL) {
680         EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_UPDATE_ERROR);
681         return 0;
682     }
683     ret = ctx->cipher->cupdate(ctx->provctx, out, &soutl, in, (size_t)inl);
684
685     if (ret) {
686         if (soutl > INT_MAX) {
687             EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_UPDATE_ERROR);
688             return 0;
689         }
690         *outl = soutl;
691     }
692
693     return ret;
694
695     /* TODO(3.0): Remove legacy code below */
696  legacy:
697
698     b = ctx->cipher->block_size;
699
700     if (EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS))
701         cmpl = (cmpl + 7) / 8;
702
703     if (inl <= 0) {
704         *outl = 0;
705         return inl == 0;
706     }
707
708     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
709         if (b == 1 && is_partially_overlapping(out, in, cmpl)) {
710             EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);
711             return 0;
712         }
713
714         fix_len = ctx->cipher->do_cipher(ctx, out, in, inl);
715         if (fix_len < 0) {
716             *outl = 0;
717             return 0;
718         } else
719             *outl = fix_len;
720         return 1;
721     }
722
723     if (ctx->flags & EVP_CIPH_NO_PADDING)
724         return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl);
725
726     OPENSSL_assert(b <= sizeof(ctx->final));
727
728     if (ctx->final_used) {
729         /* see comment about PTRDIFF_T comparison above */
730         if (((PTRDIFF_T)out == (PTRDIFF_T)in)
731             || is_partially_overlapping(out, in, b)) {
732             EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);
733             return 0;
734         }
735         memcpy(out, ctx->final, b);
736         out += b;
737         fix_len = 1;
738     } else
739         fix_len = 0;
740
741     if (!evp_EncryptDecryptUpdate(ctx, out, outl, in, inl))
742         return 0;
743
744     /*
745      * if we have 'decrypted' a multiple of block size, make sure we have a
746      * copy of this last block
747      */
748     if (b > 1 && !ctx->buf_len) {
749         *outl -= b;
750         ctx->final_used = 1;
751         memcpy(ctx->final, &out[*outl], b);
752     } else
753         ctx->final_used = 0;
754
755     if (fix_len)
756         *outl += b;
757
758     return 1;
759 }
760
761 int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
762 {
763     int ret;
764     ret = EVP_DecryptFinal_ex(ctx, out, outl);
765     return ret;
766 }
767
768 int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
769 {
770     int i, n;
771     unsigned int b;
772     size_t soutl;
773     int ret;
774
775     /* Prevent accidental use of encryption context when decrypting */
776     if (ctx->encrypt) {
777         EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_INVALID_OPERATION);
778         return 0;
779     }
780
781     if (ctx->cipher == NULL || ctx->cipher->prov == NULL)
782         goto legacy;
783
784     if (ctx->cipher->cfinal == NULL) {
785         EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_FINAL_ERROR);
786         return 0;
787     }
788
789     ret = ctx->cipher->cfinal(ctx->provctx, out, &soutl);
790
791     if (ret) {
792         if (soutl > INT_MAX) {
793             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_FINAL_ERROR);
794             return 0;
795         }
796         *outl = soutl;
797     }
798
799     return ret;
800
801     /* TODO(3.0): Remove legacy code below */
802  legacy:
803
804     *outl = 0;
805
806     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
807         i = ctx->cipher->do_cipher(ctx, out, NULL, 0);
808         if (i < 0)
809             return 0;
810         else
811             *outl = i;
812         return 1;
813     }
814
815     b = ctx->cipher->block_size;
816     if (ctx->flags & EVP_CIPH_NO_PADDING) {
817         if (ctx->buf_len) {
818             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX,
819                    EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
820             return 0;
821         }
822         *outl = 0;
823         return 1;
824     }
825     if (b > 1) {
826         if (ctx->buf_len || !ctx->final_used) {
827             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_WRONG_FINAL_BLOCK_LENGTH);
828             return 0;
829         }
830         OPENSSL_assert(b <= sizeof(ctx->final));
831
832         /*
833          * The following assumes that the ciphertext has been authenticated.
834          * Otherwise it provides a padding oracle.
835          */
836         n = ctx->final[b - 1];
837         if (n == 0 || n > (int)b) {
838             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
839             return 0;
840         }
841         for (i = 0; i < n; i++) {
842             if (ctx->final[--b] != n) {
843                 EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
844                 return 0;
845             }
846         }
847         n = ctx->cipher->block_size - n;
848         for (i = 0; i < n; i++)
849             out[i] = ctx->final[i];
850         *outl = n;
851     } else
852         *outl = 0;
853     return 1;
854 }
855
856 int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen)
857 {
858     if (c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH)
859         return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL);
860     if (EVP_CIPHER_CTX_key_length(c) == keylen)
861         return 1;
862     if ((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) {
863         c->key_len = keylen;
864         return 1;
865     }
866     EVPerr(EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH, EVP_R_INVALID_KEY_LENGTH);
867     return 0;
868 }
869
870 int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad)
871 {
872     if (pad)
873         ctx->flags &= ~EVP_CIPH_NO_PADDING;
874     else
875         ctx->flags |= EVP_CIPH_NO_PADDING;
876
877     if (ctx->cipher != NULL && ctx->cipher->prov != NULL) {
878         OSSL_PARAM params[] = {
879             OSSL_PARAM_int(OSSL_CIPHER_PARAM_PADDING, NULL),
880             OSSL_PARAM_END
881         };
882
883         params[0].data = &pad;
884
885         if (ctx->cipher->ctx_set_params == NULL) {
886             EVPerr(EVP_F_EVP_CIPHER_CTX_SET_PADDING, EVP_R_CTRL_NOT_IMPLEMENTED);
887             return 0;
888         }
889
890         if (!ctx->cipher->ctx_set_params(ctx->provctx, params))
891             return 0;
892     }
893
894     return 1;
895 }
896
897 int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
898 {
899     int ret;
900
901     if (!ctx->cipher) {
902         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_NO_CIPHER_SET);
903         return 0;
904     }
905
906     if (!ctx->cipher->ctrl) {
907         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_NOT_IMPLEMENTED);
908         return 0;
909     }
910
911     ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
912     if (ret == -1) {
913         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL,
914                EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
915         return 0;
916     }
917     return ret;
918 }
919
920 int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
921 {
922     if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
923         return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
924     if (RAND_priv_bytes(key, ctx->key_len) <= 0)
925         return 0;
926     return 1;
927 }
928
929 int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
930 {
931     if ((in == NULL) || (in->cipher == NULL)) {
932         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INPUT_NOT_INITIALIZED);
933         return 0;
934     }
935
936     if (in->cipher->prov == NULL)
937         goto legacy;
938
939     if (in->cipher->dupctx == NULL) {
940         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_NOT_ABLE_TO_COPY_CTX);
941         return 0;
942     }
943
944     EVP_CIPHER_CTX_reset(out);
945
946     *out = *in;
947     out->provctx = NULL;
948
949     if (in->fetched_cipher != NULL && !EVP_CIPHER_upref(in->fetched_cipher)) {
950         out->fetched_cipher = NULL;
951         return 0;
952     }
953
954     out->provctx = in->cipher->dupctx(in->provctx);
955     if (out->provctx == NULL) {
956         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_NOT_ABLE_TO_COPY_CTX);
957         return 0;
958     }
959
960     return 1;
961
962     /* TODO(3.0): Remove legacy code below */
963  legacy:
964
965 #ifndef OPENSSL_NO_ENGINE
966     /* Make sure it's safe to copy a cipher context using an ENGINE */
967     if (in->engine && !ENGINE_init(in->engine)) {
968         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_ENGINE_LIB);
969         return 0;
970     }
971 #endif
972
973     EVP_CIPHER_CTX_reset(out);
974     memcpy(out, in, sizeof(*out));
975
976     if (in->cipher_data && in->cipher->ctx_size) {
977         out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
978         if (out->cipher_data == NULL) {
979             out->cipher = NULL;
980             EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_MALLOC_FAILURE);
981             return 0;
982         }
983         memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
984     }
985
986     if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
987         if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) {
988             out->cipher = NULL;
989             EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INITIALIZATION_ERROR);
990             return 0;
991         }
992     return 1;
993 }
994
995 static void *evp_cipher_from_dispatch(int nid, const OSSL_DISPATCH *fns,
996                                       OSSL_PROVIDER *prov)
997 {
998     EVP_CIPHER *cipher = NULL;
999     int fnciphcnt = 0, fnctxcnt = 0;
1000
1001     if ((cipher = EVP_CIPHER_meth_new(nid, 0, 0)) == NULL)
1002         return NULL;
1003
1004     for (; fns->function_id != 0; fns++) {
1005         switch (fns->function_id) {
1006         case OSSL_FUNC_CIPHER_NEWCTX:
1007             if (cipher->newctx != NULL)
1008                 break;
1009             cipher->newctx = OSSL_get_OP_cipher_newctx(fns);
1010             fnctxcnt++;
1011             break;
1012         case OSSL_FUNC_CIPHER_ENCRYPT_INIT:
1013             if (cipher->einit != NULL)
1014                 break;
1015             cipher->einit = OSSL_get_OP_cipher_encrypt_init(fns);
1016             fnciphcnt++;
1017             break;
1018         case OSSL_FUNC_CIPHER_DECRYPT_INIT:
1019             if (cipher->dinit != NULL)
1020                 break;
1021             cipher->dinit = OSSL_get_OP_cipher_decrypt_init(fns);
1022             fnciphcnt++;
1023             break;
1024         case OSSL_FUNC_CIPHER_UPDATE:
1025             if (cipher->cupdate != NULL)
1026                 break;
1027             cipher->cupdate = OSSL_get_OP_cipher_update(fns);
1028             fnciphcnt++;
1029             break;
1030         case OSSL_FUNC_CIPHER_FINAL:
1031             if (cipher->cfinal != NULL)
1032                 break;
1033             cipher->cfinal = OSSL_get_OP_cipher_final(fns);
1034             fnciphcnt++;
1035             break;
1036         case OSSL_FUNC_CIPHER_CIPHER:
1037             if (cipher->ccipher != NULL)
1038                 break;
1039             cipher->ccipher = OSSL_get_OP_cipher_cipher(fns);
1040             break;
1041         case OSSL_FUNC_CIPHER_FREECTX:
1042             if (cipher->freectx != NULL)
1043                 break;
1044             cipher->freectx = OSSL_get_OP_cipher_freectx(fns);
1045             fnctxcnt++;
1046             break;
1047         case OSSL_FUNC_CIPHER_DUPCTX:
1048             if (cipher->dupctx != NULL)
1049                 break;
1050             cipher->dupctx = OSSL_get_OP_cipher_dupctx(fns);
1051             break;
1052         case OSSL_FUNC_CIPHER_KEY_LENGTH:
1053             if (cipher->key_length != NULL)
1054                 break;
1055             cipher->key_length = OSSL_get_OP_cipher_key_length(fns);
1056             break;
1057         case OSSL_FUNC_CIPHER_IV_LENGTH:
1058             if (cipher->iv_length != NULL)
1059                 break;
1060             cipher->iv_length = OSSL_get_OP_cipher_iv_length(fns);
1061             break;
1062         case OSSL_FUNC_CIPHER_BLOCK_SIZE:
1063             if (cipher->blocksize != NULL)
1064                 break;
1065             cipher->blocksize = OSSL_get_OP_cipher_block_size(fns);
1066             break;
1067         case OSSL_FUNC_CIPHER_GET_PARAMS:
1068             if (cipher->get_params != NULL)
1069                 break;
1070             cipher->get_params = OSSL_get_OP_cipher_get_params(fns);
1071             break;
1072         case OSSL_FUNC_CIPHER_CTX_GET_PARAMS:
1073             if (cipher->ctx_get_params != NULL)
1074                 break;
1075             cipher->ctx_get_params = OSSL_get_OP_cipher_ctx_get_params(fns);
1076             break;
1077         case OSSL_FUNC_CIPHER_CTX_SET_PARAMS:
1078             if (cipher->ctx_set_params != NULL)
1079                 break;
1080             cipher->ctx_set_params = OSSL_get_OP_cipher_ctx_set_params(fns);
1081             break;
1082         }
1083     }
1084     if ((fnciphcnt != 0 && fnciphcnt != 3 && fnciphcnt != 4)
1085             || (fnciphcnt == 0 && cipher->ccipher == NULL)
1086             || fnctxcnt != 2) {
1087         /*
1088          * In order to be a consistent set of functions we must have at least
1089          * a complete set of "encrypt" functions, or a complete set of "decrypt"
1090          * functions, or a single "cipher" function. In all cases we need a
1091          * complete set of context management functions
1092          */
1093         EVP_CIPHER_meth_free(cipher);
1094         EVPerr(EVP_F_EVP_CIPHER_FROM_DISPATCH, EVP_R_INVALID_PROVIDER_FUNCTIONS);
1095         return NULL;
1096     }
1097     cipher->prov = prov;
1098     if (prov != NULL)
1099         ossl_provider_upref(prov);
1100
1101     return cipher;
1102 }
1103
1104 static int evp_cipher_upref(void *cipher)
1105 {
1106     return EVP_CIPHER_upref(cipher);
1107 }
1108
1109 static void evp_cipher_free(void *cipher)
1110 {
1111     EVP_CIPHER_meth_free(cipher);
1112 }
1113
1114 static int evp_cipher_nid(void *vcipher)
1115 {
1116     EVP_CIPHER *cipher = vcipher;
1117
1118     return cipher->nid;
1119 }
1120
1121 EVP_CIPHER *EVP_CIPHER_fetch(OPENSSL_CTX *ctx, const char *algorithm,
1122                              const char *properties)
1123 {
1124     return evp_generic_fetch(ctx, OSSL_OP_CIPHER, algorithm, properties,
1125                              evp_cipher_from_dispatch, evp_cipher_upref,
1126                              evp_cipher_free, evp_cipher_nid);
1127 }