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