[BACK]Return to enc.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / openssl

Annotation of src/usr.bin/openssl/enc.c, Revision 1.29

1.29    ! tb          1: /* $OpenBSD: enc.c,v 1.28 2023/06/11 05:45:20 tb Exp $ */
1.1       jsing       2: /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
                      3:  * All rights reserved.
                      4:  *
                      5:  * This package is an SSL implementation written
                      6:  * by Eric Young (eay@cryptsoft.com).
                      7:  * The implementation was written so as to conform with Netscapes SSL.
                      8:  *
                      9:  * This library is free for commercial and non-commercial use as long as
                     10:  * the following conditions are aheared to.  The following conditions
                     11:  * apply to all code found in this distribution, be it the RC4, RSA,
                     12:  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
                     13:  * included with this distribution is covered by the same copyright terms
                     14:  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
                     15:  *
                     16:  * Copyright remains Eric Young's, and as such any Copyright notices in
                     17:  * the code are not to be removed.
                     18:  * If this package is used in a product, Eric Young should be given attribution
                     19:  * as the author of the parts of the library used.
                     20:  * This can be in the form of a textual message at program startup or
                     21:  * in documentation (online or textual) provided with the package.
                     22:  *
                     23:  * Redistribution and use in source and binary forms, with or without
                     24:  * modification, are permitted provided that the following conditions
                     25:  * are met:
                     26:  * 1. Redistributions of source code must retain the copyright
                     27:  *    notice, this list of conditions and the following disclaimer.
                     28:  * 2. Redistributions in binary form must reproduce the above copyright
                     29:  *    notice, this list of conditions and the following disclaimer in the
                     30:  *    documentation and/or other materials provided with the distribution.
                     31:  * 3. All advertising materials mentioning features or use of this software
                     32:  *    must display the following acknowledgement:
                     33:  *    "This product includes cryptographic software written by
                     34:  *     Eric Young (eay@cryptsoft.com)"
                     35:  *    The word 'cryptographic' can be left out if the rouines from the library
                     36:  *    being used are not cryptographic related :-).
                     37:  * 4. If you include any Windows specific code (or a derivative thereof) from
                     38:  *    the apps directory (application code) you must include an acknowledgement:
                     39:  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
                     40:  *
                     41:  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
                     42:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     43:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     44:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
                     45:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     46:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     47:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     48:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     49:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     50:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     51:  * SUCH DAMAGE.
                     52:  *
                     53:  * The licence and distribution terms for any publically available version or
                     54:  * derivative of this code cannot be changed.  i.e. this code cannot simply be
                     55:  * copied and put under another distribution licence
                     56:  * [including the GNU Public Licence.]
                     57:  */
                     58:
                     59: #include <stdio.h>
                     60: #include <stdlib.h>
                     61: #include <string.h>
                     62:
                     63: #include "apps.h"
                     64:
                     65: #include <openssl/bio.h>
                     66: #include <openssl/comp.h>
                     67: #include <openssl/err.h>
                     68: #include <openssl/evp.h>
                     69: #include <openssl/objects.h>
                     70: #include <openssl/pem.h>
                     71: #include <openssl/x509.h>
                     72:
                     73: int set_hex(char *in, unsigned char *out, int size);
                     74:
                     75: #define SIZE   (512)
                     76: #define BSIZE  (8*1024)
1.4       jsing      77:
                     78: static struct {
                     79:        int base64;
                     80:        char *bufsize;
                     81:        const EVP_CIPHER *cipher;
                     82:        int debug;
                     83:        int enc;
                     84:        char *hiv;
                     85:        char *hkey;
                     86:        char *hsalt;
                     87:        char *inf;
1.20      jsing      88:        int iter;
1.4       jsing      89:        char *keyfile;
                     90:        char *keystr;
                     91:        char *md;
                     92:        int nopad;
                     93:        int nosalt;
                     94:        int olb64;
                     95:        char *outf;
                     96:        char *passarg;
1.20      jsing      97:        int pbkdf2;
1.4       jsing      98:        int printkey;
                     99:        int verbose;
1.27      tb        100: } cfg;
1.4       jsing     101:
                    102: static int
                    103: enc_opt_cipher(int argc, char **argv, int *argsused)
                    104: {
                    105:        char *name = argv[0];
                    106:
                    107:        if (*name++ != '-')
                    108:                return (1);
                    109:
                    110:        if (strcmp(name, "none") == 0) {
1.27      tb        111:                cfg.cipher = NULL;
1.4       jsing     112:                *argsused = 1;
                    113:                return (0);
                    114:        }
                    115:
1.27      tb        116:        if ((cfg.cipher = EVP_get_cipherbyname(name)) != NULL) {
1.4       jsing     117:                *argsused = 1;
                    118:                return (0);
                    119:        }
                    120:
                    121:        return (1);
                    122: }
                    123:
