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