Fix provider cipher reinit after init/update with a partial update block.
[openssl.git] / apps / pkeyutl.c
1 /*
2  * Copyright 2006-2020 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 #include <sys/stat.h>
17
18 DEFINE_STACK_OF_STRING()
19
20 #define KEY_NONE        0
21 #define KEY_PRIVKEY     1
22 #define KEY_PUBKEY      2
23 #define KEY_CERT        3
24
25 static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize,
26                               const char *keyfile, int keyform, int key_type,
27                               char *passinarg, int pkey_op, ENGINE *e,
28                               const int impl, int rawin, EVP_PKEY **ppkey,
29                               OPENSSL_CTX *libctx, const char *propq);
30
31 static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file,
32                       ENGINE *e);
33
34 static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op,
35                     unsigned char *out, size_t *poutlen,
36                     const unsigned char *in, size_t inlen);
37
38 static int do_raw_keyop(int pkey_op, EVP_PKEY_CTX *ctx,
39                         const EVP_MD *md, EVP_PKEY *pkey, BIO *in,
40                         int filesize, unsigned char *sig, int siglen,
41                         unsigned char **out, size_t *poutlen);
42
43 typedef enum OPTION_choice {
44     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
45     OPT_ENGINE, OPT_ENGINE_IMPL, OPT_IN, OPT_OUT,
46     OPT_PUBIN, OPT_CERTIN, OPT_ASN1PARSE, OPT_HEXDUMP, OPT_SIGN,
47     OPT_VERIFY, OPT_VERIFYRECOVER, OPT_REV, OPT_ENCRYPT, OPT_DECRYPT,
48     OPT_DERIVE, OPT_SIGFILE, OPT_INKEY, OPT_PEERKEY, OPT_PASSIN,
49     OPT_PEERFORM, OPT_KEYFORM, OPT_PKEYOPT, OPT_PKEYOPT_PASSIN, OPT_KDF,
50     OPT_KDFLEN, OPT_R_ENUM, OPT_PROV_ENUM,
51     OPT_CONFIG,
52     OPT_RAWIN, OPT_DIGEST
53 } OPTION_CHOICE;
54
55 const OPTIONS pkeyutl_options[] = {
56     OPT_SECTION("General"),
57     {"help", OPT_HELP, '-', "Display this summary"},
58 #ifndef OPENSSL_NO_ENGINE
59     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
60     {"engine_impl", OPT_ENGINE_IMPL, '-',
61      "Also use engine given by -engine for crypto operations"},
62 #endif
63     {"sign", OPT_SIGN, '-', "Sign input data with private key"},
64     {"verify", OPT_VERIFY, '-', "Verify with public key"},
65     {"encrypt", OPT_ENCRYPT, '-', "Encrypt input data with public key"},
66     {"decrypt", OPT_DECRYPT, '-', "Decrypt input data with private key"},
67     {"derive", OPT_DERIVE, '-', "Derive shared secret"},
68     OPT_CONFIG_OPTION,
69
70     OPT_SECTION("Input"),
71     {"in", OPT_IN, '<', "Input file - default stdin"},
72     {"rawin", OPT_RAWIN, '-', "Indicate the input data is in raw form"},
73     {"pubin", OPT_PUBIN, '-', "Input is a public key"},
74     {"inkey", OPT_INKEY, 's', "Input private key file"},
75     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
76     {"peerkey", OPT_PEERKEY, 's', "Peer key file used in key derivation"},
77     {"peerform", OPT_PEERFORM, 'E', "Peer key format (DER/PEM/P12/ENGINE)"},
78     {"certin", OPT_CERTIN, '-', "Input is a cert with a public key"},
79     {"rev", OPT_REV, '-', "Reverse the order of the input buffer"},
80     {"sigfile", OPT_SIGFILE, '<', "Signature file (verify operation only)"},
81     {"keyform", OPT_KEYFORM, 'E', "Private key format (ENGINE, other values ignored)"},
82
83     OPT_SECTION("Output"),
84     {"out", OPT_OUT, '>', "Output file - default stdout"},
85     {"asn1parse", OPT_ASN1PARSE, '-', "asn1parse the output data"},
86     {"hexdump", OPT_HEXDUMP, '-', "Hex dump output"},
87     {"verifyrecover", OPT_VERIFYRECOVER, '-',
88      "Verify with public key, recover original data"},
89
90     OPT_SECTION("Signing/Derivation"),
91     {"digest", OPT_DIGEST, 's',
92      "Specify the digest algorithm when signing the raw input data"},
93     {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
94     {"pkeyopt_passin", OPT_PKEYOPT_PASSIN, 's',
95      "Public key option that is read as a passphrase argument opt:passphrase"},
96     {"kdf", OPT_KDF, 's', "Use KDF algorithm"},
97     {"kdflen", OPT_KDFLEN, 'p', "KDF algorithm output length"},
98
99     OPT_R_OPTIONS,
100     OPT_PROV_OPTIONS,
101     {NULL}
102 };
103
104 int pkeyutl_main(int argc, char **argv)
105 {
106     CONF *conf = NULL;
107     BIO *in = NULL, *out = NULL;
108     ENGINE *e = NULL;
109     EVP_PKEY_CTX *ctx = NULL;
110     EVP_PKEY *pkey = NULL;
111     char *infile = NULL, *outfile = NULL, *sigfile = NULL, *passinarg = NULL;
112     char hexdump = 0, asn1parse = 0, rev = 0, *prog;
113     unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL;
114     OPTION_CHOICE o;
115     int buf_inlen = 0, siglen = -1, keyform = FORMAT_PEM, peerform = FORMAT_PEM;
116     int keysize = -1, pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY;
117     int engine_impl = 0;
118     int ret = 1, rv = -1;
119     size_t buf_outlen;
120     const char *inkey = NULL;
121     const char *peerkey = NULL;
122     const char *kdfalg = NULL;
123     int kdflen = 0;
124     STACK_OF(OPENSSL_STRING) *pkeyopts = NULL;
125     STACK_OF(OPENSSL_STRING) *pkeyopts_passin = NULL;
126     int rawin = 0;
127     const EVP_MD *md = NULL;
128     int filesize = -1;
129     OPENSSL_CTX *libctx = app_get0_libctx();
130     const char *propq = NULL;
131
132     prog = opt_init(argc, argv, pkeyutl_options);
133     while ((o = opt_next()) != OPT_EOF) {
134         switch (o) {
135         case OPT_EOF:
136         case OPT_ERR:
137  opthelp:
138             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
139             goto end;
140         case OPT_HELP:
141             opt_help(pkeyutl_options);
142             ret = 0;
143             goto end;
144         case OPT_IN:
145             infile = opt_arg();
146             break;
147         case OPT_OUT:
148             outfile = opt_arg();
149             break;
150         case OPT_SIGFILE:
151             sigfile = opt_arg();
152             break;
153         case OPT_ENGINE_IMPL:
154             engine_impl = 1;
155             break;
156         case OPT_INKEY:
157             inkey = opt_arg();
158             break;
159         case OPT_PEERKEY:
160             peerkey = opt_arg();
161             break;
162         case OPT_PASSIN:
163             passinarg = opt_arg();
164             break;
165         case OPT_PEERFORM:
166             if (!opt_format(opt_arg(), OPT_FMT_ANY, &peerform))
167                 goto opthelp;
168             break;
169         case OPT_KEYFORM:
170             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
171                 goto opthelp;
172             break;
173         case OPT_R_CASES:
174             if (!opt_rand(o))
175                 goto end;
176             break;
177         case OPT_CONFIG:
178             conf = app_load_config_modules(opt_arg());
179             if (conf == NULL)
180                 goto end;
181             break;
182         case OPT_PROV_CASES:
183             if (!opt_provider(o))
184                 goto end;
185             break;
186         case OPT_ENGINE:
187             e = setup_engine(opt_arg(), 0);
188             break;
189         case OPT_PUBIN:
190             key_type = KEY_PUBKEY;
191             break;
192         case OPT_CERTIN:
193             key_type = KEY_CERT;
194             break;
195         case OPT_ASN1PARSE:
196             asn1parse = 1;
197             break;
198         case OPT_HEXDUMP:
199             hexdump = 1;
200             break;
201         case OPT_SIGN:
202             pkey_op = EVP_PKEY_OP_SIGN;
203             break;
204         case OPT_VERIFY:
205             pkey_op = EVP_PKEY_OP_VERIFY;
206             break;
207         case OPT_VERIFYRECOVER:
208             pkey_op = EVP_PKEY_OP_VERIFYRECOVER;
209             break;
210         case OPT_ENCRYPT:
211             pkey_op = EVP_PKEY_OP_ENCRYPT;
212             break;
213         case OPT_DECRYPT:
214             pkey_op = EVP_PKEY_OP_DECRYPT;
215             break;
216         case OPT_DERIVE:
217             pkey_op = EVP_PKEY_OP_DERIVE;
218             break;
219         case OPT_KDF:
220             pkey_op = EVP_PKEY_OP_DERIVE;
221             key_type = KEY_NONE;
222             kdfalg = opt_arg();
223             break;
224         case OPT_KDFLEN:
225             kdflen = atoi(opt_arg());
226             break;
227         case OPT_REV:
228             rev = 1;
229             break;
230         case OPT_PKEYOPT:
231             if ((pkeyopts == NULL &&
232                  (pkeyopts = sk_OPENSSL_STRING_new_null()) == NULL) ||
233                 sk_OPENSSL_STRING_push(pkeyopts, opt_arg()) == 0) {
234                 BIO_puts(bio_err, "out of memory\n");
235                 goto end;
236             }
237             break;
238         case OPT_PKEYOPT_PASSIN:
239             if ((pkeyopts_passin == NULL &&
240                  (pkeyopts_passin = sk_OPENSSL_STRING_new_null()) == NULL) ||
241                 sk_OPENSSL_STRING_push(pkeyopts_passin, opt_arg()) == 0) {
242                 BIO_puts(bio_err, "out of memory\n");
243                 goto end;
244             }
245             break;
246         case OPT_RAWIN:
247             rawin = 1;
248             break;
249         case OPT_DIGEST:
250             if (!opt_md(opt_arg(), &md))
251                 goto end;
252             break;
253         }
254     }
255     argc = opt_num_rest();
256     if (argc != 0)
257         goto opthelp;
258
259     if (rawin && pkey_op != EVP_PKEY_OP_SIGN && pkey_op != EVP_PKEY_OP_VERIFY) {
260         BIO_printf(bio_err,
261                    "%s: -rawin can only be used with -sign or -verify\n",
262                    prog);
263         goto opthelp;
264     }
265
266     if (md != NULL && !rawin) {
267         BIO_printf(bio_err,
268                    "%s: -digest can only be used with -rawin\n",
269                    prog);
270         goto opthelp;
271     }
272
273     if (rawin && rev) {
274         BIO_printf(bio_err, "%s: -rev cannot be used with raw input\n",
275                    prog);
276         goto opthelp;
277     }
278
279     if (kdfalg != NULL) {
280         if (kdflen == 0) {
281             BIO_printf(bio_err,
282                        "%s: no KDF length given (-kdflen parameter).\n", prog);
283             goto opthelp;
284         }
285     } else if (inkey == NULL) {
286         BIO_printf(bio_err,
287                    "%s: no private key given (-inkey parameter).\n", prog);
288         goto opthelp;
289     } else if (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE) {
290         BIO_printf(bio_err,
291                    "%s: no peer key given (-peerkey parameter).\n", prog);
292         goto opthelp;
293     }
294     ctx = init_ctx(kdfalg, &keysize, inkey, keyform, key_type,
295                    passinarg, pkey_op, e, engine_impl, rawin, &pkey,
296                    libctx, propq);
297     if (ctx == NULL) {
298         BIO_printf(bio_err, "%s: Error initializing context\n", prog);
299         ERR_print_errors(bio_err);
300         goto end;
301     }
302     if (peerkey != NULL && !setup_peer(ctx, peerform, peerkey, e)) {
303         BIO_printf(bio_err, "%s: Error setting up peer key\n", prog);
304         ERR_print_errors(bio_err);
305         goto end;
306     }
307     if (pkeyopts != NULL) {
308         int num = sk_OPENSSL_STRING_num(pkeyopts);
309         int i;
310
311         for (i = 0; i < num; ++i) {
312             const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i);
313
314             if (pkey_ctrl_string(ctx, opt) <= 0) {
315                 BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n",
316                            prog, opt);
317                 ERR_print_errors(bio_err);
318                 goto end;
319             }
320         }
321     }
322     if (pkeyopts_passin != NULL) {
323         int num = sk_OPENSSL_STRING_num(pkeyopts_passin);
324         int i;
325
326         for (i = 0; i < num; i++) {
327             char *opt = sk_OPENSSL_STRING_value(pkeyopts_passin, i);
328             char *passin = strchr(opt, ':');
329             char *passwd;
330
331             if (passin == NULL) {
332                 /* Get password interactively */
333                 char passwd_buf[4096];
334                 BIO_snprintf(passwd_buf, sizeof(passwd_buf), "Enter %s: ", opt);
335                 EVP_read_pw_string(passwd_buf, sizeof(passwd_buf) - 1,
336                                    passwd_buf, 0);
337                 passwd = OPENSSL_strdup(passwd_buf);
338                 if (passwd == NULL) {
339                     BIO_puts(bio_err, "out of memory\n");
340                     goto end;
341                 }
342             } else {
343                 /* Get password as a passin argument: First split option name
344                  * and passphrase argument into two strings */
345                 *passin = 0;
346                 passin++;
347                 if (app_passwd(passin, NULL, &passwd, NULL) == 0) {
348                     BIO_printf(bio_err, "failed to get '%s'\n", opt);
349                     goto end;
350                 }
351             }
352
353             if (EVP_PKEY_CTX_ctrl_str(ctx, opt, passwd) <= 0) {
354                 BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n",
355                            prog, opt);
356                 goto end;
357             }
358             OPENSSL_free(passwd);
359         }
360     }
361
362     if (sigfile != NULL && (pkey_op != EVP_PKEY_OP_VERIFY)) {
363         BIO_printf(bio_err,
364                    "%s: Signature file specified for non verify\n", prog);
365         goto end;
366     }
367
368     if (sigfile == NULL && (pkey_op == EVP_PKEY_OP_VERIFY)) {
369         BIO_printf(bio_err,
370                    "%s: No signature file specified for verify\n", prog);
371         goto end;
372     }
373
374     if (pkey_op != EVP_PKEY_OP_DERIVE) {
375         in = bio_open_default(infile, 'r', FORMAT_BINARY);
376         if (infile != NULL) {
377             struct stat st;
378
379             if (stat(infile, &st) == 0 && st.st_size <= INT_MAX)
380                 filesize = (int)st.st_size;
381         }
382         if (in == NULL)
383             goto end;
384     }
385     out = bio_open_default(outfile, 'w', FORMAT_BINARY);
386     if (out == NULL)
387         goto end;
388
389     if (sigfile != NULL) {
390         BIO *sigbio = BIO_new_file(sigfile, "rb");
391
392         if (sigbio == NULL) {
393             BIO_printf(bio_err, "Can't open signature file %s\n", sigfile);
394             goto end;
395         }
396         siglen = bio_to_mem(&sig, keysize * 10, sigbio);
397         BIO_free(sigbio);
398         if (siglen < 0) {
399             BIO_printf(bio_err, "Error reading signature data\n");
400             goto end;
401         }
402     }
403
404     /* Raw input data is handled elsewhere */
405     if (in != NULL && !rawin) {
406         /* Read the input data */
407         buf_inlen = bio_to_mem(&buf_in, keysize * 10, in);
408         if (buf_inlen < 0) {
409             BIO_printf(bio_err, "Error reading input Data\n");
410             goto end;
411         }
412         if (rev) {
413             size_t i;
414             unsigned char ctmp;
415             size_t l = (size_t)buf_inlen;
416             for (i = 0; i < l / 2; i++) {
417                 ctmp = buf_in[i];
418                 buf_in[i] = buf_in[l - 1 - i];
419                 buf_in[l - 1 - i] = ctmp;
420             }
421         }
422     }
423
424     /* Sanity check the input if the input is not raw */
425     if (!rawin
426             && buf_inlen > EVP_MAX_MD_SIZE
427             && (pkey_op == EVP_PKEY_OP_SIGN
428                 || pkey_op == EVP_PKEY_OP_VERIFY)) {
429         BIO_printf(bio_err,
430                    "Error: The input data looks too long to be a hash\n");
431         goto end;
432     }
433
434     if (pkey_op == EVP_PKEY_OP_VERIFY) {
435         if (rawin) {
436             rv = do_raw_keyop(pkey_op, ctx, md, pkey, in, filesize, sig, siglen,
437                               NULL, 0);
438         } else {
439             rv = EVP_PKEY_verify(ctx, sig, (size_t)siglen,
440                                  buf_in, (size_t)buf_inlen);
441         }
442         if (rv == 1) {
443             BIO_puts(out, "Signature Verified Successfully\n");
444             ret = 0;
445         } else {
446             BIO_puts(out, "Signature Verification Failure\n");
447         }
448         goto end;
449     }
450     if (kdflen != 0) {
451         buf_outlen = kdflen;
452         rv = 1;
453     } else {
454         if (rawin) {
455             /* rawin allocates the buffer in do_raw_keyop() */
456             rv = do_raw_keyop(pkey_op, ctx, md, pkey, in, filesize, NULL, 0,
457                               &buf_out, (size_t *)&buf_outlen);
458         } else {
459             rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen,
460                           buf_in, (size_t)buf_inlen);
461             if (rv > 0 && buf_outlen != 0) {
462                 buf_out = app_malloc(buf_outlen, "buffer output");
463                 rv = do_keyop(ctx, pkey_op,
464                               buf_out, (size_t *)&buf_outlen,
465                               buf_in, (size_t)buf_inlen);
466             }
467         }
468     }
469     if (rv <= 0) {
470         if (pkey_op != EVP_PKEY_OP_DERIVE) {
471             BIO_puts(bio_err, "Public Key operation error\n");
472         } else {
473             BIO_puts(bio_err, "Key derivation failed\n");
474         }
475         ERR_print_errors(bio_err);
476         goto end;
477     }
478     ret = 0;
479
480     if (asn1parse) {
481         if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1))
482             ERR_print_errors(bio_err);
483     } else if (hexdump) {
484         BIO_dump(out, (char *)buf_out, buf_outlen);
485     } else {
486         BIO_write(out, buf_out, buf_outlen);
487     }
488
489  end:
490     EVP_PKEY_CTX_free(ctx);
491     release_engine(e);
492     BIO_free(in);
493     BIO_free_all(out);
494     OPENSSL_free(buf_in);
495     OPENSSL_free(buf_out);
496     OPENSSL_free(sig);
497     sk_OPENSSL_STRING_free(pkeyopts);
498     sk_OPENSSL_STRING_free(pkeyopts_passin);
499     NCONF_free(conf);
500     return ret;
501 }
502
503 static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize,
504                               const char *keyfile, int keyform, int key_type,
505                               char *passinarg, int pkey_op, ENGINE *e,
506                               const int engine_impl, int rawin,
507                               EVP_PKEY **ppkey,
508                               OPENSSL_CTX *libctx, const char *propq)
509 {
510     EVP_PKEY *pkey = NULL;
511     EVP_PKEY_CTX *ctx = NULL;
512     ENGINE *impl = NULL;
513     char *passin = NULL;
514     int rv = -1;
515     X509 *x;
516     if (((pkey_op == EVP_PKEY_OP_SIGN) || (pkey_op == EVP_PKEY_OP_DECRYPT)
517          || (pkey_op == EVP_PKEY_OP_DERIVE))
518         && (key_type != KEY_PRIVKEY && kdfalg == NULL)) {
519         BIO_printf(bio_err, "A private key is needed for this operation\n");
520         goto end;
521     }
522     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
523         BIO_printf(bio_err, "Error getting password\n");
524         goto end;
525     }
526     switch (key_type) {
527     case KEY_PRIVKEY:
528         pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
529         break;
530
531     case KEY_PUBKEY:
532         pkey = load_pubkey(keyfile, keyform, 0, NULL, e, "Public Key");
533         break;
534
535     case KEY_CERT:
536         x = load_cert(keyfile, FORMAT_UNDEF, "Certificate");
537         if (x) {
538             pkey = X509_get_pubkey(x);
539             X509_free(x);
540         }
541         break;
542
543     case KEY_NONE:
544         break;
545
546     }
547
548 #ifndef OPENSSL_NO_ENGINE
549     if (engine_impl)
550         impl = e;
551 #endif
552
553     if (kdfalg != NULL) {
554         int kdfnid = OBJ_sn2nid(kdfalg);
555
556         if (kdfnid == NID_undef) {
557             kdfnid = OBJ_ln2nid(kdfalg);
558             if (kdfnid == NID_undef) {
559                 BIO_printf(bio_err, "The given KDF \"%s\" is unknown.\n",
560                            kdfalg);
561                 goto end;
562             }
563         }
564         if (impl != NULL)
565             ctx = EVP_PKEY_CTX_new_id(kdfnid, impl);
566         else
567             ctx = EVP_PKEY_CTX_new_from_name(libctx, kdfalg, propq);
568     } else {
569         if (pkey == NULL)
570             goto end;
571
572         *pkeysize = EVP_PKEY_size(pkey);
573         if (impl != NULL)
574             ctx = EVP_PKEY_CTX_new(pkey, impl);
575         else
576             ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq);
577         if (ppkey != NULL)
578             *ppkey = pkey;
579         EVP_PKEY_free(pkey);
580     }
581
582     if (ctx == NULL)
583         goto end;
584
585     /*
586      * If rawin then we don't need to actually initialise the EVP_PKEY_CTX
587      * itself. That will get initialised during EVP_DigestSignInit or
588      * EVP_DigestVerifyInit.
589      */
590     if (rawin) {
591         rv = 1;
592     } else {
593         switch (pkey_op) {
594         case EVP_PKEY_OP_SIGN:
595             rv = EVP_PKEY_sign_init(ctx);
596             break;
597
598         case EVP_PKEY_OP_VERIFY:
599             rv = EVP_PKEY_verify_init(ctx);
600             break;
601
602         case EVP_PKEY_OP_VERIFYRECOVER:
603             rv = EVP_PKEY_verify_recover_init(ctx);
604             break;
605
606         case EVP_PKEY_OP_ENCRYPT:
607             rv = EVP_PKEY_encrypt_init(ctx);
608             break;
609
610         case EVP_PKEY_OP_DECRYPT:
611             rv = EVP_PKEY_decrypt_init(ctx);
612             break;
613
614         case EVP_PKEY_OP_DERIVE:
615             rv = EVP_PKEY_derive_init(ctx);
616             break;
617         }
618     }
619
620     if (rv <= 0) {
621         EVP_PKEY_CTX_free(ctx);
622         ctx = NULL;
623     }
624
625  end:
626     OPENSSL_free(passin);
627     return ctx;
628
629 }
630
631 static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file,
632                       ENGINE *e)
633 {
634     EVP_PKEY *peer = NULL;
635     ENGINE *engine = NULL;
636     int ret;
637
638     if (peerform == FORMAT_ENGINE)
639         engine = e;
640     peer = load_pubkey(file, peerform, 0, NULL, engine, "Peer Key");
641     if (peer == NULL) {
642         BIO_printf(bio_err, "Error reading peer key %s\n", file);
643         ERR_print_errors(bio_err);
644         return 0;
645     }
646
647     ret = EVP_PKEY_derive_set_peer(ctx, peer);
648
649     EVP_PKEY_free(peer);
650     if (ret <= 0)
651         ERR_print_errors(bio_err);
652     return ret;
653 }
654
655 static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op,
656                     unsigned char *out, size_t *poutlen,
657                     const unsigned char *in, size_t inlen)
658 {
659     int rv = 0;
660     switch (pkey_op) {
661     case EVP_PKEY_OP_VERIFYRECOVER:
662         rv = EVP_PKEY_verify_recover(ctx, out, poutlen, in, inlen);
663         break;
664
665     case EVP_PKEY_OP_SIGN:
666         rv = EVP_PKEY_sign(ctx, out, poutlen, in, inlen);
667         break;
668
669     case EVP_PKEY_OP_ENCRYPT:
670         rv = EVP_PKEY_encrypt(ctx, out, poutlen, in, inlen);
671         break;
672
673     case EVP_PKEY_OP_DECRYPT:
674         rv = EVP_PKEY_decrypt(ctx, out, poutlen, in, inlen);
675         break;
676
677     case EVP_PKEY_OP_DERIVE:
678         rv = EVP_PKEY_derive(ctx, out, poutlen);
679         break;
680
681     }
682     return rv;
683 }
684
685 #define TBUF_MAXSIZE 2048
686
687 static int do_raw_keyop(int pkey_op, EVP_PKEY_CTX *ctx,
688                         const EVP_MD *md, EVP_PKEY *pkey, BIO *in,
689                         int filesize, unsigned char *sig, int siglen,
690                         unsigned char **out, size_t *poutlen)
691 {
692     int rv = 0;
693     EVP_MD_CTX *mctx = NULL;
694     unsigned char tbuf[TBUF_MAXSIZE];
695     unsigned char *mbuf = NULL;
696     int buf_len = 0;
697
698     if ((mctx = EVP_MD_CTX_new()) == NULL) {
699         BIO_printf(bio_err, "Error: out of memory\n");
700         return rv;
701     }
702     EVP_MD_CTX_set_pkey_ctx(mctx, ctx);
703
704     /* Some algorithms only support oneshot digests */
705     if (EVP_PKEY_id(pkey) == EVP_PKEY_ED25519
706             || EVP_PKEY_id(pkey) == EVP_PKEY_ED448) {
707         if (filesize < 0) {
708             BIO_printf(bio_err,
709                        "Error: unable to determine file size for oneshot operation\n");
710             goto end;
711         }
712         mbuf = app_malloc(filesize, "oneshot sign/verify buffer");
713         switch(pkey_op) {
714         case EVP_PKEY_OP_VERIFY:
715             if (EVP_DigestVerifyInit(mctx, NULL, md, NULL, pkey) != 1)
716                 goto end;
717             buf_len = BIO_read(in, mbuf, filesize);
718             if (buf_len != filesize) {
719                 BIO_printf(bio_err, "Error reading raw input data\n");
720                 goto end;
721             }
722             rv = EVP_DigestVerify(mctx, sig, (size_t)siglen, mbuf, buf_len);
723             break;
724         case EVP_PKEY_OP_SIGN:
725             if (EVP_DigestSignInit(mctx, NULL, md, NULL, pkey) != 1)
726                 goto end;
727             buf_len = BIO_read(in, mbuf, filesize);
728             if (buf_len != filesize) {
729                 BIO_printf(bio_err, "Error reading raw input data\n");
730                 goto end;
731             }
732             rv = EVP_DigestSign(mctx, NULL, poutlen, mbuf, buf_len);
733             if (rv == 1 && out != NULL) {
734                 *out = app_malloc(*poutlen, "buffer output");
735                 rv = EVP_DigestSign(mctx, *out, poutlen, mbuf, buf_len);
736             }
737             break;
738         }
739         goto end;
740     }
741
742     switch(pkey_op) {
743     case EVP_PKEY_OP_VERIFY:
744         if (EVP_DigestVerifyInit(mctx, NULL, md, NULL, pkey) != 1)
745             goto end;
746         for (;;) {
747             buf_len = BIO_read(in, tbuf, TBUF_MAXSIZE);
748             if (buf_len == 0)
749                 break;
750             if (buf_len < 0) {
751                 BIO_printf(bio_err, "Error reading raw input data\n");
752                 goto end;
753             }
754             rv = EVP_DigestVerifyUpdate(mctx, tbuf, (size_t)buf_len);
755             if (rv != 1) {
756                 BIO_printf(bio_err, "Error verifying raw input data\n");
757                 goto end;
758             }
759         }
760         rv = EVP_DigestVerifyFinal(mctx, sig, (size_t)siglen);
761         break;
762     case EVP_PKEY_OP_SIGN:
763         if (EVP_DigestSignInit(mctx, NULL, md, NULL, pkey) != 1)
764             goto end;
765         for (;;) {
766             buf_len = BIO_read(in, tbuf, TBUF_MAXSIZE);
767             if (buf_len == 0)
768                 break;
769             if (buf_len < 0) {
770                 BIO_printf(bio_err, "Error reading raw input data\n");
771                 goto end;
772             }
773             rv = EVP_DigestSignUpdate(mctx, tbuf, (size_t)buf_len);
774             if (rv != 1) {
775                 BIO_printf(bio_err, "Error signing raw input data\n");
776                 goto end;
777             }
778         }
779         rv = EVP_DigestSignFinal(mctx, NULL, poutlen);
780         if (rv == 1 && out != NULL) {
781             *out = app_malloc(*poutlen, "buffer output");
782             rv = EVP_DigestSignFinal(mctx, *out, poutlen);
783         }
784         break;
785     }
786
787  end:
788     OPENSSL_free(mbuf);
789     EVP_MD_CTX_free(mctx);
790     return rv;
791 }