1.21      guenther  124: static const struct option enc_options[] = {
1.4       jsing     125:        {
                    126:                .name = "A",
                    127:                .desc = "Process base64 data on one line (requires -a)",
                    128:                .type = OPTION_FLAG,
1.27      tb        129:                .opt.flag = &cfg.olb64,
1.4       jsing     130:        },
                    131:        {
                    132:                .name = "a",
                    133:                .desc = "Perform base64 encoding/decoding (alias -base64)",
                    134:                .type = OPTION_FLAG,
1.27      tb        135:                .opt.flag = &cfg.base64,
1.4       jsing     136:        },
                    137:        {
                    138:                .name = "base64",
                    139:                .type = OPTION_FLAG,
1.27      tb        140:                .opt.flag = &cfg.base64,
1.4       jsing     141:        },
                    142:        {
                    143:                .name = "bufsize",
                    144:                .argname = "size",
                    145:                .desc = "Specify the buffer size to use for I/O",
                    146:                .type = OPTION_ARG,
1.27      tb        147:                .opt.arg = &cfg.bufsize,
1.4       jsing     148:        },
                    149:        {
                    150:                .name = "d",
                    151:                .desc = "Decrypt the input data",
                    152:                .type = OPTION_VALUE,
1.27      tb        153:                .opt.value = &cfg.enc,
1.4       jsing     154:                .value = 0,
                    155:        },
                    156:        {
                    157:                .name = "debug",
                    158:                .desc = "Print debugging information",
                    159:                .type = OPTION_FLAG,
1.27      tb        160:                .opt.flag = &cfg.debug,
1.4       jsing     161:        },
                    162:        {
                    163:                .name = "e",
                    164:                .desc = "Encrypt the input data (default)",
                    165:                .type = OPTION_VALUE,
1.27      tb        166:                .opt.value = &cfg.enc,
1.4       jsing     167:                .value = 1,
                    168:        },
                    169:        {
                    170:                .name = "in",
                    171:                .argname = "file",
                    172:                .desc = "Input file to read from (default stdin)",
                    173:                .type = OPTION_ARG,
1.27      tb        174:                .opt.arg = &cfg.inf,
1.4       jsing     175:        },
                    176:        {
1.16      naddy     177:                .name = "iter",
                    178:                .argname = "iterations",
                    179:                .desc = "Specify iteration count and force use of PBKDF2",
1.19      jsing     180:                .type = OPTION_ARG_INT,
1.27      tb        181:                .opt.value = &cfg.iter,
1.16      naddy     182:        },
                    183:        {
1.4       jsing     184:                .name = "iv",
                    185:                .argname = "IV",
1.11      jmc       186:                .desc = "IV to use, specified as a hexadecimal string",
1.4       jsing     187:                .type = OPTION_ARG,
1.27      tb        188:                .opt.arg = &cfg.hiv,
1.4       jsing     189:        },
                    190:        {
                    191:                .name = "K",
                    192:                .argname = "key",
1.11      jmc       193:                .desc = "Key to use, specified as a hexadecimal string",
1.4       jsing     194:                .type = OPTION_ARG,
1.27      tb        195:                .opt.arg = &cfg.hkey,
1.4       jsing     196:        },
                    197:        {
                    198:                .name = "k",            /* Superseded by -pass. */
                    199:                .type = OPTION_ARG,
1.27      tb        200:                .opt.arg = &cfg.keystr,
1.4       jsing     201:        },
                    202:        {
                    203:                .name = "kfile",        /* Superseded by -pass. */
                    204:                .type = OPTION_ARG,
1.27      tb        205:                .opt.arg = &cfg.keyfile,
1.4       jsing     206:        },
                    207:        {
                    208:                .name = "md",
                    209:                .argname = "digest",
                    210:                .desc = "Digest to use to create a key from the passphrase",
                    211:                .type = OPTION_ARG,
1.27      tb        212:                .opt.arg = &cfg.md,
1.4       jsing     213:        },
                    214:        {
                    215:                .name = "none",
                    216:                .desc = "Use NULL cipher (no encryption or decryption)",
                    217:                .type = OPTION_ARGV_FUNC,
                    218:                .opt.argvfunc = enc_opt_cipher,
                    219:        },
                    220:        {
                    221:                .name = "nopad",
                    222:                .desc = "Disable standard block padding",
                    223:                .type = OPTION_FLAG,
1.27      tb        224:                .opt.flag = &cfg.nopad,
1.4       jsing     225:        },
                    226:        {
                    227:                .name = "nosalt",
                    228:                .type = OPTION_VALUE,
1.27      tb        229:                .opt.value = &cfg.nosalt,
1.4       jsing     230:                .value = 1,
                    231:        },
                    232:        {
                    233:                .name = "out",
                    234:                .argname = "file",
                    235:                .desc = "Output file to write to (default stdout)",
                    236:                .type = OPTION_ARG,
1.27      tb        237:                .opt.arg = &cfg.outf,
1.4       jsing     238:        },
                    239:        {
                    240:                .name = "P",
                    241:                .desc = "Print out the salt, key and IV used, then exit\n"
                    242:                    "  (no encryption or decryption is performed)",
                    243:                .type = OPTION_VALUE,
1.27      tb        244:                .opt.value = &cfg.printkey,
1.4       jsing     245:                .value = 2,
                    246:        },
                    247:        {
                    248:                .name = "p",
                    249:                .desc = "Print out the salt, key and IV used",
                    250:                .type = OPTION_VALUE,
1.27      tb        251:                .opt.value = &cfg.printkey,
1.4       jsing     252:                .value = 1,
                    253:        },
                    254:        {
                    255:                .name = "pass",
                    256:                .argname = "source",
                    257:                .desc = "Password source",
                    258:                .type = OPTION_ARG,
1.27      tb        259:                .opt.arg = &cfg.passarg,
1.4       jsing     260:        },
                    261:        {
1.16      naddy     262:                .name = "pbkdf2",
                    263:                .desc = "Use the pbkdf2 key derivation function",
                    264:                .type = OPTION_FLAG,
1.27      tb        265:                .opt.flag = &cfg.pbkdf2,
1.16      naddy     266:        },
                    267:        {
1.4       jsing     268:                .name = "S",
                    269:                .argname = "salt",
1.11      jmc       270:                .desc = "Salt to use, specified as a hexadecimal string",
1.4       jsing     271:                .type = OPTION_ARG,
1.27      tb        272:                .opt.arg = &cfg.hsalt,
1.4       jsing     273:        },
                    274:        {
                    275:                .name = "salt",
                    276:                .desc = "Use a salt in the key derivation routines (default)",
                    277:                .type = OPTION_VALUE,
1.27      tb        278:                .opt.value = &cfg.nosalt,
1.4       jsing     279:                .value = 0,
                    280:        },
                    281:        {
                    282:                .name = "v",
                    283:                .desc = "Verbose",
                    284:                .type = OPTION_FLAG,
1.27      tb        285:                .opt.flag = &cfg.verbose,
1.4       jsing     286:        },
                    287:        {
                    288:                .name = NULL,
                    289:                .type = OPTION_ARGV_FUNC,
                    290:                .opt.argvfunc = enc_opt_cipher,
                    291:        },
                    292:        { NULL },
                    293: };
