Use 8bit-counters when using libfuzzer
[openssl.git] / apps / 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 <stdlib.h>
12 #include <string.h>
13 #include <limits.h>
14 #include "apps.h"
15 #include <openssl/bio.h>
16 #include <openssl/err.h>
17 #include <openssl/evp.h>
18 #include <openssl/objects.h>
19 #include <openssl/x509.h>
20 #include <openssl/rand.h>
21 #include <openssl/pem.h>
22 #ifndef OPENSSL_NO_COMP
23 # include <openssl/comp.h>
24 #endif
25 #include <ctype.h>
26
27 #undef SIZE
28 #undef BSIZE
29 #define SIZE    (512)
30 #define BSIZE   (8*1024)
31
32 static int set_hex(char *in, unsigned char *out, int size);
33 static void show_ciphers(const OBJ_NAME *name, void *bio_);
34
35 typedef enum OPTION_choice {
36     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
37     OPT_LIST,
38     OPT_E, OPT_IN, OPT_OUT, OPT_PASS, OPT_ENGINE, OPT_D, OPT_P, OPT_V,
39     OPT_NOPAD, OPT_SALT, OPT_NOSALT, OPT_DEBUG, OPT_UPPER_P, OPT_UPPER_A,
40     OPT_A, OPT_Z, OPT_BUFSIZE, OPT_K, OPT_KFILE, OPT_UPPER_K, OPT_NONE,
41     OPT_UPPER_S, OPT_IV, OPT_MD, OPT_CIPHER
42 } OPTION_CHOICE;
43
44 const OPTIONS enc_options[] = {
45     {"help", OPT_HELP, '-', "Display this summary"},
46     {"ciphers", OPT_LIST, '-', "List ciphers"},
47     {"in", OPT_IN, '<', "Input file"},
48     {"out", OPT_OUT, '>', "Output file"},
49     {"pass", OPT_PASS, 's', "Passphrase source"},
50     {"e", OPT_E, '-', "Encrypt"},
51     {"d", OPT_D, '-', "Decrypt"},
52     {"p", OPT_P, '-', "Print the iv/key"},
53     {"P", OPT_UPPER_P, '-', "Print the iv/key and exit"},
54     {"v", OPT_V, '-', "Verbose output"},
55     {"nopad", OPT_NOPAD, '-', "Disable standard block padding"},
56     {"salt", OPT_SALT, '-', "Use salt in the KDF (default)"},
57     {"nosalt", OPT_NOSALT, '-', "Do not use salt in the KDF"},
58     {"debug", OPT_DEBUG, '-', "Print debug info"},
59     {"a", OPT_A, '-', "Base64 encode/decode, depending on encryption flag"},
60     {"base64", OPT_A, '-', "Same as option -a"},
61     {"A", OPT_UPPER_A, '-',
62      "Used with -[base64|a] to specify base64 buffer as a single line"},
63     {"bufsize", OPT_BUFSIZE, 's', "Buffer size"},
64     {"k", OPT_K, 's', "Passphrase"},
65     {"kfile", OPT_KFILE, '<', "Read passphrase from file"},
66     {"K", OPT_UPPER_K, 's', "Raw key, in hex"},
67     {"S", OPT_UPPER_S, 's', "Salt, in hex"},
68     {"iv", OPT_IV, 's', "IV in hex"},
69     {"md", OPT_MD, 's', "Use specified digest to create a key from the passphrase"},
70     {"none", OPT_NONE, '-', "Don't encrypt"},
71     {"", OPT_CIPHER, '-', "Any supported cipher"},
72 #ifdef ZLIB
73     {"z", OPT_Z, '-', "Use zlib as the 'encryption'"},
74 #endif
75 #ifndef OPENSSL_NO_ENGINE
76     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
77 #endif
78     {NULL}
79 };
80
81 int enc_main(int argc, char **argv)
82 {
83     static char buf[128];
84     static const char magic[] = "Salted__";
85     ENGINE *e = NULL;
86     BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio =
87         NULL, *wbio = NULL;
88     EVP_CIPHER_CTX *ctx = NULL;
89     const EVP_CIPHER *cipher = NULL, *c;
90     const EVP_MD *dgst = NULL;
91     char *hkey = NULL, *hiv = NULL, *hsalt = NULL, *p;
92     char *infile = NULL, *outfile = NULL, *prog;
93     char *str = NULL, *passarg = NULL, *pass = NULL, *strbuf = NULL;
94     char mbuf[sizeof magic - 1];
95     OPTION_CHOICE o;
96     int bsize = BSIZE, verbose = 0, debug = 0, olb64 = 0, nosalt = 0;
97     int enc = 1, printkey = 0, i, k;
98     int base64 = 0, informat = FORMAT_BINARY, outformat = FORMAT_BINARY;
99     int ret = 1, inl, nopad = 0;
100     unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
101     unsigned char *buff = NULL, salt[PKCS5_SALT_LEN];
102     long n;
103 #ifdef ZLIB
104     int do_zlib = 0;
105     BIO *bzl = NULL;
106 #endif
107
108     /* first check the program name */
109     prog = opt_progname(argv[0]);
110     if (strcmp(prog, "base64") == 0)
111         base64 = 1;
112 #ifdef ZLIB
113     else if (strcmp(prog, "zlib") == 0)
114         do_zlib = 1;
115 #endif
116     else {
117         cipher = EVP_get_cipherbyname(prog);
118         if (cipher == NULL && strcmp(prog, "enc") != 0) {
119             BIO_printf(bio_err, "%s is not a known cipher\n", prog);
120             goto end;
121         }
122     }
123
124     prog = opt_init(argc, argv, enc_options);
125     while ((o = opt_next()) != OPT_EOF) {
126         switch (o) {
127         case OPT_EOF:
128         case OPT_ERR:
129  opthelp:
130             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
131             goto end;
132         case OPT_HELP:
133             opt_help(enc_options);
134             ret = 0;
135             goto end;
136         case OPT_LIST:
137             BIO_printf(bio_err, "Supported ciphers:\n");
138             OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
139                                    show_ciphers, bio_err);
140             BIO_printf(bio_err, "\n");
141             goto end;
142         case OPT_E:
143             enc = 1;
144             break;
145         case OPT_IN:
146             infile = opt_arg();
147             break;
148         case OPT_OUT:
149             outfile = opt_arg();
150             break;
151         case OPT_PASS:
152             passarg = opt_arg();
153             break;
154         case OPT_ENGINE:
155             e = setup_engine(opt_arg(), 0);
156             break;
157         case OPT_D:
158             enc = 0;
159             break;
160         case OPT_P:
161             printkey = 1;
162             break;
163         case OPT_V:
164             verbose = 1;
165             break;
166         case OPT_NOPAD:
167             nopad = 1;
168             break;
169         case OPT_SALT:
170             nosalt = 0;
171             break;
172         case OPT_NOSALT:
173             nosalt = 1;
174             break;
175         case OPT_DEBUG:
176             debug = 1;
177             break;
178         case OPT_UPPER_P:
179             printkey = 2;
180             break;
181         case OPT_UPPER_A:
182             olb64 = 1;
183             break;
184         case OPT_A:
185             base64 = 1;
186             break;
187         case OPT_Z:
188 #ifdef ZLIB
189             do_zlib = 1;
190 #endif
191             break;
192         case OPT_BUFSIZE:
193             p = opt_arg();
194             i = (int)strlen(p) - 1;
195             k = i >= 1 && p[i] == 'k';
196             if (k)
197                 p[i] = '\0';
198             if (!opt_long(opt_arg(), &n)
199                     || n < 0 || (k && n >= LONG_MAX / 1024))
200                 goto opthelp;
201             if (k)
202                 n *= 1024;
203             bsize = (int)n;
204             break;
205         case OPT_K:
206             str = opt_arg();
207             break;
208         case OPT_KFILE:
209             in = bio_open_default(opt_arg(), 'r', FORMAT_TEXT);
210             if (in == NULL)
211                 goto opthelp;
212             i = BIO_gets(in, buf, sizeof buf);
213             BIO_free(in);
214             in = NULL;
215             if (i <= 0) {
216                 BIO_printf(bio_err,
217                            "%s Can't read key from %s\n", prog, opt_arg());
218                 goto opthelp;
219             }
220             while (--i > 0 && (buf[i] == '\r' || buf[i] == '\n'))
221                 buf[i] = '\0';
222             if (i <= 0) {
223                 BIO_printf(bio_err, "%s: zero length password\n", prog);
224                 goto opthelp;
225             }
226             str = buf;
227             break;
228         case OPT_UPPER_K:
229             hkey = opt_arg();
230             break;
231         case OPT_UPPER_S:
232             hsalt = opt_arg();
233             break;
234         case OPT_IV:
235             hiv = opt_arg();
236             break;
237         case OPT_MD:
238             if (!opt_md(opt_arg(), &dgst))
239                 goto opthelp;
240             break;
241         case OPT_CIPHER:
242             if (!opt_cipher(opt_unknown(), &c))
243                 goto opthelp;
244             cipher = c;
245             break;
246         case OPT_NONE:
247             cipher = NULL;
248             break;
249         }
250     }
251
252     if (cipher && EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
253         BIO_printf(bio_err, "%s: AEAD ciphers not supported\n", prog);
254         goto end;
255     }
256
257     if (cipher && (EVP_CIPHER_mode(cipher) == EVP_CIPH_XTS_MODE)) {
258         BIO_printf(bio_err, "%s XTS ciphers not supported\n", prog);
259         goto end;
260     }
261
262     if (dgst == NULL)
263         dgst = EVP_sha256();
264
265     /* It must be large enough for a base64 encoded line */
266     if (base64 && bsize < 80)
267         bsize = 80;
268     if (verbose)
269         BIO_printf(bio_err, "bufsize=%d\n", bsize);
270
271 #ifdef ZLIB
272     if (!do_zlib)
273 #endif
274         if (base64) {
275             if (enc)
276                 outformat = FORMAT_BASE64;
277             else
278                 informat = FORMAT_BASE64;
279         }
280
281     strbuf = app_malloc(SIZE, "strbuf");
282     buff = app_malloc(EVP_ENCODE_LENGTH(bsize), "evp buffer");
283
284     if (infile == NULL) {
285         unbuffer(stdin);
286         in = dup_bio_in(informat);
287     } else
288         in = bio_open_default(infile, 'r', informat);
289     if (in == NULL)
290         goto end;
291
292     if (!str && passarg) {
293         if (!app_passwd(passarg, NULL, &pass, NULL)) {
294             BIO_printf(bio_err, "Error getting password\n");
295             goto end;
296         }
297         str = pass;
298     }
299
300     if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) {
301         if (1) {
302 #ifndef OPENSSL_NO_UI
303             for (;;) {
304                 char prompt[200];
305
306                 BIO_snprintf(prompt, sizeof prompt, "enter %s %s password:",
307                              OBJ_nid2ln(EVP_CIPHER_nid(cipher)),
308                              (enc) ? "encryption" : "decryption");
309                 strbuf[0] = '\0';
310                 i = EVP_read_pw_string((char *)strbuf, SIZE, prompt, enc);
311                 if (i == 0) {
312                     if (strbuf[0] == '\0') {
313                         ret = 1;
314                         goto end;
315                     }
316                     str = strbuf;
317                     break;
318                 }
319                 if (i < 0) {
320                     BIO_printf(bio_err, "bad password read\n");
321                     goto end;
322                 }
323             }
324         } else {
325 #endif
326             BIO_printf(bio_err, "password required\n");
327             goto end;
328         }
329     }
330
331     out = bio_open_default(outfile, 'w', outformat);
332     if (out == NULL)
333         goto end;
334
335     if (debug) {
336         BIO_set_callback(in, BIO_debug_callback);
337         BIO_set_callback(out, BIO_debug_callback);
338         BIO_set_callback_arg(in, (char *)bio_err);
339         BIO_set_callback_arg(out, (char *)bio_err);
340     }
341
342     rbio = in;
343     wbio = out;
344
345 #ifdef ZLIB
346     if (do_zlib) {
347         if ((bzl = BIO_new(BIO_f_zlib())) == NULL)
348             goto end;
349         if (debug) {
350             BIO_set_callback(bzl, BIO_debug_callback);
351             BIO_set_callback_arg(bzl, (char *)bio_err);
352         }
353         if (enc)
354             wbio = BIO_push(bzl, wbio);
355         else
356             rbio = BIO_push(bzl, rbio);
357     }
358 #endif
359
360     if (base64) {
361         if ((b64 = BIO_new(BIO_f_base64())) == NULL)
362             goto end;
363         if (debug) {
364             BIO_set_callback(b64, BIO_debug_callback);
365             BIO_set_callback_arg(b64, (char *)bio_err);
366         }
367         if (olb64)
368             BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
369         if (enc)
370             wbio = BIO_push(b64, wbio);
371         else
372             rbio = BIO_push(b64, rbio);
373     }
374
375     if (cipher != NULL) {
376         /*
377          * Note that str is NULL if a key was passed on the command line, so
378          * we get no salt in that case. Is this a bug?
379          */
380         if (str != NULL) {
381             /*
382              * Salt handling: if encrypting generate a salt and write to
383              * output BIO. If decrypting read salt from input BIO.
384              */
385             unsigned char *sptr;
386             size_t str_len = strlen(str);
387
388             if (nosalt)
389                 sptr = NULL;
390             else {
391                 if (enc) {
392                     if (hsalt) {
393                         if (!set_hex(hsalt, salt, sizeof salt)) {
394                             BIO_printf(bio_err, "invalid hex salt value\n");
395                             goto end;
396                         }
397                     } else if (RAND_bytes(salt, sizeof salt) <= 0)
398                         goto end;
399                     /*
400                      * If -P option then don't bother writing
401                      */
402                     if ((printkey != 2)
403                         && (BIO_write(wbio, magic,
404                                       sizeof magic - 1) != sizeof magic - 1
405                             || BIO_write(wbio,
406                                          (char *)salt,
407                                          sizeof salt) != sizeof salt)) {
408                         BIO_printf(bio_err, "error writing output file\n");
409                         goto end;
410                     }
411                 } else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf
412                            || BIO_read(rbio,
413                                        (unsigned char *)salt,
414                                        sizeof salt) != sizeof salt) {
415                     BIO_printf(bio_err, "error reading input file\n");
416                     goto end;
417                 } else if (memcmp(mbuf, magic, sizeof magic - 1)) {
418                     BIO_printf(bio_err, "bad magic number\n");
419                     goto end;
420                 }
421
422                 sptr = salt;
423             }
424
425             if (!EVP_BytesToKey(cipher, dgst, sptr,
426                                 (unsigned char *)str,
427                                 str_len, 1, key, iv)) {
428                 BIO_printf(bio_err, "EVP_BytesToKey failed\n");
429                 goto end;
430             }
431             /*
432              * zero the complete buffer or the string passed from the command
433              * line bug picked up by Larry J. Hughes Jr. <hughes@indiana.edu>
434              */
435             if (str == strbuf)
436                 OPENSSL_cleanse(str, SIZE);
437             else
438                 OPENSSL_cleanse(str, str_len);
439         }
440         if (hiv != NULL) {
441             int siz = EVP_CIPHER_iv_length(cipher);
442             if (siz == 0) {
443                 BIO_printf(bio_err, "warning: iv not use by this cipher\n");
444             } else if (!set_hex(hiv, iv, sizeof iv)) {
445                 BIO_printf(bio_err, "invalid hex iv value\n");
446                 goto end;
447             }
448         }
449         if ((hiv == NULL) && (str == NULL)
450             && EVP_CIPHER_iv_length(cipher) != 0) {
451             /*
452              * No IV was explicitly set and no IV was generated during
453              * EVP_BytesToKey. Hence the IV is undefined, making correct
454              * decryption impossible.
455              */
456             BIO_printf(bio_err, "iv undefined\n");
457             goto end;
458         }
459         if ((hkey != NULL) && !set_hex(hkey, key, EVP_CIPHER_key_length(cipher))) {
460             BIO_printf(bio_err, "invalid hex key value\n");
461             goto end;
462         }
463
464         if ((benc = BIO_new(BIO_f_cipher())) == NULL)
465             goto end;
466
467         /*
468          * Since we may be changing parameters work on the encryption context
469          * rather than calling BIO_set_cipher().
470          */
471
472         BIO_get_cipher_ctx(benc, &ctx);
473
474         if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc)) {
475             BIO_printf(bio_err, "Error setting cipher %s\n",
476                        EVP_CIPHER_name(cipher));
477             ERR_print_errors(bio_err);
478             goto end;
479         }
480
481         if (nopad)
482             EVP_CIPHER_CTX_set_padding(ctx, 0);
483
484         if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc)) {
485             BIO_printf(bio_err, "Error setting cipher %s\n",
486                        EVP_CIPHER_name(cipher));
487             ERR_print_errors(bio_err);
488             goto end;
489         }
490
491         if (debug) {
492             BIO_set_callback(benc, BIO_debug_callback);
493             BIO_set_callback_arg(benc, (char *)bio_err);
494         }
495
496         if (printkey) {
497             if (!nosalt) {
498                 printf("salt=");
499                 for (i = 0; i < (int)sizeof(salt); i++)
500                     printf("%02X", salt[i]);
501                 printf("\n");
502             }
503             if (EVP_CIPHER_key_length(cipher) > 0) {
504                 printf("key=");
505                 for (i = 0; i < EVP_CIPHER_key_length(cipher); i++)
506                     printf("%02X", key[i]);
507                 printf("\n");
508             }
509             if (EVP_CIPHER_iv_length(cipher) > 0) {
510                 printf("iv =");
511                 for (i = 0; i < EVP_CIPHER_iv_length(cipher); i++)
512                     printf("%02X", iv[i]);
513                 printf("\n");
514             }
515             if (printkey == 2) {
516                 ret = 0;
517                 goto end;
518             }
519         }
520     }
521
522     /* Only encrypt/decrypt as we write the file */
523     if (benc != NULL)
524         wbio = BIO_push(benc, wbio);
525
526     for (;;) {
527         inl = BIO_read(rbio, (char *)buff, bsize);
528         if (inl <= 0)
529             break;
530         if (BIO_write(wbio, (char *)buff, inl) != inl) {
531             BIO_printf(bio_err, "error writing output file\n");
532             goto end;
533         }
534     }
535     if (!BIO_flush(wbio)) {
536         BIO_printf(bio_err, "bad decrypt\n");
537         goto end;
538     }
539
540     ret = 0;
541     if (verbose) {
542         BIO_printf(bio_err, "bytes read   :%8"PRIu64"\n", BIO_number_read(in));
543         BIO_printf(bio_err, "bytes written:%8"PRIu64"\n", BIO_number_written(out));
544     }
545  end:
546     ERR_print_errors(bio_err);
547     OPENSSL_free(strbuf);
548     OPENSSL_free(buff);
549     BIO_free(in);
550     BIO_free_all(out);
551     BIO_free(benc);
552     BIO_free(b64);
553 #ifdef ZLIB
554     BIO_free(bzl);
555 #endif
556     release_engine(e);
557     OPENSSL_free(pass);
558     return (ret);
559 }
560
561 static void show_ciphers(const OBJ_NAME *name, void *bio_)
562 {
563     BIO *bio = bio_;
564     static int n;
565
566     if (!islower((unsigned char)*name->name))
567         return;
568
569     BIO_printf(bio, "-%-25s", name->name);
570     if (++n == 3) {
571         BIO_printf(bio, "\n");
572         n = 0;
573     } else
574         BIO_printf(bio, " ");
575 }
576
577 static int set_hex(char *in, unsigned char *out, int size)
578 {
579     int i, n;
580     unsigned char j;
581
582     n = strlen(in);
583     if (n > (size * 2)) {
584         BIO_printf(bio_err, "hex string is too long\n");
585         return (0);
586     }
587     memset(out, 0, size);
588     for (i = 0; i < n; i++) {
589         j = (unsigned char)*in;
590         *(in++) = '\0';
591         if (j == 0)
592             break;
593         if (!isxdigit(j)) {
594             BIO_printf(bio_err, "non-hex digit\n");
595             return (0);
596         }
597         j = (unsigned char)OPENSSL_hexchar2int(j);
598         if (i & 1)
599             out[i / 2] |= j;
600         else
601             out[i / 2] = (j << 4);
602     }
603     return (1);
604 }