Revert "Add some casts for %j"
[openssl.git] / apps / pkeyutl.c
1 /*
2  * Copyright 2006-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 <string.h>
12 #include <openssl/err.h>
13 #include <openssl/pem.h>
14 #include <openssl/evp.h>
15
16 #define KEY_NONE        0
17 #define KEY_PRIVKEY     1
18 #define KEY_PUBKEY      2
19 #define KEY_CERT        3
20
21 static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize,
22                               const char *keyfile, int keyform, int key_type,
23                               char *passinarg, int pkey_op, ENGINE *e,
24                               const int impl);
25
26 static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file,
27                       ENGINE *e);
28
29 static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op,
30                     unsigned char *out, size_t *poutlen,
31                     const unsigned char *in, size_t inlen);
32
33 typedef enum OPTION_choice {
34     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
35     OPT_ENGINE, OPT_ENGINE_IMPL, OPT_IN, OPT_OUT,
36     OPT_PUBIN, OPT_CERTIN, OPT_ASN1PARSE, OPT_HEXDUMP, OPT_SIGN,
37     OPT_VERIFY, OPT_VERIFYRECOVER, OPT_REV, OPT_ENCRYPT, OPT_DECRYPT,
38     OPT_DERIVE, OPT_SIGFILE, OPT_INKEY, OPT_PEERKEY, OPT_PASSIN,
39     OPT_PEERFORM, OPT_KEYFORM, OPT_PKEYOPT, OPT_KDF, OPT_KDFLEN,
40     OPT_R_ENUM
41 } OPTION_CHOICE;
42
43 const OPTIONS pkeyutl_options[] = {
44     {"help", OPT_HELP, '-', "Display this summary"},
45     {"in", OPT_IN, '<', "Input file - default stdin"},
46     {"out", OPT_OUT, '>', "Output file - default stdout"},
47     {"pubin", OPT_PUBIN, '-', "Input is a public key"},
48     {"certin", OPT_CERTIN, '-', "Input is a cert with a public key"},
49     {"asn1parse", OPT_ASN1PARSE, '-', "asn1parse the output data"},
50     {"hexdump", OPT_HEXDUMP, '-', "Hex dump output"},
51     {"sign", OPT_SIGN, '-', "Sign input data with private key"},
52     {"verify", OPT_VERIFY, '-', "Verify with public key"},
53     {"verifyrecover", OPT_VERIFYRECOVER, '-',
54      "Verify with public key, recover original data"},
55     {"rev", OPT_REV, '-', "Reverse the order of the input buffer"},
56     {"encrypt", OPT_ENCRYPT, '-', "Encrypt input data with public key"},
57     {"decrypt", OPT_DECRYPT, '-', "Decrypt input data with private key"},
58     {"derive", OPT_DERIVE, '-', "Derive shared secret"},
59     {"kdf", OPT_KDF, 's', "Use KDF algorithm"},
60     {"kdflen", OPT_KDFLEN, 'p', "KDF algorithm output length"},
61     {"sigfile", OPT_SIGFILE, '<', "Signature file (verify operation only)"},
62     {"inkey", OPT_INKEY, 's', "Input private key file"},
63     {"peerkey", OPT_PEERKEY, 's', "Peer key file used in key derivation"},
64     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
65     {"peerform", OPT_PEERFORM, 'E', "Peer key format - default PEM"},
66     {"keyform", OPT_KEYFORM, 'E', "Private key format - default PEM"},
67     {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
68     OPT_R_OPTIONS,
69 #ifndef OPENSSL_NO_ENGINE
70     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
71     {"engine_impl", OPT_ENGINE_IMPL, '-',
72      "Also use engine given by -engine for crypto operations"},
73 #endif
74     {NULL}
75 };
76
77 int pkeyutl_main(int argc, char **argv)
78 {
79     BIO *in = NULL, *out = NULL;
80     ENGINE *e = NULL;
81     EVP_PKEY_CTX *ctx = NULL;
82     char *infile = NULL, *outfile = NULL, *sigfile = NULL, *passinarg = NULL;
83     char hexdump = 0, asn1parse = 0, rev = 0, *prog;
84     unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL;
85     OPTION_CHOICE o;
86     int buf_inlen = 0, siglen = -1, keyform = FORMAT_PEM, peerform =
87         FORMAT_PEM;
88     int keysize = -1, pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY;
89     int engine_impl = 0;
90     int ret = 1, rv = -1;
91     size_t buf_outlen;
92     const char *inkey = NULL;
93     const char *peerkey = NULL;
94     const char *kdfalg = NULL;
95     int kdflen = 0;
96     STACK_OF(OPENSSL_STRING) *pkeyopts = NULL;
97
98     prog = opt_init(argc, argv, pkeyutl_options);
99     while ((o = opt_next()) != OPT_EOF) {
100         switch (o) {
101         case OPT_EOF:
102         case OPT_ERR:
103  opthelp:
104             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
105             goto end;
106         case OPT_HELP:
107             opt_help(pkeyutl_options);
108             ret = 0;
109             goto end;
110         case OPT_IN:
111             infile = opt_arg();
112             break;
113         case OPT_OUT:
114             outfile = opt_arg();
115             break;
116         case OPT_SIGFILE:
117             sigfile = opt_arg();
118             break;
119         case OPT_ENGINE_IMPL:
120             engine_impl = 1;
121             break;
122         case OPT_INKEY:
123             inkey = opt_arg();
124             break;
125         case OPT_PEERKEY:
126             peerkey = opt_arg();
127             break;
128         case OPT_PASSIN:
129             passinarg = opt_arg();
130             break;
131         case OPT_PEERFORM:
132             if (!opt_format(opt_arg(), OPT_FMT_PDE, &peerform))
133                 goto opthelp;
134             break;
135         case OPT_KEYFORM:
136             if (!opt_format(opt_arg(), OPT_FMT_PDE, &keyform))
137                 goto opthelp;
138             break;
139         case OPT_R_CASES:
140             if (!opt_rand(o))
141                 goto end;
142             break;
143         case OPT_ENGINE:
144             e = setup_engine(opt_arg(), 0);
145             break;
146         case OPT_PUBIN:
147             key_type = KEY_PUBKEY;
148             break;
149         case OPT_CERTIN:
150             key_type = KEY_CERT;
151             break;
152         case OPT_ASN1PARSE:
153             asn1parse = 1;
154             break;
155         case OPT_HEXDUMP:
156             hexdump = 1;
157             break;
158         case OPT_SIGN:
159             pkey_op = EVP_PKEY_OP_SIGN;
160             break;
161         case OPT_VERIFY:
162             pkey_op = EVP_PKEY_OP_VERIFY;
163             break;
164         case OPT_VERIFYRECOVER:
165             pkey_op = EVP_PKEY_OP_VERIFYRECOVER;
166             break;
167         case OPT_ENCRYPT:
168             pkey_op = EVP_PKEY_OP_ENCRYPT;
169             break;
170         case OPT_DECRYPT:
171             pkey_op = EVP_PKEY_OP_DECRYPT;
172             break;
173         case OPT_DERIVE:
174             pkey_op = EVP_PKEY_OP_DERIVE;
175             break;
176         case OPT_KDF:
177             pkey_op = EVP_PKEY_OP_DERIVE;
178             key_type = KEY_NONE;
179             kdfalg = opt_arg();
180             break;
181         case OPT_KDFLEN:
182             kdflen = atoi(opt_arg());
183             break;
184         case OPT_REV:
185             rev = 1;
186             break;
187         case OPT_PKEYOPT:
188             if ((pkeyopts == NULL &&
189                  (pkeyopts = sk_OPENSSL_STRING_new_null()) == NULL) ||
190                 sk_OPENSSL_STRING_push(pkeyopts, opt_arg()) == 0) {
191                 BIO_puts(bio_err, "out of memory\n");
192                 goto end;
193             }
194             break;
195         }
196     }
197     argc = opt_num_rest();
198     if (argc != 0)
199         goto opthelp;
200
201     if (kdfalg != NULL) {
202         if (kdflen == 0)
203             goto opthelp;
204     } else if ((inkey == NULL)
205             || (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE)) {
206         goto opthelp;
207     }
208     ctx = init_ctx(kdfalg, &keysize, inkey, keyform, key_type,
209                    passinarg, pkey_op, e, engine_impl);
210     if (ctx == NULL) {
211         BIO_printf(bio_err, "%s: Error initializing context\n", prog);
212         ERR_print_errors(bio_err);
213         goto end;
214     }
215     if (peerkey != NULL && !setup_peer(ctx, peerform, peerkey, e)) {
216         BIO_printf(bio_err, "%s: Error setting up peer key\n", prog);
217         ERR_print_errors(bio_err);
218         goto end;
219     }
220     if (pkeyopts != NULL) {
221         int num = sk_OPENSSL_STRING_num(pkeyopts);
222         int i;
223
224         for (i = 0; i < num; ++i) {
225             const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i);
226
227             if (pkey_ctrl_string(ctx, opt) <= 0) {
228                 BIO_printf(bio_err, "%s: Can't set parameter:\n", prog);
229                 ERR_print_errors(bio_err);
230                 goto end;
231             }
232         }
233     }
234
235     if (sigfile != NULL && (pkey_op != EVP_PKEY_OP_VERIFY)) {
236         BIO_printf(bio_err,
237                    "%s: Signature file specified for non verify\n", prog);
238         goto end;
239     }
240
241     if (sigfile == NULL && (pkey_op == EVP_PKEY_OP_VERIFY)) {
242         BIO_printf(bio_err,
243                    "%s: No signature file specified for verify\n", prog);
244         goto end;
245     }
246
247     if (pkey_op != EVP_PKEY_OP_DERIVE) {
248         in = bio_open_default(infile, 'r', FORMAT_BINARY);
249         if (in == NULL)
250             goto end;
251     }
252     out = bio_open_default(outfile, 'w', FORMAT_BINARY);
253     if (out == NULL)
254         goto end;
255
256     if (sigfile != NULL) {
257         BIO *sigbio = BIO_new_file(sigfile, "rb");
258
259         if (sigbio == NULL) {
260             BIO_printf(bio_err, "Can't open signature file %s\n", sigfile);
261             goto end;
262         }
263         siglen = bio_to_mem(&sig, keysize * 10, sigbio);
264         BIO_free(sigbio);
265         if (siglen < 0) {
266             BIO_printf(bio_err, "Error reading signature data\n");
267             goto end;
268         }
269     }
270
271     if (in != NULL) {
272         /* Read the input data */
273         buf_inlen = bio_to_mem(&buf_in, keysize * 10, in);
274         if (buf_inlen < 0) {
275             BIO_printf(bio_err, "Error reading input Data\n");
276             exit(1);
277         }
278         if (rev) {
279             size_t i;
280             unsigned char ctmp;
281             size_t l = (size_t)buf_inlen;
282             for (i = 0; i < l / 2; i++) {
283                 ctmp = buf_in[i];
284                 buf_in[i] = buf_in[l - 1 - i];
285                 buf_in[l - 1 - i] = ctmp;
286             }
287         }
288     }
289
290     if (pkey_op == EVP_PKEY_OP_VERIFY) {
291         rv = EVP_PKEY_verify(ctx, sig, (size_t)siglen,
292                              buf_in, (size_t)buf_inlen);
293         if (rv == 1) {
294             BIO_puts(out, "Signature Verified Successfully\n");
295             ret = 0;
296         } else {
297             BIO_puts(out, "Signature Verification Failure\n");
298         }
299         goto end;
300     }
301     if (kdflen != 0) {
302         buf_outlen = kdflen;
303         rv = 1;
304     } else {
305         rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen,
306                       buf_in, (size_t)buf_inlen);
307     }
308     if (rv > 0 && buf_outlen != 0) {
309         buf_out = app_malloc(buf_outlen, "buffer output");
310         rv = do_keyop(ctx, pkey_op,
311                       buf_out, (size_t *)&buf_outlen,
312                       buf_in, (size_t)buf_inlen);
313     }
314     if (rv <= 0) {
315         BIO_puts(bio_err, "Public Key operation error\n");
316         ERR_print_errors(bio_err);
317         goto end;
318     }
319     ret = 0;
320
321     if (asn1parse) {
322         if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1))
323             ERR_print_errors(bio_err);
324     } else if (hexdump) {
325         BIO_dump(out, (char *)buf_out, buf_outlen);
326     } else {
327         BIO_write(out, buf_out, buf_outlen);
328     }
329
330  end:
331     EVP_PKEY_CTX_free(ctx);
332     release_engine(e);
333     BIO_free(in);
334     BIO_free_all(out);
335     OPENSSL_free(buf_in);
336     OPENSSL_free(buf_out);
337     OPENSSL_free(sig);
338     sk_OPENSSL_STRING_free(pkeyopts);
339     return ret;
340 }
341
342 static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize,
343                               const char *keyfile, int keyform, int key_type,
344                               char *passinarg, int pkey_op, ENGINE *e,
345                               const int engine_impl)
346 {
347     EVP_PKEY *pkey = NULL;
348     EVP_PKEY_CTX *ctx = NULL;
349     ENGINE *impl = NULL;
350     char *passin = NULL;
351     int rv = -1;
352     X509 *x;
353     if (((pkey_op == EVP_PKEY_OP_SIGN) || (pkey_op == EVP_PKEY_OP_DECRYPT)
354          || (pkey_op == EVP_PKEY_OP_DERIVE))
355         && (key_type != KEY_PRIVKEY && kdfalg == NULL)) {
356         BIO_printf(bio_err, "A private key is needed for this operation\n");
357         goto end;
358     }
359     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
360         BIO_printf(bio_err, "Error getting password\n");
361         goto end;
362     }
363     switch (key_type) {
364     case KEY_PRIVKEY:
365         pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
366         break;
367
368     case KEY_PUBKEY:
369         pkey = load_pubkey(keyfile, keyform, 0, NULL, e, "Public Key");
370         break;
371
372     case KEY_CERT:
373         x = load_cert(keyfile, keyform, "Certificate");
374         if (x) {
375             pkey = X509_get_pubkey(x);
376             X509_free(x);
377         }
378         break;
379
380     case KEY_NONE:
381         break;
382
383     }
384
385 #ifndef OPENSSL_NO_ENGINE
386     if (engine_impl)
387         impl = e;
388 #endif
389
390     if (kdfalg != NULL) {
391         int kdfnid = OBJ_sn2nid(kdfalg);
392
393         if (kdfnid == NID_undef) {
394             kdfnid = OBJ_ln2nid(kdfalg);
395             if (kdfnid == NID_undef)
396                 goto end;
397         }
398         ctx = EVP_PKEY_CTX_new_id(kdfnid, impl);
399     } else {
400         if (pkey == NULL)
401             goto end;
402         *pkeysize = EVP_PKEY_size(pkey);
403         ctx = EVP_PKEY_CTX_new(pkey, impl);
404         EVP_PKEY_free(pkey);
405     }
406
407     if (ctx == NULL)
408         goto end;
409
410     switch (pkey_op) {
411     case EVP_PKEY_OP_SIGN:
412         rv = EVP_PKEY_sign_init(ctx);
413         break;
414
415     case EVP_PKEY_OP_VERIFY:
416         rv = EVP_PKEY_verify_init(ctx);
417         break;
418
419     case EVP_PKEY_OP_VERIFYRECOVER:
420         rv = EVP_PKEY_verify_recover_init(ctx);
421         break;
422
423     case EVP_PKEY_OP_ENCRYPT:
424         rv = EVP_PKEY_encrypt_init(ctx);
425         break;
426
427     case EVP_PKEY_OP_DECRYPT:
428         rv = EVP_PKEY_decrypt_init(ctx);
429         break;
430
431     case EVP_PKEY_OP_DERIVE:
432         rv = EVP_PKEY_derive_init(ctx);
433         break;
434     }
435
436     if (rv <= 0) {
437         EVP_PKEY_CTX_free(ctx);
438         ctx = NULL;
439     }
440
441  end:
442     OPENSSL_free(passin);
443     return ctx;
444
445 }
446
447 static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file,
448                       ENGINE* e)
449 {
450     EVP_PKEY *peer = NULL;
451     ENGINE* engine = NULL;
452     int ret;
453
454     if (peerform == FORMAT_ENGINE)
455         engine = e;
456     peer = load_pubkey(file, peerform, 0, NULL, engine, "Peer Key");
457     if (peer == NULL) {
458         BIO_printf(bio_err, "Error reading peer key %s\n", file);
459         ERR_print_errors(bio_err);
460         return 0;
461     }
462
463     ret = EVP_PKEY_derive_set_peer(ctx, peer);
464
465     EVP_PKEY_free(peer);
466     if (ret <= 0)
467         ERR_print_errors(bio_err);
468     return ret;
469 }
470
471 static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op,
472                     unsigned char *out, size_t *poutlen,
473                     const unsigned char *in, size_t inlen)
474 {
475     int rv = 0;
476     switch (pkey_op) {
477     case EVP_PKEY_OP_VERIFYRECOVER:
478         rv = EVP_PKEY_verify_recover(ctx, out, poutlen, in, inlen);
479         break;
480
481     case EVP_PKEY_OP_SIGN:
482         rv = EVP_PKEY_sign(ctx, out, poutlen, in, inlen);
483         break;
484
485     case EVP_PKEY_OP_ENCRYPT:
486         rv = EVP_PKEY_encrypt(ctx, out, poutlen, in, inlen);
487         break;
488
489     case EVP_PKEY_OP_DECRYPT:
490         rv = EVP_PKEY_decrypt(ctx, out, poutlen, in, inlen);
491         break;
492
493     case EVP_PKEY_OP_DERIVE:
494         rv = EVP_PKEY_derive(ctx, out, poutlen);
495         break;
496
497     }
498     return rv;
499 }