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