bce2b5720c945db1c295c8fed6bdf090c6640f57
[openssl.git] / crypto / evp / evp_enc.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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/engine.h>
17 #include "internal/evp_int.h"
18 #include "evp_locl.h"
19
20 int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX *c)
21 {
22     if (c == NULL)
23         return 1;
24     if (c->cipher != NULL) {
25         if (c->cipher->cleanup && !c->cipher->cleanup(c))
26             return 0;
27         /* Cleanse cipher context data */
28         if (c->cipher_data && c->cipher->ctx_size)
29             OPENSSL_cleanse(c->cipher_data, c->cipher->ctx_size);
30     }
31     OPENSSL_free(c->cipher_data);
32 #ifndef OPENSSL_NO_ENGINE
33     ENGINE_finish(c->engine);
34 #endif
35     memset(c, 0, sizeof(*c));
36     return 1;
37 }
38
39 EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void)
40 {
41     return OPENSSL_zalloc(sizeof(EVP_CIPHER_CTX));
42 }
43
44 void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx)
45 {
46     EVP_CIPHER_CTX_reset(ctx);
47     OPENSSL_free(ctx);
48 }
49
50 int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
51                    const unsigned char *key, const unsigned char *iv, int enc)
52 {
53     EVP_CIPHER_CTX_reset(ctx);
54     return EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, enc);
55 }
56
57 int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
58                       ENGINE *impl, const unsigned char *key,
59                       const unsigned char *iv, int enc)
60 {
61     if (enc == -1)
62         enc = ctx->encrypt;
63     else {
64         if (enc)
65             enc = 1;
66         ctx->encrypt = enc;
67     }
68 #ifndef OPENSSL_NO_ENGINE
69     /*
70      * Whether it's nice or not, "Inits" can be used on "Final"'d contexts so
71      * this context may already have an ENGINE! Try to avoid releasing the
72      * previous handle, re-querying for an ENGINE, and having a
73      * reinitialisation, when it may all be unnecessary.
74      */
75     if (ctx->engine && ctx->cipher
76         && (cipher == NULL || cipher->nid == ctx->cipher->nid))
77         goto skip_to_init;
78 #endif
79     if (cipher) {
80         /*
81          * Ensure a context left lying around from last time is cleared (the
82          * previous check attempted to avoid this if the same ENGINE and
83          * EVP_CIPHER could be used).
84          */
85         if (ctx->cipher) {
86             unsigned long flags = ctx->flags;
87             EVP_CIPHER_CTX_reset(ctx);
88             /* Restore encrypt and flags */
89             ctx->encrypt = enc;
90             ctx->flags = flags;
91         }
92 #ifndef OPENSSL_NO_ENGINE
93         if (impl) {
94             if (!ENGINE_init(impl)) {
95                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
96                 return 0;
97             }
98         } else
99             /* Ask if an ENGINE is reserved for this job */
100             impl = ENGINE_get_cipher_engine(cipher->nid);
101         if (impl) {
102             /* There's an ENGINE for this job ... (apparently) */
103             const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid);
104             if (!c) {
105                 /*
106                  * One positive side-effect of US's export control history,
107                  * is that we should at least be able to avoid using US
108                  * misspellings of "initialisation"?
109                  */
110                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
111                 return 0;
112             }
113             /* We'll use the ENGINE's private cipher definition */
114             cipher = c;
115             /*
116              * Store the ENGINE functional reference so we know 'cipher' came
117              * from an ENGINE and we need to release it when done.
118              */
119             ctx->engine = impl;
120         } else
121             ctx->engine = NULL;
122 #endif
123
124         ctx->cipher = cipher;
125         if (ctx->cipher->ctx_size) {
126             ctx->cipher_data = OPENSSL_zalloc(ctx->cipher->ctx_size);
127             if (ctx->cipher_data == NULL) {
128                 ctx->cipher = NULL;
129                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE);
130                 return 0;
131             }
132         } else {
133             ctx->cipher_data = NULL;
134         }
135         ctx->key_len = cipher->key_len;
136         /* Preserve wrap enable flag, zero everything else */
137         ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW;
138         if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) {
139             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) {
140                 ctx->cipher = NULL;
141                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
142                 return 0;
143             }
144         }
145     } else if (!ctx->cipher) {
146         EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET);
147         return 0;
148     }
149 #ifndef OPENSSL_NO_ENGINE
150  skip_to_init:
151 #endif
152     /* we assume block size is a power of 2 in *cryptUpdate */
153     OPENSSL_assert(ctx->cipher->block_size == 1
154                    || ctx->cipher->block_size == 8
155                    || ctx->cipher->block_size == 16);
156
157     if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW)
158         && EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_WRAP_MODE) {
159         EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_WRAP_MODE_NOT_ALLOWED);
160         return 0;
161     }
162
163     if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_CUSTOM_IV)) {
164         switch (EVP_CIPHER_CTX_mode(ctx)) {
165
166         case EVP_CIPH_STREAM_CIPHER:
167         case EVP_CIPH_ECB_MODE:
168             break;
169
170         case EVP_CIPH_CFB_MODE:
171         case EVP_CIPH_OFB_MODE:
172
173             ctx->num = 0;
174             /* fall-through */
175
176         case EVP_CIPH_CBC_MODE:
177
178             OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <=
179                            (int)sizeof(ctx->iv));
180             if (iv)
181                 memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
182             memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
183             break;
184
185         case EVP_CIPH_CTR_MODE:
186             ctx->num = 0;
187             /* Don't reuse IV for CTR mode */
188             if (iv)
189                 memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
190             break;
191
192         default:
193             return 0;
194         }
195     }
196
197     if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
198         if (!ctx->cipher->init(ctx, key, iv, enc))
199             return 0;
200     }
201     ctx->buf_len = 0;
202     ctx->final_used = 0;
203     ctx->block_mask = ctx->cipher->block_size - 1;
204     return 1;
205 }
206
207 int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
208                      const unsigned char *in, int inl)
209 {
210     if (ctx->encrypt)
211         return EVP_EncryptUpdate(ctx, out, outl, in, inl);
212     else
213         return EVP_DecryptUpdate(ctx, out, outl, in, inl);
214 }
215
216 int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
217 {
218     if (ctx->encrypt)
219         return EVP_EncryptFinal_ex(ctx, out, outl);
220     else
221         return EVP_DecryptFinal_ex(ctx, out, outl);
222 }
223
224 int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
225 {
226     if (ctx->encrypt)
227         return EVP_EncryptFinal(ctx, out, outl);
228     else
229         return EVP_DecryptFinal(ctx, out, outl);
230 }
231
232 int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
233                     const unsigned char *key, const unsigned char *iv)
234 {
235     return EVP_CipherInit(ctx, cipher, key, iv, 1);
236 }
237
238 int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
239                        ENGINE *impl, const unsigned char *key,
240                        const unsigned char *iv)
241 {
242     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
243 }
244
245 int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
246                     const unsigned char *key, const unsigned char *iv)
247 {
248     return EVP_CipherInit(ctx, cipher, key, iv, 0);
249 }
250
251 int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
252                        ENGINE *impl, const unsigned char *key,
253                        const unsigned char *iv)
254 {
255     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
256 }
257
258 /*
259  * According to the letter of standard difference between pointers
260  * is specified to be valid only within same object. This makes
261  * it formally challenging to determine if input and output buffers
262  * are not partially overlapping with standard pointer arithmetic.
263  */
264 #ifdef PTRDIFF_T
265 # undef PTRDIFF_T
266 #endif
267 #if defined(OPENSSL_SYS_VMS) && __INITIAL_POINTER_SIZE==64
268 /*
269  * Then we have VMS that distinguishes itself by adhering to
270  * sizeof(size_t)==4 even in 64-bit builds, which means that
271  * difference between two pointers might be truncated to 32 bits.
272  * In the context one can even wonder how comparison for
273  * equality is implemented. To be on the safe side we adhere to
274  * PTRDIFF_T even for comparison for equality.
275  */
276 # define PTRDIFF_T uint64_t
277 #else
278 # define PTRDIFF_T size_t
279 #endif
280
281 int is_partially_overlapping(const void *ptr1, const void *ptr2, int len)
282 {
283     PTRDIFF_T diff = (PTRDIFF_T)ptr1-(PTRDIFF_T)ptr2;
284     /*
285      * Check for partially overlapping buffers. [Binary logical
286      * operations are used instead of boolean to minimize number
287      * of conditional branches.]
288      */
289     int overlapped = (len > 0) & (diff != 0) & ((diff < (PTRDIFF_T)len) |
290                                                 (diff > (0 - (PTRDIFF_T)len)));
291
292     return overlapped;
293 }
294
295 int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
296                       const unsigned char *in, int inl)
297 {
298     int i, j, bl;
299
300     bl = ctx->cipher->block_size;
301
302     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
303         /* If block size > 1 then the cipher will have to do this check */
304         if (bl == 1 && is_partially_overlapping(out, in, inl)) {
305             EVPerr(EVP_F_EVP_ENCRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);
306             return 0;
307         }
308
309         i = ctx->cipher->do_cipher(ctx, out, in, inl);
310         if (i < 0)
311             return 0;
312         else
313             *outl = i;
314         return 1;
315     }
316
317     if (inl <= 0) {
318         *outl = 0;
319         return inl == 0;
320     }
321     if (is_partially_overlapping(out + ctx->buf_len, in, inl)) {
322         EVPerr(EVP_F_EVP_ENCRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);
323         return 0;
324     }
325
326     if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
327         if (ctx->cipher->do_cipher(ctx, out, in, inl)) {
328             *outl = inl;
329             return 1;
330         } else {
331             *outl = 0;
332             return 0;
333         }
334     }
335     i = ctx->buf_len;
336     OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
337     if (i != 0) {
338         if (bl - i > inl) {
339             memcpy(&(ctx->buf[i]), in, inl);
340             ctx->buf_len += inl;
341             *outl = 0;
342             return 1;
343         } else {
344             j = bl - i;
345             memcpy(&(ctx->buf[i]), in, j);
346             inl -= j;
347             in += j;
348             if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl))
349                 return 0;
350             out += bl;
351             *outl = bl;
352         }
353     } else
354         *outl = 0;
355     i = inl & (bl - 1);
356     inl -= i;
357     if (inl > 0) {
358         if (!ctx->cipher->do_cipher(ctx, out, in, inl))
359             return 0;
360         *outl += inl;
361     }
362
363     if (i != 0)
364         memcpy(ctx->buf, &(in[inl]), i);
365     ctx->buf_len = i;
366     return 1;
367 }
368
369 int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
370 {
371     int ret;
372     ret = EVP_EncryptFinal_ex(ctx, out, outl);
373     return ret;
374 }
375
376 int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
377 {
378     int n, ret;
379     unsigned int i, b, bl;
380
381     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
382         ret = ctx->cipher->do_cipher(ctx, out, NULL, 0);
383         if (ret < 0)
384             return 0;
385         else
386             *outl = ret;
387         return 1;
388     }
389
390     b = ctx->cipher->block_size;
391     OPENSSL_assert(b <= sizeof ctx->buf);
392     if (b == 1) {
393         *outl = 0;
394         return 1;
395     }
396     bl = ctx->buf_len;
397     if (ctx->flags & EVP_CIPH_NO_PADDING) {
398         if (bl) {
399             EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX,
400                    EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
401             return 0;
402         }
403         *outl = 0;
404         return 1;
405     }
406
407     n = b - bl;
408     for (i = bl; i < b; i++)
409         ctx->buf[i] = n;
410     ret = ctx->cipher->do_cipher(ctx, out, ctx->buf, b);
411
412     if (ret)
413         *outl = b;
414
415     return ret;
416 }
417
418 int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
419                       const unsigned char *in, int inl)
420 {
421     int fix_len;
422     unsigned int b;
423
424     b = ctx->cipher->block_size;
425
426     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
427         if (b == 1 && is_partially_overlapping(out, in, inl)) {
428             EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);
429             return 0;
430         }
431
432         fix_len = ctx->cipher->do_cipher(ctx, out, in, inl);
433         if (fix_len < 0) {
434             *outl = 0;
435             return 0;
436         } else
437             *outl = fix_len;
438         return 1;
439     }
440
441     if (inl <= 0) {
442         *outl = 0;
443         return inl == 0;
444     }
445
446     if (ctx->flags & EVP_CIPH_NO_PADDING)
447         return EVP_EncryptUpdate(ctx, out, outl, in, inl);
448
449     OPENSSL_assert(b <= sizeof ctx->final);
450
451     if (ctx->final_used) {
452         /* see comment about PTRDIFF_T comparison above */
453         if (((PTRDIFF_T)out == (PTRDIFF_T)in)
454             || is_partially_overlapping(out, in, b)) {
455             EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_PARTIALLY_OVERLAPPING);
456             return 0;
457         }
458         memcpy(out, ctx->final, b);
459         out += b;
460         fix_len = 1;
461     } else
462         fix_len = 0;
463
464     if (!EVP_EncryptUpdate(ctx, out, outl, in, inl))
465         return 0;
466
467     /*
468      * if we have 'decrypted' a multiple of block size, make sure we have a
469      * copy of this last block
470      */
471     if (b > 1 && !ctx->buf_len) {
472         *outl -= b;
473         ctx->final_used = 1;
474         memcpy(ctx->final, &out[*outl], b);
475     } else
476         ctx->final_used = 0;
477
478     if (fix_len)
479         *outl += b;
480
481     return 1;
482 }
483
484 int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
485 {
486     int ret;
487     ret = EVP_DecryptFinal_ex(ctx, out, outl);
488     return ret;
489 }
490
491 int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
492 {
493     int i, n;
494     unsigned int b;
495     *outl = 0;
496
497     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
498         i = ctx->cipher->do_cipher(ctx, out, NULL, 0);
499         if (i < 0)
500             return 0;
501         else
502             *outl = i;
503         return 1;
504     }
505
506     b = ctx->cipher->block_size;
507     if (ctx->flags & EVP_CIPH_NO_PADDING) {
508         if (ctx->buf_len) {
509             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX,
510                    EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
511             return 0;
512         }
513         *outl = 0;
514         return 1;
515     }
516     if (b > 1) {
517         if (ctx->buf_len || !ctx->final_used) {
518             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_WRONG_FINAL_BLOCK_LENGTH);
519             return (0);
520         }
521         OPENSSL_assert(b <= sizeof ctx->final);
522
523         /*
524          * The following assumes that the ciphertext has been authenticated.
525          * Otherwise it provides a padding oracle.
526          */
527         n = ctx->final[b - 1];
528         if (n == 0 || n > (int)b) {
529             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
530             return (0);
531         }
532         for (i = 0; i < n; i++) {
533             if (ctx->final[--b] != n) {
534                 EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
535                 return (0);
536             }
537         }
538         n = ctx->cipher->block_size - n;
539         for (i = 0; i < n; i++)
540             out[i] = ctx->final[i];
541         *outl = n;
542     } else
543         *outl = 0;
544     return (1);
545 }
546
547 int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen)
548 {
549     if (c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH)
550         return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL);
551     if (c->key_len == keylen)
552         return 1;
553     if ((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) {
554         c->key_len = keylen;
555         return 1;
556     }
557     EVPerr(EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH, EVP_R_INVALID_KEY_LENGTH);
558     return 0;
559 }
560
561 int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad)
562 {
563     if (pad)
564         ctx->flags &= ~EVP_CIPH_NO_PADDING;
565     else
566         ctx->flags |= EVP_CIPH_NO_PADDING;
567     return 1;
568 }
569
570 int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
571 {
572     int ret;
573     if (!ctx->cipher) {
574         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_NO_CIPHER_SET);
575         return 0;
576     }
577
578     if (!ctx->cipher->ctrl) {
579         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_NOT_IMPLEMENTED);
580         return 0;
581     }
582
583     ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
584     if (ret == -1) {
585         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL,
586                EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
587         return 0;
588     }
589     return ret;
590 }
591
592 int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
593 {
594     if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
595         return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
596     if (RAND_bytes(key, ctx->key_len) <= 0)
597         return 0;
598     return 1;
599 }
600
601 int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
602 {
603     if ((in == NULL) || (in->cipher == NULL)) {
604         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INPUT_NOT_INITIALIZED);
605         return 0;
606     }
607 #ifndef OPENSSL_NO_ENGINE
608     /* Make sure it's safe to copy a cipher context using an ENGINE */
609     if (in->engine && !ENGINE_init(in->engine)) {
610         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_ENGINE_LIB);
611         return 0;
612     }
613 #endif
614
615     EVP_CIPHER_CTX_reset(out);
616     memcpy(out, in, sizeof(*out));
617
618     if (in->cipher_data && in->cipher->ctx_size) {
619         out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
620         if (out->cipher_data == NULL) {
621             out->cipher = NULL;
622             EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_MALLOC_FAILURE);
623             return 0;
624         }
625         memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
626     }
627
628     if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
629         if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) {
630             out->cipher = NULL;
631             EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INITIALIZATION_ERROR);
632             return 0;
633         }
634     return 1;
635 }