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