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