1/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
7 *
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to.  The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14 *
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the copyright
26 *    notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 *    notice, this list of conditions and the following disclaimer in the
29 *    documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 *    must display the following acknowledgement:
32 *    "This product includes cryptographic software written by
33 *     Eric Young (eay@cryptsoft.com)"
34 *    The word 'cryptographic' can be left out if the rouines from the library
35 *    being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 *    the apps directory (application code) you must include an acknowledgement:
38 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 *
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed.  i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.] */
56
57#include <openssl/cipher.h>
58
59#include <assert.h>
60#include <string.h>
61
62#include <openssl/err.h>
63#include <openssl/mem.h>
64#include <openssl/nid.h>
65
66#include "internal.h"
67#include "../../internal.h"
68
69
70void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx) {
71  OPENSSL_memset(ctx, 0, sizeof(EVP_CIPHER_CTX));
72}
73
74EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void) {
75  EVP_CIPHER_CTX *ctx = OPENSSL_malloc(sizeof(EVP_CIPHER_CTX));
76  if (ctx) {
77    EVP_CIPHER_CTX_init(ctx);
78  }
79  return ctx;
80}
81
82int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *c) {
83  if (c->cipher != NULL) {
84    if (c->cipher->cleanup) {
85      c->cipher->cleanup(c);
86    }
87    OPENSSL_cleanse(c->cipher_data, c->cipher->ctx_size);
88  }
89  OPENSSL_free(c->cipher_data);
90
91  OPENSSL_memset(c, 0, sizeof(EVP_CIPHER_CTX));
92  return 1;
93}
94
95void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx) {
96  if (ctx) {
97    EVP_CIPHER_CTX_cleanup(ctx);
98    OPENSSL_free(ctx);
99  }
100}
101
102int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in) {
103  if (in == NULL || in->cipher == NULL) {
104    OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INPUT_NOT_INITIALIZED);
105    return 0;
106  }
107
108  EVP_CIPHER_CTX_cleanup(out);
109  OPENSSL_memcpy(out, in, sizeof(EVP_CIPHER_CTX));
110
111  if (in->cipher_data && in->cipher->ctx_size) {
112    out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
113    if (!out->cipher_data) {
114      out->cipher = NULL;
115      OPENSSL_PUT_ERROR(CIPHER, ERR_R_MALLOC_FAILURE);
116      return 0;
117    }
118    OPENSSL_memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
119  }
120
121  if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY) {
122    if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) {
123      out->cipher = NULL;
124      return 0;
125    }
126  }
127
128  return 1;
129}
130
131int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
132                      ENGINE *engine, const uint8_t *key, const uint8_t *iv,
133                      int enc) {
134  if (enc == -1) {
135    enc = ctx->encrypt;
136  } else {
137    if (enc) {
138      enc = 1;
139    }
140    ctx->encrypt = enc;
141  }
142
143  if (cipher) {
144    /* Ensure a context left from last time is cleared (the previous check
145     * attempted to avoid this if the same ENGINE and EVP_CIPHER could be
146     * used). */
147    if (ctx->cipher) {
148      EVP_CIPHER_CTX_cleanup(ctx);
149      /* Restore encrypt and flags */
150      ctx->encrypt = enc;
151    }
152
153    ctx->cipher = cipher;
154    if (ctx->cipher->ctx_size) {
155      ctx->cipher_data = OPENSSL_malloc(ctx->cipher->ctx_size);
156      if (!ctx->cipher_data) {
157        ctx->cipher = NULL;
158        OPENSSL_PUT_ERROR(CIPHER, ERR_R_MALLOC_FAILURE);
159        return 0;
160      }
161    } else {
162      ctx->cipher_data = NULL;
163    }
164
165    ctx->key_len = cipher->key_len;
166    ctx->flags = 0;
167
168    if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) {
169      if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) {
170        ctx->cipher = NULL;
171        OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INITIALIZATION_ERROR);
172        return 0;
173      }
174    }
175  } else if (!ctx->cipher) {
176    OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_NO_CIPHER_SET);
177    return 0;
178  }
179
180  /* we assume block size is a power of 2 in *cryptUpdate */
181  assert(ctx->cipher->block_size == 1 || ctx->cipher->block_size == 8 ||
182         ctx->cipher->block_size == 16);
183
184  if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_CUSTOM_IV)) {
185    switch (EVP_CIPHER_CTX_mode(ctx)) {
186      case EVP_CIPH_STREAM_CIPHER:
187      case EVP_CIPH_ECB_MODE:
188        break;
189
190      case EVP_CIPH_CFB_MODE:
191        ctx->num = 0;
192        /* fall-through */
193
194      case EVP_CIPH_CBC_MODE:
195        assert(EVP_CIPHER_CTX_iv_length(ctx) <= sizeof(ctx->iv));
196        if (iv) {
197          OPENSSL_memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
198        }
199        OPENSSL_memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
200        break;
201
202      case EVP_CIPH_CTR_MODE:
203      case EVP_CIPH_OFB_MODE:
204        ctx->num = 0;
205        /* Don't reuse IV for CTR mode */
206        if (iv) {
207          OPENSSL_memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
208        }
209        break;
210
211      default:
212        return 0;
213    }
214  }
215
216  if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
217    if (!ctx->cipher->init(ctx, key, iv, enc)) {
218      return 0;
219    }
220  }
221
222  ctx->buf_len = 0;
223  ctx->final_used = 0;
224  ctx->block_mask = ctx->cipher->block_size - 1;
225  return 1;
226}
227
228int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
229                       ENGINE *impl, const uint8_t *key, const uint8_t *iv) {
230  return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
231}
232
233int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
234                       ENGINE *impl, const uint8_t *key, const uint8_t *iv) {
235  return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
236}
237
238int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len,
239                      const uint8_t *in, int in_len) {
240  int i, j, bl;
241
242  if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
243    i = ctx->cipher->cipher(ctx, out, in, in_len);
244    if (i < 0) {
245      return 0;
246    } else {
247      *out_len = i;
248    }
249    return 1;
250  }
251
252  if (in_len <= 0) {
253    *out_len = 0;
254    return in_len == 0;
255  }
256
257  if (ctx->buf_len == 0 && (in_len & ctx->block_mask) == 0) {
258    if (ctx->cipher->cipher(ctx, out, in, in_len)) {
259      *out_len = in_len;
260      return 1;
261    } else {
262      *out_len = 0;
263      return 0;
264    }
265  }
266
267  i = ctx->buf_len;
268  bl = ctx->cipher->block_size;
269  assert(bl <= (int)sizeof(ctx->buf));
270  if (i != 0) {
271    if (bl - i > in_len) {
272      OPENSSL_memcpy(&ctx->buf[i], in, in_len);
273      ctx->buf_len += in_len;
274      *out_len = 0;
275      return 1;
276    } else {
277      j = bl - i;
278      OPENSSL_memcpy(&ctx->buf[i], in, j);
279      if (!ctx->cipher->cipher(ctx, out, ctx->buf, bl)) {
280        return 0;
281      }
282      in_len -= j;
283      in += j;
284      out += bl;
285      *out_len = bl;
286    }
287  } else {
288    *out_len = 0;
289  }
290
291  i = in_len & ctx->block_mask;
292  in_len -= i;
293  if (in_len > 0) {
294    if (!ctx->cipher->cipher(ctx, out, in, in_len)) {
295      return 0;
296    }
297    *out_len += in_len;
298  }
299
300  if (i != 0) {
301    OPENSSL_memcpy(ctx->buf, &in[in_len], i);
302  }
303  ctx->buf_len = i;
304  return 1;
305}
306
307int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len) {
308  int n, ret;
309  unsigned int i, b, bl;
310
311  if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
312    ret = ctx->cipher->cipher(ctx, out, NULL, 0);
313    if (ret < 0) {
314      return 0;
315    } else {
316      *out_len = ret;
317    }
318    return 1;
319  }
320
321  b = ctx->cipher->block_size;
322  assert(b <= sizeof(ctx->buf));
323  if (b == 1) {
324    *out_len = 0;
325    return 1;
326  }
327
328  bl = ctx->buf_len;
329  if (ctx->flags & EVP_CIPH_NO_PADDING) {
330    if (bl) {
331      OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
332      return 0;
333    }
334    *out_len = 0;
335    return 1;
336  }
337
338  n = b - bl;
339  for (i = bl; i < b; i++) {
340    ctx->buf[i] = n;
341  }
342  ret = ctx->cipher->cipher(ctx, out, ctx->buf, b);
343
344  if (ret) {
345    *out_len = b;
346  }
347
348  return ret;
349}
350
351int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len,
352                      const uint8_t *in, int in_len) {
353  int fix_len;
354  unsigned int b;
355
356  if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
357    int r = ctx->cipher->cipher(ctx, out, in, in_len);
358    if (r < 0) {
359      *out_len = 0;
360      return 0;
361    } else {
362      *out_len = r;
363    }
364    return 1;
365  }
366
367  if (in_len <= 0) {
368    *out_len = 0;
369    return in_len == 0;
370  }
371
372  if (ctx->flags & EVP_CIPH_NO_PADDING) {
373    return EVP_EncryptUpdate(ctx, out, out_len, in, in_len);
374  }
375
376  b = ctx->cipher->block_size;
377  assert(b <= sizeof(ctx->final));
378
379  if (ctx->final_used) {
380    OPENSSL_memcpy(out, ctx->final, b);
381    out += b;
382    fix_len = 1;
383  } else {
384    fix_len = 0;
385  }
386
387  if (!EVP_EncryptUpdate(ctx, out, out_len, in, in_len)) {
388    return 0;
389  }
390
391  /* if we have 'decrypted' a multiple of block size, make sure
392   * we have a copy of this last block */
393  if (b > 1 && !ctx->buf_len) {
394    *out_len -= b;
395    ctx->final_used = 1;
396    OPENSSL_memcpy(ctx->final, &out[*out_len], b);
397  } else {
398    ctx->final_used = 0;
399  }
400
401  if (fix_len) {
402    *out_len += b;
403  }
404
405  return 1;
406}
407
408int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *out_len) {
409  int i, n;
410  unsigned int b;
411  *out_len = 0;
412
413  if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
414    i = ctx->cipher->cipher(ctx, out, NULL, 0);
415    if (i < 0) {
416      return 0;
417    } else {
418      *out_len = i;
419    }
420    return 1;
421  }
422
423  b = ctx->cipher->block_size;
424  if (ctx->flags & EVP_CIPH_NO_PADDING) {
425    if (ctx->buf_len) {
426      OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
427      return 0;
428    }
429    *out_len = 0;
430    return 1;
431  }
432
433  if (b > 1) {
434    if (ctx->buf_len || !ctx->final_used) {
435      OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_WRONG_FINAL_BLOCK_LENGTH);
436      return 0;
437    }
438    assert(b <= sizeof(ctx->final));
439
440    /* The following assumes that the ciphertext has been authenticated.
441     * Otherwise it provides a padding oracle. */
442    n = ctx->final[b - 1];
443    if (n == 0 || n > (int)b) {
444      OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
445      return 0;
446    }
447
448    for (i = 0; i < n; i++) {
449      if (ctx->final[--b] != n) {
450        OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
451        return 0;
452      }
453    }
454
455    n = ctx->cipher->block_size - n;
456    for (i = 0; i < n; i++) {
457      out[i] = ctx->final[i];
458    }
459    *out_len = n;
460  } else {
461    *out_len = 0;
462  }
463
464  return 1;
465}
466
467int EVP_Cipher(EVP_CIPHER_CTX *ctx, uint8_t *out, const uint8_t *in,
468               size_t in_len) {
469  return ctx->cipher->cipher(ctx, out, in, in_len);
470}
471
472int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len,
473                     const uint8_t *in, int in_len) {
474  if (ctx->encrypt) {
475    return EVP_EncryptUpdate(ctx, out, out_len, in, in_len);
476  } else {
477    return EVP_DecryptUpdate(ctx, out, out_len, in, in_len);
478  }
479}
480
481int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, uint8_t *out, int *out_len) {
482  if (ctx->encrypt) {
483    return EVP_EncryptFinal_ex(ctx, out, out_len);
484  } else {
485    return EVP_DecryptFinal_ex(ctx, out, out_len);
486  }
487}
488
489const EVP_CIPHER *EVP_CIPHER_CTX_cipher(const EVP_CIPHER_CTX *ctx) {
490  return ctx->cipher;
491}
492
493int EVP_CIPHER_CTX_nid(const EVP_CIPHER_CTX *ctx) {
494  return ctx->cipher->nid;
495}
496
497unsigned EVP_CIPHER_CTX_block_size(const EVP_CIPHER_CTX *ctx) {
498  return ctx->cipher->block_size;
499}
500
501unsigned EVP_CIPHER_CTX_key_length(const EVP_CIPHER_CTX *ctx) {
502  return ctx->key_len;
503}
504
505unsigned EVP_CIPHER_CTX_iv_length(const EVP_CIPHER_CTX *ctx) {
506  return ctx->cipher->iv_len;
507}
508
509void *EVP_CIPHER_CTX_get_app_data(const EVP_CIPHER_CTX *ctx) {
510  return ctx->app_data;
511}
512
513void EVP_CIPHER_CTX_set_app_data(EVP_CIPHER_CTX *ctx, void *data) {
514  ctx->app_data = data;
515}
516
517uint32_t EVP_CIPHER_CTX_flags(const EVP_CIPHER_CTX *ctx) {
518  return ctx->cipher->flags & ~EVP_CIPH_MODE_MASK;
519}
520
521uint32_t EVP_CIPHER_CTX_mode(const EVP_CIPHER_CTX *ctx) {
522  return ctx->cipher->flags & EVP_CIPH_MODE_MASK;
523}
524
525int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int command, int arg, void *ptr) {
526  int ret;
527  if (!ctx->cipher) {
528    OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_NO_CIPHER_SET);
529    return 0;
530  }
531
532  if (!ctx->cipher->ctrl) {
533    OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_CTRL_NOT_IMPLEMENTED);
534    return 0;
535  }
536
537  ret = ctx->cipher->ctrl(ctx, command, arg, ptr);
538  if (ret == -1) {
539    OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_CTRL_OPERATION_NOT_IMPLEMENTED);
540    return 0;
541  }
542
543  return ret;
544}
545
546int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad) {
547  if (pad) {
548    ctx->flags &= ~EVP_CIPH_NO_PADDING;
549  } else {
550    ctx->flags |= EVP_CIPH_NO_PADDING;
551  }
552  return 1;
553}
554
555int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, unsigned key_len) {
556  if (c->key_len == key_len) {
557    return 1;
558  }
559
560  if (key_len == 0 || !(c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) {
561    OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_INVALID_KEY_LENGTH);
562    return 0;
563  }
564
565  c->key_len = key_len;
566  return 1;
567}
568
569int EVP_CIPHER_nid(const EVP_CIPHER *cipher) { return cipher->nid; }
570
571unsigned EVP_CIPHER_block_size(const EVP_CIPHER *cipher) {
572  return cipher->block_size;
573}
574
575unsigned EVP_CIPHER_key_length(const EVP_CIPHER *cipher) {
576  return cipher->key_len;
577}
578
579unsigned EVP_CIPHER_iv_length(const EVP_CIPHER *cipher) {
580  return cipher->iv_len;
581}
582
583uint32_t EVP_CIPHER_flags(const EVP_CIPHER *cipher) {
584  return cipher->flags & ~EVP_CIPH_MODE_MASK;
585}
586
587uint32_t EVP_CIPHER_mode(const EVP_CIPHER *cipher) {
588  return cipher->flags & EVP_CIPH_MODE_MASK;
589}
590
591int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
592                   const uint8_t *key, const uint8_t *iv, int enc) {
593  if (cipher) {
594    EVP_CIPHER_CTX_init(ctx);
595  }
596  return EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, enc);
597}
598
599int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
600                    const uint8_t *key, const uint8_t *iv) {
601  return EVP_CipherInit(ctx, cipher, key, iv, 1);
602}
603
604int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
605                    const uint8_t *key, const uint8_t *iv) {
606  return EVP_CipherInit(ctx, cipher, key, iv, 0);
607}
608
609int EVP_add_cipher_alias(const char *a, const char *b) {
610  return 1;
611}
612