1.1       jsing     294:
                    295: static void
1.26      tb        296: skip_aead_and_xts(const OBJ_NAME *name, void *arg)
                    297: {
                    298:        const EVP_CIPHER *cipher;
                    299:
                    300:        if ((cipher = EVP_get_cipherbyname(name->name)) == NULL)
                    301:                return;
                    302:
                    303:        if ((EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0)
                    304:                return;
                    305:        if (EVP_CIPHER_mode(cipher) == EVP_CIPH_XTS_MODE)
                    306:                return;
                    307:
                    308:        show_cipher(name, arg);
                    309: }
                    310:
                    311: static void
1.4       jsing     312: enc_usage(void)
                    313: {
1.18      inoguchi  314:        int n = 0;
                    315:
1.4       jsing     316:        fprintf(stderr, "usage: enc -ciphername [-AadePp] [-base64] "
                    317:            "[-bufsize number] [-debug]\n"
1.16      naddy     318:            "    [-in file] [-iter iterations] [-iv IV] [-K key] "
                    319:             "[-k password]\n"
1.4       jsing     320:            "    [-kfile file] [-md digest] [-none] [-nopad] [-nosalt]\n"
1.16      naddy     321:            "    [-out file] [-pass source] [-pbkdf2] [-S salt] [-salt]\n\n");
1.4       jsing     322:        options_usage(enc_options);
                    323:        fprintf(stderr, "\n");
                    324:
                    325:        fprintf(stderr, "Valid ciphername values:\n\n");
1.26      tb        326:        OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, skip_aead_and_xts, &n);
1.4       jsing     327:        fprintf(stderr, "\n");
1.1       jsing     328: }
                    329:
                    330: int
                    331: enc_main(int argc, char **argv)
                    332: {
                    333:        static const char magic[] = "Salted__";
                    334:        char mbuf[sizeof magic - 1];
1.4       jsing     335:        char *strbuf = NULL, *pass = NULL;
                    336:        unsigned char *buff = NULL;
                    337:        int bsize = BSIZE;
1.1       jsing     338:        int ret = 1, inl;
                    339:        unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
                    340:        unsigned char salt[PKCS5_SALT_LEN];
                    341:        EVP_CIPHER_CTX *ctx = NULL;
1.4       jsing     342:        const EVP_MD *dgst = NULL;
                    343:        BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL;
                    344:        BIO *rbio = NULL, *wbio = NULL;
1.1       jsing     345: #define PROG_NAME_SIZE  39
                    346:        char pname[PROG_NAME_SIZE + 1];
1.4       jsing     347:        int i;
1.8       doug      348:
1.25      joshua    349:        if (pledge("stdio cpath wpath rpath tty", NULL) == -1) {
                    350:                perror("pledge");
                    351:                exit(1);
1.8       doug      352:        }
1.4       jsing     353:
1.27      tb        354:        memset(&cfg, 0, sizeof(cfg));
                    355:        cfg.enc = 1;
1.1       jsing     356:
                    357:        /* first check the program name */
1.4       jsing     358:        program_name(argv[0], pname, sizeof(pname));
                    359:
1.1       jsing     360:        if (strcmp(pname, "base64") == 0)
1.27      tb        361:                cfg.base64 = 1;
1.4       jsing     362:
1.27      tb        363:        cfg.cipher = EVP_get_cipherbyname(pname);
1.4       jsing     364:
1.29    ! tb        365:        if (!cfg.base64 && cfg.cipher == NULL && strcmp(pname, "enc") != 0) {
1.1       jsing     366:                BIO_printf(bio_err, "%s is an unknown cipher\n", pname);
1.4       jsing     367:                goto end;
                    368:        }
                    369:
                    370:        if (options_parse(argc, argv, enc_options, NULL, NULL) != 0) {
                    371:                enc_usage();
                    372:                goto end;
1.1       jsing     373:        }
1.4       jsing     374:
1.27      tb        375:        if (cfg.keyfile != NULL) {
1.4       jsing     376:                static char buf[128];
                    377:                FILE *infile;
                    378:
1.27      tb        379:                infile = fopen(cfg.keyfile, "r");
1.4       jsing     380:                if (infile == NULL) {
                    381:                        BIO_printf(bio_err, "unable to read key from '%s'\n",
1.27      tb        382:                            cfg.keyfile);
1.4       jsing     383:                        goto end;
1.1       jsing     384:                }
1.4       jsing     385:                buf[0] = '\0';
                    386:                if (!fgets(buf, sizeof buf, infile)) {
                    387:                        BIO_printf(bio_err, "unable to read key from '%s'\n",
1.27      tb        388:                            cfg.keyfile);
1.4       jsing     389:                        fclose(infile);
                    390:                        goto end;
1.1       jsing     391:                }
1.4       jsing     392:                fclose(infile);
                    393:                i = strlen(buf);
                    394:                if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r')))
                    395:                        buf[--i] = '\0';
                    396:                if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r')))
                    397:                        buf[--i] = '\0';
                    398:                if (i < 1) {
                    399:                        BIO_printf(bio_err, "zero length password\n");
1.1       jsing     400:                        goto end;
                    401:                }
1.27      tb        402:                cfg.keystr = buf;
1.26      tb        403:        }
                    404:
1.27      tb        405:        if (cfg.cipher != NULL &&
                    406:            (EVP_CIPHER_flags(cfg.cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0) {
1.26      tb        407:                BIO_printf(bio_err, "enc does not support AEAD ciphers\n");
                    408:                goto end;
                    409:        }
                    410:
1.27      tb        411:        if (cfg.cipher != NULL &&
                    412:            EVP_CIPHER_mode(cfg.cipher) == EVP_CIPH_XTS_MODE) {
1.26      tb        413:                BIO_printf(bio_err, "enc does not support XTS mode\n");
                    414:                goto end;
1.1       jsing     415:        }
                    416:
1.27      tb        417:        if (cfg.md != NULL &&
                    418:            (dgst = EVP_get_digestbyname(cfg.md)) == NULL) {
1.4       jsing     419:                BIO_printf(bio_err,
                    420:                    "%s is an unsupported message digest type\n",
1.27      tb        421:                    cfg.md);
1.1       jsing     422:                goto end;
                    423:        }
                    424:        if (dgst == NULL) {
1.15      beck      425:                dgst = EVP_sha256();
1.1       jsing     426:        }
1.4       jsing     427:
1.27      tb        428:        if (cfg.bufsize != NULL) {
                    429:                char *p = cfg.bufsize;
1.1       jsing     430:                unsigned long n;
                    431:
1.4       jsing     432:                /* XXX - provide an OPTION_ARG_DISKUNIT. */
                    433:                for (n = 0; *p != '\0'; p++) {
                    434:                        i = *p;
1.1       jsing     435:                        if ((i <= '9') && (i >= '0'))
                    436:                                n = n * 10 + i - '0';
                    437:                        else if (i == 'k') {
                    438:                                n *= 1024;
1.4       jsing     439:                                p++;
1.1       jsing     440:                                break;
                    441:                        }
                    442:                }
1.4       jsing     443:                if (*p != '\0') {
1.1       jsing     444:                        BIO_printf(bio_err, "invalid 'bufsize' specified.\n");
                    445:                        goto end;
                    446:                }
1.4       jsing     447:                /* It must be large enough for a base64 encoded line. */
1.27      tb        448:                if (cfg.base64 && n < 80)
1.1       jsing     449:                        n = 80;
                    450:
1.4       jsing     451:                bsize = (int)n;
1.27      tb        452:                if (cfg.verbose)
1.1       jsing     453:                        BIO_printf(bio_err, "bufsize=%d\n", bsize);
                    454:        }
                    455:        strbuf = malloc(SIZE);
                    456:        buff = malloc(EVP_ENCODE_LENGTH(bsize));
                    457:        if ((buff == NULL) || (strbuf == NULL)) {
                    458:                BIO_printf(bio_err, "malloc failure %ld\n", (long) EVP_ENCODE_LENGTH(bsize));
                    459:                goto end;
                    460:        }
                    461:        in = BIO_new(BIO_s_file());
                    462:        out = BIO_new(BIO_s_file());
                    463:        if ((in == NULL) || (out == NULL)) {
                    464:                ERR_print_errors(bio_err);
                    465:                goto end;
                    466:        }
1.27      tb        467:        if (cfg.debug) {
1.1       jsing     468:                BIO_set_callback(in, BIO_debug_callback);
                    469:                BIO_set_callback(out, BIO_debug_callback);
                    470:                BIO_set_callback_arg(in, (char *) bio_err);
                    471:                BIO_set_callback_arg(out, (char *) bio_err);
                    472:        }
1.27      tb        473:        if (cfg.inf == NULL) {
                    474:                if (cfg.bufsize != NULL)
1.1       jsing     475:                        setvbuf(stdin, (char *) NULL, _IONBF, 0);
                    476:                BIO_set_fp(in, stdin, BIO_NOCLOSE);
                    477:        } else {
1.27      tb        478:                if (BIO_read_filename(in, cfg.inf) <= 0) {
                    479:                        perror(cfg.inf);
1.1       jsing     480:                        goto end;
                    481:                }
                    482:        }
                    483:
1.27      tb        484:        if (!cfg.keystr && cfg.passarg) {
                    485:                if (!app_passwd(bio_err, cfg.passarg, NULL,
1.4       jsing     486:                    &pass, NULL)) {
1.1       jsing     487:                        BIO_printf(bio_err, "Error getting password\n");
                    488:                        goto end;
                    489:                }
1.27      tb        490:                cfg.keystr = pass;
1.1       jsing     491:        }
1.27      tb        492:        if (cfg.keystr == NULL && cfg.cipher != NULL &&
                    493:            cfg.hkey == NULL) {
1.1       jsing     494:                for (;;) {
                    495:                        char buf[200];
1.2       doug      496:                        int retval;
1.1       jsing     497:
1.4       jsing     498:                        retval = snprintf(buf, sizeof buf,
                    499:                            "enter %s %s password:",
1.27      tb        500:                            OBJ_nid2ln(EVP_CIPHER_nid(cfg.cipher)),
                    501:                            cfg.enc ? "encryption" : "decryption");
1.2       doug      502:                        if ((size_t)retval >= sizeof buf) {
1.4       jsing     503:                                BIO_printf(bio_err,
                    504:                                    "Password prompt too long\n");
1.1       jsing     505:                                goto end;
                    506:                        }
                    507:                        strbuf[0] = '\0';
1.4       jsing     508:                        i = EVP_read_pw_string((char *)strbuf, SIZE, buf,
1.27      tb        509:                            cfg.enc);
1.1       jsing     510:                        if (i == 0) {
                    511:                                if (strbuf[0] == '\0') {
                    512:                                        ret = 1;
                    513:                                        goto end;
                    514:                                }
1.27      tb        515:                                cfg.keystr = strbuf;
1.1       jsing     516:                                break;
                    517:                        }
                    518:                        if (i < 0) {
                    519:                                BIO_printf(bio_err, "bad password read\n");
                    520:                                goto end;
                    521:                        }
                    522:                }
                    523:        }
1.27      tb        524:        if (cfg.outf == NULL) {
1.1       jsing     525:                BIO_set_fp(out, stdout, BIO_NOCLOSE);
1.27      tb        526:                if (cfg.bufsize != NULL)
1.4       jsing     527:                        setvbuf(stdout, (char *)NULL, _IONBF, 0);
1.1       jsing     528:        } else {
1.27      tb        529:                if (BIO_write_filename(out, cfg.outf) <= 0) {
                    530:                        perror(cfg.outf);
1.1       jsing     531:                        goto end;
                    532:                }
                    533:        }
                    534:
                    535:        rbio = in;
                    536:        wbio = out;
                    537:
1.27      tb        538:        if (cfg.base64) {
1.1       jsing     539:                if ((b64 = BIO_new(BIO_f_base64())) == NULL)
                    540:                        goto end;
1.27      tb        541:                if (cfg.debug) {
1.1       jsing     542:                        BIO_set_callback(b64, BIO_debug_callback);
                    543:                        BIO_set_callback_arg(b64, (char *) bio_err);
                    544:                }
1.27      tb        545:                if (cfg.olb64)
1.1       jsing     546:                        BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1.27      tb        547:                if (cfg.enc)
1.1       jsing     548:                        wbio = BIO_push(b64, wbio);
                    549:                else
                    550:                        rbio = BIO_push(b64, rbio);
                    551:        }
1.27      tb        552:        if (cfg.cipher != NULL) {
1.1       jsing     553:                /*
1.4       jsing     554:                 * Note that keystr is NULL if a key was passed on the command
1.1       jsing     555:                 * line, so we get no salt in that case. Is this a bug?
                    556:                 */
1.27      tb        557:                if (cfg.keystr != NULL) {
1.1       jsing     558:                        /*
                    559:                         * Salt handling: if encrypting generate a salt and
                    560:                         * write to output BIO. If decrypting read salt from
                    561:                         * input BIO.
                    562:                         */
                    563:                        unsigned char *sptr;
1.27      tb        564:                        if (cfg.nosalt)
1.1       jsing     565:                                sptr = NULL;
                    566:                        else {
1.27      tb        567:                                if (cfg.enc) {
                    568:                                        if (cfg.hsalt) {
                    569:                                                if (!set_hex(cfg.hsalt, salt, sizeof salt)) {
1.1       jsing     570:                                                        BIO_printf(bio_err,
                    571:                                                            "invalid hex salt value\n");
                    572:                                                        goto end;
                    573:                                                }
1.3       jsing     574:                                        } else
                    575:                                                arc4random_buf(salt,
                    576:                                                    sizeof(salt));
1.1       jsing     577:                                        /*
                    578:                                         * If -P option then don't bother
                    579:                                         * writing
                    580:                                         */
1.27      tb        581:                                        if ((cfg.printkey != 2)
1.1       jsing     582:                                            && (BIO_write(wbio, magic,
                    583:                                                    sizeof magic - 1) != sizeof magic - 1
                    584:                                                || BIO_write(wbio,
                    585:                                                    (char *) salt,
                    586:                                                    sizeof salt) != sizeof salt)) {
                    587:                                                BIO_printf(bio_err, "error writing output file\n");
                    588:                                                goto end;
                    589:                                        }
                    590:                                } else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf
                    591:                                            || BIO_read(rbio,
                    592:                                                (unsigned char *) salt,
                    593:                                        sizeof salt) != sizeof salt) {
                    594:                                        BIO_printf(bio_err, "error reading input file\n");
                    595:                                        goto end;
                    596:                                } else if (memcmp(mbuf, magic, sizeof magic - 1)) {
                    597:                                        BIO_printf(bio_err, "bad magic number\n");
                    598:                                        goto end;
                    599:                                }
                    600:                                sptr = salt;
                    601:                        }
1.27      tb        602:                        if (cfg.pbkdf2 == 1 || cfg.iter > 0) {
1.15      beck      603:                                /*
                    604:                                 * derive key and default iv
                    605:                                 * concatenated into a temporary buffer
                    606:                                 */
                    607:                                unsigned char tmpkeyiv[EVP_MAX_KEY_LENGTH + EVP_MAX_IV_LENGTH];
1.27      tb        608:                                int iklen = EVP_CIPHER_key_length(cfg.cipher);
                    609:                                int ivlen = EVP_CIPHER_iv_length(cfg.cipher);
1.15      beck      610:                                /* not needed if HASH_UPDATE() is fixed : */
                    611:                                int islen = (sptr != NULL ? sizeof(salt) : 0);
                    612:
1.27      tb        613:                                if (cfg.iter == 0)
                    614:                                        cfg.iter = 10000;
1.15      beck      615:
1.27      tb        616:                                if (!PKCS5_PBKDF2_HMAC(cfg.keystr,
                    617:                                        strlen(cfg.keystr), sptr, islen,
                    618:                                        cfg.iter, dgst, iklen+ivlen, tmpkeyiv)) {
1.15      beck      619:                                        BIO_printf(bio_err, "PKCS5_PBKDF2_HMAC failed\n");
                    620:                                        goto end;
                    621:                                }
                    622:                                /* split and move data back to global buffer */
                    623:                                memcpy(key, tmpkeyiv, iklen);
1.22      bcook     624:                                memcpy(iv, tmpkeyiv + iklen, ivlen);
                    625:                                explicit_bzero(tmpkeyiv, sizeof tmpkeyiv);
1.15      beck      626:                        } else {
1.27      tb        627:                                EVP_BytesToKey(cfg.cipher, dgst, sptr,
                    628:                                    (unsigned char *)cfg.keystr,
                    629:                                    strlen(cfg.keystr), 1, key, iv);
1.15      beck      630:                        }
1.1       jsing     631:
                    632:                        /*
                    633:                         * zero the complete buffer or the string passed from
                    634:                         * the command line bug picked up by Larry J. Hughes
                    635:                         * Jr. <hughes@indiana.edu>
                    636:                         */
1.27      tb        637:                        if (cfg.keystr == strbuf)
                    638:                                explicit_bzero(cfg.keystr, SIZE);
1.1       jsing     639:                        else
1.27      tb        640:                                explicit_bzero(cfg.keystr,
                    641:                                    strlen(cfg.keystr));
1.1       jsing     642:                }
1.27      tb        643:                if (cfg.hiv != NULL &&
                    644:                    !set_hex(cfg.hiv, iv, sizeof iv)) {
1.1       jsing     645:                        BIO_printf(bio_err, "invalid hex iv value\n");
                    646:                        goto end;
                    647:                }
1.27      tb        648:                if (cfg.hiv == NULL && cfg.keystr == NULL &&
                    649:                    EVP_CIPHER_iv_length(cfg.cipher) != 0) {
1.1       jsing     650:                        /*
                    651:                         * No IV was explicitly set and no IV was generated
                    652:                         * during EVP_BytesToKey. Hence the IV is undefined,
                    653:                         * making correct decryption impossible.
                    654:                         */
                    655:                        BIO_printf(bio_err, "iv undefined\n");
                    656:                        goto end;
                    657:                }
1.27      tb        658:                if (cfg.hkey != NULL &&
                    659:                    !set_hex(cfg.hkey, key, sizeof key)) {
1.1       jsing     660:                        BIO_printf(bio_err, "invalid hex key value\n");
                    661:                        goto end;
                    662:                }
                    663:                if ((benc = BIO_new(BIO_f_cipher())) == NULL)
                    664:                        goto end;
                    665:
                    666:                /*
                    667:                 * Since we may be changing parameters work on the encryption
                    668:                 * context rather than calling BIO_set_cipher().
                    669:                 */
                    670:
                    671:                BIO_get_cipher_ctx(benc, &ctx);
                    672:
1.27      tb        673:                if (!EVP_CipherInit_ex(ctx, cfg.cipher, NULL, NULL,
                    674:                    NULL, cfg.enc)) {
1.1       jsing     675:                        BIO_printf(bio_err, "Error setting cipher %s\n",
1.27      tb        676:                            EVP_CIPHER_name(cfg.cipher));
1.1       jsing     677:                        ERR_print_errors(bio_err);
                    678:                        goto end;
                    679:                }
1.27      tb        680:                if (cfg.nopad)
1.1       jsing     681:                        EVP_CIPHER_CTX_set_padding(ctx, 0);
                    682:
1.4       jsing     683:                if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv,
1.27      tb        684:                    cfg.enc)) {
1.1       jsing     685:                        BIO_printf(bio_err, "Error setting cipher %s\n",
1.27      tb        686:                            EVP_CIPHER_name(cfg.cipher));
1.1       jsing     687:                        ERR_print_errors(bio_err);
                    688:                        goto end;
                    689:                }
1.27      tb        690:                if (cfg.debug) {
1.1       jsing     691:                        BIO_set_callback(benc, BIO_debug_callback);
                    692:                        BIO_set_callback_arg(benc, (char *) bio_err);
                    693:                }
1.27      tb        694:                if (cfg.printkey) {
1.24      tb        695:                        int key_len, iv_len;
                    696:
1.27      tb        697:                        if (!cfg.nosalt) {
1.1       jsing     698:                                printf("salt=");
                    699:                                for (i = 0; i < (int) sizeof(salt); i++)
                    700:                                        printf("%02X", salt[i]);
                    701:                                printf("\n");
                    702:                        }
1.27      tb        703:                        key_len = EVP_CIPHER_key_length(cfg.cipher);
1.24      tb        704:                        if (key_len > 0) {
1.1       jsing     705:                                printf("key=");
1.24      tb        706:                                for (i = 0; i < key_len; i++)
1.1       jsing     707:                                        printf("%02X", key[i]);
                    708:                                printf("\n");
                    709:                        }
1.27      tb        710:                        iv_len = EVP_CIPHER_iv_length(cfg.cipher);
1.24      tb        711:                        if (iv_len > 0) {
1.1       jsing     712:                                printf("iv =");
1.24      tb        713:                                for (i = 0; i < iv_len; i++)
1.1       jsing     714:                                        printf("%02X", iv[i]);
                    715:                                printf("\n");
                    716:                        }
1.27      tb        717:                        if (cfg.printkey == 2) {
1.1       jsing     718:                                ret = 0;
                    719:                                goto end;
                    720:                        }
                    721:                }
                    722:        }
                    723:        /* Only encrypt/decrypt as we write the file */
                    724:        if (benc != NULL)
                    725:                wbio = BIO_push(benc, wbio);
                    726:
                    727:        for (;;) {
                    728:                inl = BIO_read(rbio, (char *) buff, bsize);
                    729:                if (inl <= 0)
                    730:                        break;
                    731:                if (BIO_write(wbio, (char *) buff, inl) != inl) {
                    732:                        BIO_printf(bio_err, "error writing output file\n");
                    733:                        goto end;
                    734:                }
                    735:        }
                    736:        if (!BIO_flush(wbio)) {
                    737:                BIO_printf(bio_err, "bad decrypt\n");
                    738:                goto end;
                    739:        }
                    740:        ret = 0;
