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