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