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