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