Make ca command silently use default if .attr file does not exist
[openssl.git] / apps / pkeyutl.c
1 /*
2  * Copyright 2006-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 "apps.h"
11 #include "progs.h"
12 #include <string.h>
13 #include <openssl/err.h>
14 #include <openssl/pem.h>
15 #include <openssl/evp.h>
16
17 #define KEY_NONE        0
18 #define KEY_PRIVKEY     1
19 #define KEY_PUBKEY      2
20 #define KEY_CERT        3
21
22 static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize,
23                               const char *keyfile, int keyform, int key_type,
24                               char *passinarg, int pkey_op, ENGINE *e,
25                               const int impl);
26
27 static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file,
28                       ENGINE *e);
29
30 static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op,
31                     unsigned char *out, size_t *poutlen,
32                     const unsigned char *in, size_t inlen);
33
34 typedef enum OPTION_choice {
35     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
36     OPT_ENGINE, OPT_ENGINE_IMPL, OPT_IN, OPT_OUT,
37     OPT_PUBIN, OPT_CERTIN, OPT_ASN1PARSE, OPT_HEXDUMP, OPT_SIGN,
38     OPT_VERIFY, OPT_VERIFYRECOVER, OPT_REV, OPT_ENCRYPT, OPT_DECRYPT,
39     OPT_DERIVE, OPT_SIGFILE, OPT_INKEY, OPT_PEERKEY, OPT_PASSIN,
40     OPT_PEERFORM, OPT_KEYFORM, OPT_PKEYOPT, OPT_PKEYOPT_PASSIN, OPT_KDF,
41     OPT_KDFLEN, OPT_R_ENUM
42 } OPTION_CHOICE;
43
44 const OPTIONS pkeyutl_options[] = {
45     {"help", OPT_HELP, '-', "Display this summary"},
46     {"in", OPT_IN, '<', "Input file - default stdin"},
47     {"out", OPT_OUT, '>', "Output file - default stdout"},
48     {"pubin", OPT_PUBIN, '-', "Input is a public key"},
49     {"certin", OPT_CERTIN, '-', "Input is a cert with a public key"},
50     {"asn1parse", OPT_ASN1PARSE, '-', "asn1parse the output data"},
51     {"hexdump", OPT_HEXDUMP, '-', "Hex dump output"},
52     {"sign", OPT_SIGN, '-', "Sign input data with private key"},
53     {"verify", OPT_VERIFY, '-', "Verify with public key"},
54     {"verifyrecover", OPT_VERIFYRECOVER, '-',
55      "Verify with public key, recover original data"},
56     {"rev", OPT_REV, '-', "Reverse the order of the input buffer"},
57     {"encrypt", OPT_ENCRYPT, '-', "Encrypt input data with public key"},
58     {"decrypt", OPT_DECRYPT, '-', "Decrypt input data with private key"},
59     {"derive", OPT_DERIVE, '-', "Derive shared secret"},
60     {"kdf", OPT_KDF, 's', "Use KDF algorithm"},
61     {"kdflen", OPT_KDFLEN, 'p', "KDF algorithm output length"},
62     {"sigfile", OPT_SIGFILE, '<', "Signature file (verify operation only)"},
63     {"inkey", OPT_INKEY, 's', "Input private key file"},
64     {"peerkey", OPT_PEERKEY, 's', "Peer key file used in key derivation"},
65     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
66     {"peerform", OPT_PEERFORM, 'E', "Peer key format - default PEM"},
67     {"keyform", OPT_KEYFORM, 'E', "Private key format - default PEM"},
68     {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
69     {"pkeyopt_passin", OPT_PKEYOPT_PASSIN, 's',
70      "Public key option that is read as a passphrase argument opt:passphrase"},
71     OPT_R_OPTIONS,
72 #ifndef OPENSSL_NO_ENGINE
73     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
74     {"engine_impl", OPT_ENGINE_IMPL, '-',
75      "Also use engine given by -engine for crypto operations"},
76 #endif
77     {NULL}
78 };
79
80 int pkeyutl_main(int argc, char **argv)
81 {
82     BIO *in = NULL, *out = NULL;
83     ENGINE *e = NULL;
84     EVP_PKEY_CTX *ctx = NULL;
85     char *infile = NULL, *outfile = NULL, *sigfile = NULL, *passinarg = NULL;
86     char hexdump = 0, asn1parse = 0, rev = 0, *prog;
87     unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL;
88     OPTION_CHOICE o;
89     int buf_inlen = 0, siglen = -1, keyform = FORMAT_PEM, peerform = FORMAT_PEM;
90     int keysize = -1, pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY;
91     int engine_impl = 0;
92     int ret = 1, rv = -1;
93     size_t buf_outlen;
94     const char *inkey = NULL;
95     const char *peerkey = NULL;
96     const char *kdfalg = NULL;
97     int kdflen = 0;
98     STACK_OF(OPENSSL_STRING) *pkeyopts = NULL;
99     STACK_OF(OPENSSL_STRING) *pkeyopts_passin = NULL;
100
101     prog = opt_init(argc, argv, pkeyutl_options);
102     while ((o = opt_next()) != OPT_EOF) {
103         switch (o) {
104         case OPT_EOF:
105         case OPT_ERR:
106  opthelp:
107             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
108             goto end;
109         case OPT_HELP:
110             opt_help(pkeyutl_options);
111             ret = 0;
112             goto end;
113         case OPT_IN:
114             infile = opt_arg();
115             break;
116         case OPT_OUT:
117             outfile = opt_arg();
118             break;
119         case OPT_SIGFILE:
120             sigfile = opt_arg();
121             break;
122         case OPT_ENGINE_IMPL:
123             engine_impl = 1;
124             break;
125         case OPT_INKEY:
126             inkey = opt_arg();
127             break;
128         case OPT_PEERKEY:
129             peerkey = opt_arg();
130             break;
131         case OPT_PASSIN:
132             passinarg = opt_arg();
133             break;
134         case OPT_PEERFORM:
135             if (!opt_format(opt_arg(), OPT_FMT_PDE, &peerform))
136                 goto opthelp;
137             break;
138         case OPT_KEYFORM:
139             if (!opt_format(opt_arg(), OPT_FMT_PDE, &keyform))
140                 goto opthelp;
141             break;
142         case OPT_R_CASES:
143             if (!opt_rand(o))
144                 goto end;
145             break;
146         case OPT_ENGINE:
147             e = setup_engine(opt_arg(), 0);
148             break;
149         case OPT_PUBIN:
150             key_type = KEY_PUBKEY;
151             break;
152         case OPT_CERTIN:
153             key_type = KEY_CERT;
154             break;
155         case OPT_ASN1PARSE:
156             asn1parse = 1;
157             break;
158         case OPT_HEXDUMP:
159             hexdump = 1;
160             break;
161         case OPT_SIGN:
162             pkey_op = EVP_PKEY_OP_SIGN;
163             break;
164         case OPT_VERIFY:
165             pkey_op = EVP_PKEY_OP_VERIFY;
166             break;
167         case OPT_VERIFYRECOVER:
168             pkey_op = EVP_PKEY_OP_VERIFYRECOVER;
169             break;
170         case OPT_ENCRYPT:
171             pkey_op = EVP_PKEY_OP_ENCRYPT;
172             break;
173         case OPT_DECRYPT:
174             pkey_op = EVP_PKEY_OP_DECRYPT;
175             break;
176         case OPT_DERIVE:
177             pkey_op = EVP_PKEY_OP_DERIVE;
178             break;
179         case OPT_KDF:
180             pkey_op = EVP_PKEY_OP_DERIVE;
181             key_type = KEY_NONE;
182             kdfalg = opt_arg();
183             break;
184         case OPT_KDFLEN:
185             kdflen = atoi(opt_arg());
186             break;
187         case OPT_REV:
188             rev = 1;
189             break;
190         case OPT_PKEYOPT:
191             if ((pkeyopts == NULL &&
192                  (pkeyopts = sk_OPENSSL_STRING_new_null()) == NULL) ||
193                 sk_OPENSSL_STRING_push(pkeyopts, opt_arg()) == 0) {
194                 BIO_puts(bio_err, "out of memory\n");
195                 goto end;
196             }
197             break;
198         case OPT_PKEYOPT_PASSIN:
199             if ((pkeyopts_passin == NULL &&
200                  (pkeyopts_passin = sk_OPENSSL_STRING_new_null()) == NULL) ||
201                 sk_OPENSSL_STRING_push(pkeyopts_passin, opt_arg()) == 0) {
202                 BIO_puts(bio_err, "out of memory\n");
203                 goto end;
204             }
205             break;
206         }
207     }
208     argc = opt_num_rest();
209     if (argc != 0)
210         goto opthelp;
211
212     if (kdfalg != NULL) {
213         if (kdflen == 0) {
214             BIO_printf(bio_err,
215                        "%s: no KDF length given (-kdflen parameter).\n", prog);
216             goto opthelp;
217         }
218     } else if (inkey == NULL) {
219         BIO_printf(bio_err,
220                    "%s: no private key given (-inkey parameter).\n", prog);
221         goto opthelp;
222     } else if (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE) {
223         BIO_printf(bio_err,
224                    "%s: no peer key given (-peerkey parameter).\n", prog);
225         goto opthelp;
226     }
227     ctx = init_ctx(kdfalg, &keysize, inkey, keyform, key_type,
228                    passinarg, pkey_op, e, engine_impl);
229     if (ctx == NULL) {
230         BIO_printf(bio_err, "%s: Error initializing context\n", prog);
231         ERR_print_errors(bio_err);
232         goto end;
233     }
234     if (peerkey != NULL && !setup_peer(ctx, peerform, peerkey, e)) {
235         BIO_printf(bio_err, "%s: Error setting up peer key\n", prog);
236         ERR_print_errors(bio_err);
237         goto end;
238     }
239     if (pkeyopts != NULL) {
240         int num = sk_OPENSSL_STRING_num(pkeyopts);
241         int i;
242
243         for (i = 0; i < num; ++i) {
244             const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i);
245
246             if (pkey_ctrl_string(ctx, opt) <= 0) {
247                 BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n",
248                            prog, opt);
249                 ERR_print_errors(bio_err);
250                 goto end;
251             }
252         }
253     }
254     if (pkeyopts_passin != NULL) {
255         int num = sk_OPENSSL_STRING_num(pkeyopts_passin);
256         int i;
257
258         for (i = 0; i < num; i++) {
259             char *opt = sk_OPENSSL_STRING_value(pkeyopts_passin, i);
260             char *passin = strchr(opt, ':');
261             char *passwd;
262
263             if (passin == NULL) {
264                 /* Get password interactively */
265                 char passwd_buf[4096];
266                 BIO_snprintf(passwd_buf, sizeof(passwd_buf), "Enter %s: ", opt);
267                 EVP_read_pw_string(passwd_buf, sizeof(passwd_buf) - 1,
268                                    passwd_buf, 0);
269                 passwd = OPENSSL_strdup(passwd_buf);
270                 if (passwd == NULL) {
271                     BIO_puts(bio_err, "out of memory\n");
272                     goto end;
273                 }
274             } else {
275                 /* Get password as a passin argument: First split option name
276                  * and passphrase argument into two strings */
277                 *passin = 0;
278                 passin++;
279                 if (app_passwd(passin, NULL, &passwd, NULL) == 0) {
280                     BIO_printf(bio_err, "failed to get '%s'\n", opt);
281                     goto end;
282                 }
283             }
284
285             if (EVP_PKEY_CTX_ctrl_str(ctx, opt, passwd) <= 0) {
286                 BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n",
287                            prog, opt);
288                 goto end;
289             }
290             OPENSSL_free(passwd);
291         }
292     }
293
294     if (sigfile != NULL && (pkey_op != EVP_PKEY_OP_VERIFY)) {
295         BIO_printf(bio_err,
296                    "%s: Signature file specified for non verify\n", prog);
297         goto end;
298     }
299
300     if (sigfile == NULL && (pkey_op == EVP_PKEY_OP_VERIFY)) {
301         BIO_printf(bio_err,
302                    "%s: No signature file specified for verify\n", prog);
303         goto end;
304     }
305
306     if (pkey_op != EVP_PKEY_OP_DERIVE) {
307         in = bio_open_default(infile, 'r', FORMAT_BINARY);
308         if (in == NULL)
309             goto end;
310     }
311     out = bio_open_default(outfile, 'w', FORMAT_BINARY);
312     if (out == NULL)
313         goto end;
314
315     if (sigfile != NULL) {
316         BIO *sigbio = BIO_new_file(sigfile, "rb");
317
318         if (sigbio == NULL) {
319             BIO_printf(bio_err, "Can't open signature file %s\n", sigfile);
320             goto end;
321         }
322         siglen = bio_to_mem(&sig, keysize * 10, sigbio);
323         BIO_free(sigbio);
324         if (siglen < 0) {
325             BIO_printf(bio_err, "Error reading signature data\n");
326             goto end;
327         }
328     }
329
330     if (in != NULL) {
331         /* Read the input data */
332         buf_inlen = bio_to_mem(&buf_in, keysize * 10, in);
333         if (buf_inlen < 0) {
334             BIO_printf(bio_err, "Error reading input Data\n");
335             goto end;
336         }
337         if (rev) {
338             size_t i;
339             unsigned char ctmp;
340             size_t l = (size_t)buf_inlen;
341             for (i = 0; i < l / 2; i++) {
342                 ctmp = buf_in[i];
343                 buf_in[i] = buf_in[l - 1 - i];
344                 buf_in[l - 1 - i] = ctmp;
345             }
346         }
347     }
348
349     /* Sanity check the input */
350     if (buf_inlen > EVP_MAX_MD_SIZE
351             && (pkey_op == EVP_PKEY_OP_SIGN
352                 || pkey_op == EVP_PKEY_OP_VERIFY
353                 || pkey_op == EVP_PKEY_OP_VERIFYRECOVER)) {
354         BIO_printf(bio_err,
355                    "Error: The input data looks too long to be a hash\n");
356         goto end;
357     }
358
359     if (pkey_op == EVP_PKEY_OP_VERIFY) {
360         rv = EVP_PKEY_verify(ctx, sig, (size_t)siglen,
361                              buf_in, (size_t)buf_inlen);
362         if (rv == 1) {
363             BIO_puts(out, "Signature Verified Successfully\n");
364             ret = 0;
365         } else {
366             BIO_puts(out, "Signature Verification Failure\n");
367         }
368         goto end;
369     }
370     if (kdflen != 0) {
371         buf_outlen = kdflen;
372         rv = 1;
373     } else {
374         rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen,
375                       buf_in, (size_t)buf_inlen);
376     }
377     if (rv > 0 && buf_outlen != 0) {
378         buf_out = app_malloc(buf_outlen, "buffer output");
379         rv = do_keyop(ctx, pkey_op,
380                       buf_out, (size_t *)&buf_outlen,
381                       buf_in, (size_t)buf_inlen);
382     }
383     if (rv <= 0) {
384         if (pkey_op != EVP_PKEY_OP_DERIVE) {
385             BIO_puts(bio_err, "Public Key operation error\n");
386         } else {
387             BIO_puts(bio_err, "Key derivation failed\n");
388         }
389         ERR_print_errors(bio_err);
390         goto end;
391     }
392     ret = 0;
393
394     if (asn1parse) {
395         if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1))
396             ERR_print_errors(bio_err);
397     } else if (hexdump) {
398         BIO_dump(out, (char *)buf_out, buf_outlen);
399     } else {
400         BIO_write(out, buf_out, buf_outlen);
401     }
402
403  end:
404     EVP_PKEY_CTX_free(ctx);
405     release_engine(e);
406     BIO_free(in);
407     BIO_free_all(out);
408     OPENSSL_free(buf_in);
409     OPENSSL_free(buf_out);
410     OPENSSL_free(sig);
411     sk_OPENSSL_STRING_free(pkeyopts);
412     sk_OPENSSL_STRING_free(pkeyopts_passin);
413     return ret;
414 }
415
416 static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize,
417                               const char *keyfile, int keyform, int key_type,
418                               char *passinarg, int pkey_op, ENGINE *e,
419                               const int engine_impl)
420 {
421     EVP_PKEY *pkey = NULL;
422     EVP_PKEY_CTX *ctx = NULL;
423     ENGINE *impl = NULL;
424     char *passin = NULL;
425     int rv = -1;
426     X509 *x;
427     if (((pkey_op == EVP_PKEY_OP_SIGN) || (pkey_op == EVP_PKEY_OP_DECRYPT)
428          || (pkey_op == EVP_PKEY_OP_DERIVE))
429         && (key_type != KEY_PRIVKEY && kdfalg == NULL)) {
430         BIO_printf(bio_err, "A private key is needed for this operation\n");
431         goto end;
432     }
433     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
434         BIO_printf(bio_err, "Error getting password\n");
435         goto end;
436     }
437     switch (key_type) {
438     case KEY_PRIVKEY:
439         pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
440         break;
441
442     case KEY_PUBKEY:
443         pkey = load_pubkey(keyfile, keyform, 0, NULL, e, "Public Key");
444         break;
445
446     case KEY_CERT:
447         x = load_cert(keyfile, keyform, "Certificate");
448         if (x) {
449             pkey = X509_get_pubkey(x);
450             X509_free(x);
451         }
452         break;
453
454     case KEY_NONE:
455         break;
456
457     }
458
459 #ifndef OPENSSL_NO_ENGINE
460     if (engine_impl)
461         impl = e;
462 #endif
463
464     if (kdfalg != NULL) {
465         int kdfnid = OBJ_sn2nid(kdfalg);
466
467         if (kdfnid == NID_undef) {
468             kdfnid = OBJ_ln2nid(kdfalg);
469             if (kdfnid == NID_undef) {
470                 BIO_printf(bio_err, "The given KDF \"%s\" is unknown.\n",
471                            kdfalg);
472                 goto end;
473             }
474         }
475         ctx = EVP_PKEY_CTX_new_id(kdfnid, impl);
476     } else {
477         if (pkey == NULL)
478             goto end;
479         *pkeysize = EVP_PKEY_size(pkey);
480         ctx = EVP_PKEY_CTX_new(pkey, impl);
481         EVP_PKEY_free(pkey);
482     }
483
484     if (ctx == NULL)
485         goto end;
486
487     switch (pkey_op) {
488     case EVP_PKEY_OP_SIGN:
489         rv = EVP_PKEY_sign_init(ctx);
490         break;
491
492     case EVP_PKEY_OP_VERIFY:
493         rv = EVP_PKEY_verify_init(ctx);
494         break;
495
496     case EVP_PKEY_OP_VERIFYRECOVER:
497         rv = EVP_PKEY_verify_recover_init(ctx);
498         break;
499
500     case EVP_PKEY_OP_ENCRYPT:
501         rv = EVP_PKEY_encrypt_init(ctx);
502         break;
503
504     case EVP_PKEY_OP_DECRYPT:
505         rv = EVP_PKEY_decrypt_init(ctx);
506         break;
507
508     case EVP_PKEY_OP_DERIVE:
509         rv = EVP_PKEY_derive_init(ctx);
510         break;
511     }
512
513     if (rv <= 0) {
514         EVP_PKEY_CTX_free(ctx);
515         ctx = NULL;
516     }
517
518  end:
519     OPENSSL_free(passin);
520     return ctx;
521
522 }
523
524 static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file,
525                       ENGINE *e)
526 {
527     EVP_PKEY *peer = NULL;
528     ENGINE *engine = NULL;
529     int ret;
530
531     if (peerform == FORMAT_ENGINE)
532         engine = e;
533     peer = load_pubkey(file, peerform, 0, NULL, engine, "Peer Key");
534     if (peer == NULL) {
535         BIO_printf(bio_err, "Error reading peer key %s\n", file);
536         ERR_print_errors(bio_err);
537         return 0;
538     }
539
540     ret = EVP_PKEY_derive_set_peer(ctx, peer);
541
542     EVP_PKEY_free(peer);
543     if (ret <= 0)
544         ERR_print_errors(bio_err);
545     return ret;
546 }
547
548 static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op,
549                     unsigned char *out, size_t *poutlen,
550                     const unsigned char *in, size_t inlen)
551 {
552     int rv = 0;
553     switch (pkey_op) {
554     case EVP_PKEY_OP_VERIFYRECOVER:
555         rv = EVP_PKEY_verify_recover(ctx, out, poutlen, in, inlen);
556         break;
557
558     case EVP_PKEY_OP_SIGN:
559         rv = EVP_PKEY_sign(ctx, out, poutlen, in, inlen);
560         break;
561
562     case EVP_PKEY_OP_ENCRYPT:
563         rv = EVP_PKEY_encrypt(ctx, out, poutlen, in, inlen);
564         break;
565
566     case EVP_PKEY_OP_DECRYPT:
567         rv = EVP_PKEY_decrypt(ctx, out, poutlen, in, inlen);
568         break;
569
570     case EVP_PKEY_OP_DERIVE:
571         rv = EVP_PKEY_derive(ctx, out, poutlen);
572         break;
573
574     }
575     return rv;
576 }