1.27      tb        741:        if (cfg.verbose) {
1.1       jsing     742:                BIO_printf(bio_err, "bytes read   :%8ld\n", BIO_number_read(in));
                    743:                BIO_printf(bio_err, "bytes written:%8ld\n", BIO_number_written(out));
                    744:        }
1.14      jsing     745:  end:
1.1       jsing     746:        ERR_print_errors(bio_err);
                    747:        free(strbuf);
                    748:        free(buff);
                    749:        BIO_free(in);
1.13      jsing     750:        BIO_free_all(out);
1.1       jsing     751:        BIO_free(benc);
                    752:        BIO_free(b64);
                    753:        free(pass);
                    754:
                    755:        return (ret);
                    756: }
                    757:
                    758: int
                    759: set_hex(char *in, unsigned char *out, int size)
                    760: {
                    761:        int i, n;
                    762:        unsigned char j;
                    763:
                    764:        n = strlen(in);
                    765:        if (n > (size * 2)) {
                    766:                BIO_printf(bio_err, "hex string is too long\n");
                    767:                return (0);
                    768:        }
                    769:        memset(out, 0, size);
                    770:        for (i = 0; i < n; i++) {
                    771:                j = (unsigned char) *in;
                    772:                *(in++) = '\0';
                    773:                if (j == 0)
                    774:                        break;
                    775:                if ((j >= '0') && (j <= '9'))
                    776:                        j -= '0';
                    777:                else if ((j >= 'A') && (j <= 'F'))
                    778:                        j = j - 'A' + 10;
                    779:                else if ((j >= 'a') && (j <= 'f'))
                    780:                        j = j - 'a' + 10;
                    781:                else {
                    782:                        BIO_printf(bio_err, "non-hex digit\n");
                    783:                        return (0);
                    784:                }
                    785:                if (i & 1)
                    786:                        out[i / 2] |= j;
                    787:                else
                    788:                        out[i / 2] = (j << 4);
                    789:        }
                    790:        return (1);
                    791: }