Convert memset calls to OPENSSL_cleanse
[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                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE);
129                 return 0;
130             }
131         } else {
132             ctx->cipher_data = NULL;
133         }
134         ctx->key_len = cipher->key_len;
135         /* Preserve wrap enable flag, zero everything else */
136         ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW;
137         if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) {
138             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) {
139                 EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
140                 return 0;
141             }
142         }
143     } else if (!ctx->cipher) {
144         EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET);
145         return 0;
146     }
147 #ifndef OPENSSL_NO_ENGINE
148  skip_to_init:
149 #endif
150     /* we assume block size is a power of 2 in *cryptUpdate */
151     OPENSSL_assert(ctx->cipher->block_size == 1
152                    || ctx->cipher->block_size == 8
153                    || ctx->cipher->block_size == 16);
154
155     if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW)
156         && EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_WRAP_MODE) {
157         EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_WRAP_MODE_NOT_ALLOWED);
158         return 0;
159     }
160
161     if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_CUSTOM_IV)) {
162         switch (EVP_CIPHER_CTX_mode(ctx)) {
163
164         case EVP_CIPH_STREAM_CIPHER:
165         case EVP_CIPH_ECB_MODE:
166             break;
167
168         case EVP_CIPH_CFB_MODE:
169         case EVP_CIPH_OFB_MODE:
170
171             ctx->num = 0;
172             /* fall-through */
173
174         case EVP_CIPH_CBC_MODE:
175
176             OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <=
177                            (int)sizeof(ctx->iv));
178             if (iv)
179                 memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
180             memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
181             break;
182
183         case EVP_CIPH_CTR_MODE:
184             ctx->num = 0;
185             /* Don't reuse IV for CTR mode */
186             if (iv)
187                 memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
188             break;
189
190         default:
191             return 0;
192         }
193     }
194
195     if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
196         if (!ctx->cipher->init(ctx, key, iv, enc))
197             return 0;
198     }
199     ctx->buf_len = 0;
200     ctx->final_used = 0;
201     ctx->block_mask = ctx->cipher->block_size - 1;
202     return 1;
203 }
204
205 int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
206                      const unsigned char *in, int inl)
207 {
208     if (ctx->encrypt)
209         return EVP_EncryptUpdate(ctx, out, outl, in, inl);
210     else
211         return EVP_DecryptUpdate(ctx, out, outl, in, inl);
212 }
213
214 int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
215 {
216     if (ctx->encrypt)
217         return EVP_EncryptFinal_ex(ctx, out, outl);
218     else
219         return EVP_DecryptFinal_ex(ctx, out, outl);
220 }
221
222 int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
223 {
224     if (ctx->encrypt)
225         return EVP_EncryptFinal(ctx, out, outl);
226     else
227         return EVP_DecryptFinal(ctx, out, outl);
228 }
229
230 int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
231                     const unsigned char *key, const unsigned char *iv)
232 {
233     return EVP_CipherInit(ctx, cipher, key, iv, 1);
234 }
235
236 int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
237                        ENGINE *impl, const unsigned char *key,
238                        const unsigned char *iv)
239 {
240     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
241 }
242
243 int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
244                     const unsigned char *key, const unsigned char *iv)
245 {
246     return EVP_CipherInit(ctx, cipher, key, iv, 0);
247 }
248
249 int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
250                        ENGINE *impl, const unsigned char *key,
251                        const unsigned char *iv)
252 {
253     return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
254 }
255
256 /*
257  * According to the letter of standard difference between pointers
258  * is specified to be valid only within same object. This makes
259  * it formally challenging to determine if input and output buffers
260  * are not partially overlapping with standard pointer arithmetic.
261  */
262 #ifdef PTRDIFF_T
263 # undef PTRDIFF_T
264 #endif
265 #if defined(OPENSSL_SYS_VMS) && __INITIAL_POINTER_SIZE==64
266 /*
267  * Then we have VMS that distinguishes itself by adhering to
268  * sizeof(size_t)==4 even in 64-bit builds, which means that
269  * difference between two pointers might be truncated to 32 bits.
270  * In the context one can even wonder how comparison for
271  * equality is implemented. To be on the safe side we adhere to
272  * PTRDIFF_T even for comparison for equality.
273  */
274 # define PTRDIFF_T uint64_t
275 #else
276 # define PTRDIFF_T size_t
277 #endif
278
279 static int is_partially_overlapping(const void *ptr1, const void *ptr2,
280                                     int len)
281 {
282     PTRDIFF_T diff = (PTRDIFF_T)ptr1-(PTRDIFF_T)ptr2;
283     /*
284      * Check for partially overlapping buffers. [Binary logical
285      * operations are used instead of boolean to minimize number
286      * of conditional branches.]
287      */
288     int condition = (len > 0) & (diff != 0) & ((diff < (PTRDIFF_T)len) |
289                                                (diff > (0 - (PTRDIFF_T)len)));
290     assert(!condition);
291     return condition;
292 }
293
294 int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
295                       const unsigned char *in, int inl)
296 {
297     int i, j, bl;
298
299     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
300         if (is_partially_overlapping(out, in, inl))
301             return 0;
302
303         i = ctx->cipher->do_cipher(ctx, out, in, inl);
304         if (i < 0)
305             return 0;
306         else
307             *outl = i;
308         return 1;
309     }
310
311     if (inl <= 0) {
312         *outl = 0;
313         return inl == 0;
314     }
315     if (is_partially_overlapping(out, in, inl))
316         return 0;
317
318     if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
319         if (ctx->cipher->do_cipher(ctx, out, in, inl)) {
320             *outl = inl;
321             return 1;
322         } else {
323             *outl = 0;
324             return 0;
325         }
326     }
327     i = ctx->buf_len;
328     bl = ctx->cipher->block_size;
329     OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
330     if (i != 0) {
331         if (bl - i > inl) {
332             memcpy(&(ctx->buf[i]), in, inl);
333             ctx->buf_len += inl;
334             *outl = 0;
335             return 1;
336         } else {
337             j = bl - i;
338             memcpy(&(ctx->buf[i]), in, j);
339             inl -= j;
340             in += j;
341             if (is_partially_overlapping(out, in, bl))
342                 return 0;
343             if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl))
344                 return 0;
345             out += bl;
346             *outl = bl;
347         }
348     } else
349         *outl = 0;
350     i = inl & (bl - 1);
351     inl -= i;
352     if (inl > 0) {
353         if (!ctx->cipher->do_cipher(ctx, out, in, inl))
354             return 0;
355         *outl += inl;
356     }
357
358     if (i != 0)
359         memcpy(ctx->buf, &(in[inl]), i);
360     ctx->buf_len = i;
361     return 1;
362 }
363
364 int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
365 {
366     int ret;
367     ret = EVP_EncryptFinal_ex(ctx, out, outl);
368     return ret;
369 }
370
371 int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
372 {
373     int n, ret;
374     unsigned int i, b, bl;
375
376     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
377         ret = ctx->cipher->do_cipher(ctx, out, NULL, 0);
378         if (ret < 0)
379             return 0;
380         else
381             *outl = ret;
382         return 1;
383     }
384
385     b = ctx->cipher->block_size;
386     OPENSSL_assert(b <= sizeof ctx->buf);
387     if (b == 1) {
388         *outl = 0;
389         return 1;
390     }
391     bl = ctx->buf_len;
392     if (ctx->flags & EVP_CIPH_NO_PADDING) {
393         if (bl) {
394             EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX,
395                    EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
396             return 0;
397         }
398         *outl = 0;
399         return 1;
400     }
401
402     n = b - bl;
403     for (i = bl; i < b; i++)
404         ctx->buf[i] = n;
405     ret = ctx->cipher->do_cipher(ctx, out, ctx->buf, b);
406
407     if (ret)
408         *outl = b;
409
410     return ret;
411 }
412
413 int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
414                       const unsigned char *in, int inl)
415 {
416     int fix_len;
417     unsigned int b;
418
419     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
420         if (is_partially_overlapping(out, in, inl))
421             return 0;
422
423         fix_len = ctx->cipher->do_cipher(ctx, out, in, inl);
424         if (fix_len < 0) {
425             *outl = 0;
426             return 0;
427         } else
428             *outl = fix_len;
429         return 1;
430     }
431
432     if (inl <= 0) {
433         *outl = 0;
434         return inl == 0;
435     }
436
437     if (ctx->flags & EVP_CIPH_NO_PADDING)
438         return EVP_EncryptUpdate(ctx, out, outl, in, inl);
439
440     b = ctx->cipher->block_size;
441     OPENSSL_assert(b <= sizeof ctx->final);
442
443     if (ctx->final_used) {
444         /* see comment about PTRDIFF_T comparison above */
445         if (((PTRDIFF_T)out == (PTRDIFF_T)in)
446             || is_partially_overlapping(out, in, b))
447             return 0;
448         memcpy(out, ctx->final, b);
449         out += b;
450         fix_len = 1;
451     } else
452         fix_len = 0;
453
454     if (!EVP_EncryptUpdate(ctx, out, outl, in, inl))
455         return 0;
456
457     /*
458      * if we have 'decrypted' a multiple of block size, make sure we have a
459      * copy of this last block
460      */
461     if (b > 1 && !ctx->buf_len) {
462         *outl -= b;
463         ctx->final_used = 1;
464         memcpy(ctx->final, &out[*outl], b);
465     } else
466         ctx->final_used = 0;
467
468     if (fix_len)
469         *outl += b;
470
471     return 1;
472 }
473
474 int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
475 {
476     int ret;
477     ret = EVP_DecryptFinal_ex(ctx, out, outl);
478     return ret;
479 }
480
481 int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
482 {
483     int i, n;
484     unsigned int b;
485     *outl = 0;
486
487     if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
488         i = ctx->cipher->do_cipher(ctx, out, NULL, 0);
489         if (i < 0)
490             return 0;
491         else
492             *outl = i;
493         return 1;
494     }
495
496     b = ctx->cipher->block_size;
497     if (ctx->flags & EVP_CIPH_NO_PADDING) {
498         if (ctx->buf_len) {
499             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX,
500                    EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
501             return 0;
502         }
503         *outl = 0;
504         return 1;
505     }
506     if (b > 1) {
507         if (ctx->buf_len || !ctx->final_used) {
508             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_WRONG_FINAL_BLOCK_LENGTH);
509             return (0);
510         }
511         OPENSSL_assert(b <= sizeof ctx->final);
512
513         /*
514          * The following assumes that the ciphertext has been authenticated.
515          * Otherwise it provides a padding oracle.
516          */
517         n = ctx->final[b - 1];
518         if (n == 0 || n > (int)b) {
519             EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
520             return (0);
521         }
522         for (i = 0; i < n; i++) {
523             if (ctx->final[--b] != n) {
524                 EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
525                 return (0);
526             }
527         }
528         n = ctx->cipher->block_size - n;
529         for (i = 0; i < n; i++)
530             out[i] = ctx->final[i];
531         *outl = n;
532     } else
533         *outl = 0;
534     return (1);
535 }
536
537 int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen)
538 {
539     if (c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH)
540         return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL);
541     if (c->key_len == keylen)
542         return 1;
543     if ((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) {
544         c->key_len = keylen;
545         return 1;
546     }
547     EVPerr(EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH, EVP_R_INVALID_KEY_LENGTH);
548     return 0;
549 }
550
551 int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad)
552 {
553     if (pad)
554         ctx->flags &= ~EVP_CIPH_NO_PADDING;
555     else
556         ctx->flags |= EVP_CIPH_NO_PADDING;
557     return 1;
558 }
559
560 int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
561 {
562     int ret;
563     if (!ctx->cipher) {
564         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_NO_CIPHER_SET);
565         return 0;
566     }
567
568     if (!ctx->cipher->ctrl) {
569         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_NOT_IMPLEMENTED);
570         return 0;
571     }
572
573     ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
574     if (ret == -1) {
575         EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL,
576                EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
577         return 0;
578     }
579     return ret;
580 }
581
582 int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
583 {
584     if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
585         return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
586     if (RAND_bytes(key, ctx->key_len) <= 0)
587         return 0;
588     return 1;
589 }
590
591 int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
592 {
593     if ((in == NULL) || (in->cipher == NULL)) {
594         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INPUT_NOT_INITIALIZED);
595         return 0;
596     }
597 #ifndef OPENSSL_NO_ENGINE
598     /* Make sure it's safe to copy a cipher context using an ENGINE */
599     if (in->engine && !ENGINE_init(in->engine)) {
600         EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_ENGINE_LIB);
601         return 0;
602     }
603 #endif
604
605     EVP_CIPHER_CTX_reset(out);
606     memcpy(out, in, sizeof(*out));
607
608     if (in->cipher_data && in->cipher->ctx_size) {
609         out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
610         if (out->cipher_data == NULL) {
611             EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_MALLOC_FAILURE);
612             return 0;
613         }
614         memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
615     }
616
617     if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
618         return in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out);
619     return 1;
620 }