Extensive application of __owur to CT functions that return a boolean
[openssl.git] / apps / pkeyutl.c
1 /*
2  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
3  * 2006.
4  */
5 /* ====================================================================
6  * Copyright (c) 2006 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58
59 #include "apps.h"
60 #include <string.h>
61 #include <openssl/err.h>
62 #include <openssl/pem.h>
63 #include <openssl/evp.h>
64
65 #define KEY_NONE        0
66 #define KEY_PRIVKEY     1
67 #define KEY_PUBKEY      2
68 #define KEY_CERT        3
69
70 static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize,
71                               const char *keyfile, int keyform, int key_type,
72                               char *passinarg, int pkey_op, ENGINE *e,
73                               const int impl);
74
75 static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file,
76                       ENGINE *e);
77
78 static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op,
79                     unsigned char *out, size_t *poutlen,
80                     unsigned char *in, size_t inlen);
81
82 typedef enum OPTION_choice {
83     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
84     OPT_ENGINE, OPT_ENGINE_IMPL, OPT_IN, OPT_OUT,
85     OPT_PUBIN, OPT_CERTIN, OPT_ASN1PARSE, OPT_HEXDUMP, OPT_SIGN,
86     OPT_VERIFY, OPT_VERIFYRECOVER, OPT_REV, OPT_ENCRYPT, OPT_DECRYPT,
87     OPT_DERIVE, OPT_SIGFILE, OPT_INKEY, OPT_PEERKEY, OPT_PASSIN,
88     OPT_PEERFORM, OPT_KEYFORM, OPT_PKEYOPT, OPT_KDF, OPT_KDFLEN
89 } OPTION_CHOICE;
90
91 OPTIONS pkeyutl_options[] = {
92     {"help", OPT_HELP, '-', "Display this summary"},
93     {"in", OPT_IN, '<', "Input file - default stdin"},
94     {"out", OPT_OUT, '>', "Output file - default stdout"},
95     {"pubin", OPT_PUBIN, '-', "Input is a public key"},
96     {"certin", OPT_CERTIN, '-', "Input is a cert with a public key"},
97     {"asn1parse", OPT_ASN1PARSE, '-', "asn1parse the output data"},
98     {"hexdump", OPT_HEXDUMP, '-', "Hex dump output"},
99     {"sign", OPT_SIGN, '-', "Sign input data with private key"},
100     {"verify", OPT_VERIFY, '-', "Verify with public key"},
101     {"verifyrecover", OPT_VERIFYRECOVER, '-',
102      "Verify with public key, recover original data"},
103     {"rev", OPT_REV, '-', "Reverse the order of the input buffer"},
104     {"encrypt", OPT_ENCRYPT, '-', "Encrypt input data with public key"},
105     {"decrypt", OPT_DECRYPT, '-', "Decrypt input data with private key"},
106     {"derive", OPT_DERIVE, '-', "Derive shared secret"},
107     {"kdf", OPT_KDF, 's', "Use KDF algorithm"},
108     {"kdflen", OPT_KDFLEN, 'p', "KDF algorithm output length"},
109     {"sigfile", OPT_SIGFILE, '<', "Signature file (verify operation only)"},
110     {"inkey", OPT_INKEY, 's', "Input private key file"},
111     {"peerkey", OPT_PEERKEY, 's', "Peer key file used in key derivation"},
112     {"passin", OPT_PASSIN, 's', "Pass phrase source"},
113     {"peerform", OPT_PEERFORM, 'E', "Peer key format - default PEM"},
114     {"keyform", OPT_KEYFORM, 'E', "Private key format - default PEM"},
115     {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
116 #ifndef OPENSSL_NO_ENGINE
117     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
118     {"engine_impl", OPT_ENGINE_IMPL, '-',
119      "Also use engine given by -engine for crypto operations"},
120 #endif
121     {NULL}
122 };
123
124 int pkeyutl_main(int argc, char **argv)
125 {
126     BIO *in = NULL, *out = NULL;
127     ENGINE *e = NULL;
128     EVP_PKEY_CTX *ctx = NULL;
129     char *infile = NULL, *outfile = NULL, *sigfile = NULL, *passinarg = NULL;
130     char hexdump = 0, asn1parse = 0, rev = 0, *prog;
131     unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL;
132     OPTION_CHOICE o;
133     int buf_inlen = 0, siglen = -1, keyform = FORMAT_PEM, peerform =
134         FORMAT_PEM;
135     int keysize = -1, pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY;
136     int engine_impl = 0;
137     int ret = 1, rv = -1;
138     size_t buf_outlen;
139     const char *inkey = NULL;
140     const char *peerkey = NULL;
141     const char *kdfalg = NULL;
142     int kdflen = 0;
143     STACK_OF(OPENSSL_STRING) *pkeyopts = NULL;
144
145     prog = opt_init(argc, argv, pkeyutl_options);
146     while ((o = opt_next()) != OPT_EOF) {
147         switch (o) {
148         case OPT_EOF:
149         case OPT_ERR:
150  opthelp:
151             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
152             goto end;
153         case OPT_HELP:
154             opt_help(pkeyutl_options);
155             ret = 0;
156             goto end;
157         case OPT_IN:
158             infile = opt_arg();
159             break;
160         case OPT_OUT:
161             outfile = opt_arg();
162             break;
163         case OPT_SIGFILE:
164             sigfile = opt_arg();
165             break;
166         case OPT_ENGINE_IMPL:
167             engine_impl = 1;
168             break;
169         case OPT_INKEY:
170             inkey = opt_arg();
171             break;
172         case OPT_PEERKEY:
173             peerkey = opt_arg();
174             break;
175         case OPT_PASSIN:
176             passinarg = opt_arg();
177             break;
178         case OPT_PEERFORM:
179             if (!opt_format(opt_arg(), OPT_FMT_PDE, &peerform))
180                 goto opthelp;
181             break;
182         case OPT_KEYFORM:
183             if (!opt_format(opt_arg(), OPT_FMT_PDE, &keyform))
184                 goto opthelp;
185             break;
186         case OPT_ENGINE:
187             e = setup_engine(opt_arg(), 0);
188             break;
189         case OPT_PUBIN:
190             key_type = KEY_PUBKEY;
191             break;
192         case OPT_CERTIN:
193             key_type = KEY_CERT;
194             break;
195         case OPT_ASN1PARSE:
196             asn1parse = 1;
197             break;
198         case OPT_HEXDUMP:
199             hexdump = 1;
200             break;
201         case OPT_SIGN:
202             pkey_op = EVP_PKEY_OP_SIGN;
203             break;
204         case OPT_VERIFY:
205             pkey_op = EVP_PKEY_OP_VERIFY;
206             break;
207         case OPT_VERIFYRECOVER:
208             pkey_op = EVP_PKEY_OP_VERIFYRECOVER;
209             break;
210         case OPT_ENCRYPT:
211             pkey_op = EVP_PKEY_OP_ENCRYPT;
212             break;
213         case OPT_DECRYPT:
214             pkey_op = EVP_PKEY_OP_DECRYPT;
215             break;
216         case OPT_DERIVE:
217             pkey_op = EVP_PKEY_OP_DERIVE;
218             break;
219         case OPT_KDF:
220             pkey_op = EVP_PKEY_OP_DERIVE;
221             key_type = KEY_NONE;
222             kdfalg = opt_arg();
223             break;
224         case OPT_KDFLEN:
225             kdflen = atoi(opt_arg());
226             break;
227         case OPT_REV:
228             rev = 1;
229             break;
230         case OPT_PKEYOPT:
231             if ((pkeyopts == NULL &&
232                  (pkeyopts = sk_OPENSSL_STRING_new_null()) == NULL) ||
233                 sk_OPENSSL_STRING_push(pkeyopts, opt_arg()) == 0) {
234                 BIO_puts(bio_err, "out of memory\n");
235                 goto end;
236             }
237             break;
238         }
239     }
240     argc = opt_num_rest();
241     if (argc != 0)
242         goto opthelp;
243
244     if (kdfalg != NULL) {
245         if (kdflen == 0)
246             goto opthelp;
247     } else if ((inkey == NULL)
248             || (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE)) {
249         goto opthelp;
250     }
251     ctx = init_ctx(kdfalg, &keysize, inkey, keyform, key_type,
252                    passinarg, pkey_op, e, engine_impl);
253     if (ctx == NULL) {
254         BIO_printf(bio_err, "%s: Error initializing context\n", prog);
255         ERR_print_errors(bio_err);
256         goto end;
257     }
258     if (peerkey != NULL && !setup_peer(ctx, peerform, peerkey, e)) {
259         BIO_printf(bio_err, "%s: Error setting up peer key\n", prog);
260         ERR_print_errors(bio_err);
261         goto end;
262     }
263     if (pkeyopts != NULL) {
264         int num = sk_OPENSSL_STRING_num(pkeyopts);
265         int i;
266
267         for (i = 0; i < num; ++i) {
268             const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i);
269
270             if (pkey_ctrl_string(ctx, opt) <= 0) {
271                 BIO_printf(bio_err, "%s: Can't set parameter:\n", prog);
272                 ERR_print_errors(bio_err);
273                 goto end;
274             }
275         }
276     }
277
278     if (sigfile && (pkey_op != EVP_PKEY_OP_VERIFY)) {
279         BIO_printf(bio_err,
280                    "%s: Signature file specified for non verify\n", prog);
281         goto end;
282     }
283
284     if (!sigfile && (pkey_op == EVP_PKEY_OP_VERIFY)) {
285         BIO_printf(bio_err,
286                    "%s: No signature file specified for verify\n", prog);
287         goto end;
288     }
289
290 /* FIXME: seed PRNG only if needed */
291     app_RAND_load_file(NULL, 0);
292
293     if (pkey_op != EVP_PKEY_OP_DERIVE) {
294         in = bio_open_default(infile, 'r', FORMAT_BINARY);
295         if (in == NULL)
296             goto end;
297     }
298     out = bio_open_default(outfile, 'w', FORMAT_BINARY);
299     if (out == NULL)
300         goto end;
301
302     if (sigfile) {
303         BIO *sigbio = BIO_new_file(sigfile, "rb");
304         if (!sigbio) {
305             BIO_printf(bio_err, "Can't open signature file %s\n", sigfile);
306             goto end;
307         }
308         siglen = bio_to_mem(&sig, keysize * 10, sigbio);
309         BIO_free(sigbio);
310         if (siglen < 0) {
311             BIO_printf(bio_err, "Error reading signature data\n");
312             goto end;
313         }
314     }
315
316     if (in) {
317         /* Read the input data */
318         buf_inlen = bio_to_mem(&buf_in, keysize * 10, in);
319         if (buf_inlen < 0) {
320             BIO_printf(bio_err, "Error reading input Data\n");
321             exit(1);
322         }
323         if (rev) {
324             size_t i;
325             unsigned char ctmp;
326             size_t l = (size_t)buf_inlen;
327             for (i = 0; i < l / 2; i++) {
328                 ctmp = buf_in[i];
329                 buf_in[i] = buf_in[l - 1 - i];
330                 buf_in[l - 1 - i] = ctmp;
331             }
332         }
333     }
334
335     if (pkey_op == EVP_PKEY_OP_VERIFY) {
336         rv = EVP_PKEY_verify(ctx, sig, (size_t)siglen,
337                              buf_in, (size_t)buf_inlen);
338         if (rv == 1) {
339             BIO_puts(out, "Signature Verified Successfully\n");
340             ret = 0;
341         } else
342             BIO_puts(out, "Signature Verification Failure\n");
343         goto end;
344     }
345     if (kdflen != 0) {
346         buf_outlen = kdflen;
347         rv = 1;
348     } else {
349         rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen,
350                       buf_in, (size_t)buf_inlen);
351     }
352     if (rv > 0 && buf_outlen != 0) {
353         buf_out = app_malloc(buf_outlen, "buffer output");
354         rv = do_keyop(ctx, pkey_op,
355                       buf_out, (size_t *)&buf_outlen,
356                       buf_in, (size_t)buf_inlen);
357     }
358     if (rv <= 0) {
359         BIO_puts(bio_err, "Public Key operation error\n");
360         ERR_print_errors(bio_err);
361         goto end;
362     }
363     ret = 0;
364
365     if (asn1parse) {
366         if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1))
367             ERR_print_errors(bio_err);
368     } else if (hexdump)
369         BIO_dump(out, (char *)buf_out, buf_outlen);
370     else
371         BIO_write(out, buf_out, buf_outlen);
372
373  end:
374     EVP_PKEY_CTX_free(ctx);
375     BIO_free(in);
376     BIO_free_all(out);
377     OPENSSL_free(buf_in);
378     OPENSSL_free(buf_out);
379     OPENSSL_free(sig);
380     sk_OPENSSL_STRING_free(pkeyopts);
381     return ret;
382 }
383
384 static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize,
385                               const char *keyfile, int keyform, int key_type,
386                               char *passinarg, int pkey_op, ENGINE *e,
387                               const int engine_impl)
388 {
389     EVP_PKEY *pkey = NULL;
390     EVP_PKEY_CTX *ctx = NULL;
391     ENGINE *impl = NULL;
392     char *passin = NULL;
393     int rv = -1;
394     X509 *x;
395     if (((pkey_op == EVP_PKEY_OP_SIGN) || (pkey_op == EVP_PKEY_OP_DECRYPT)
396          || (pkey_op == EVP_PKEY_OP_DERIVE))
397         && (key_type != KEY_PRIVKEY && kdfalg == NULL)) {
398         BIO_printf(bio_err, "A private key is needed for this operation\n");
399         goto end;
400     }
401     if (!app_passwd(passinarg, NULL, &passin, NULL)) {
402         BIO_printf(bio_err, "Error getting password\n");
403         goto end;
404     }
405     switch (key_type) {
406     case KEY_PRIVKEY:
407         pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
408         break;
409
410     case KEY_PUBKEY:
411         pkey = load_pubkey(keyfile, keyform, 0, NULL, e, "Public Key");
412         break;
413
414     case KEY_CERT:
415         x = load_cert(keyfile, keyform, "Certificate");
416         if (x) {
417             pkey = X509_get_pubkey(x);
418             X509_free(x);
419         }
420         break;
421
422     case KEY_NONE:
423         break;
424
425     }
426
427 #ifndef OPENSSL_NO_ENGINE
428     if (engine_impl)
429         impl = e;
430 #endif
431
432     if (kdfalg) {
433         int kdfnid = OBJ_sn2nid(kdfalg);
434         if (kdfnid == NID_undef)
435             goto end;
436         ctx = EVP_PKEY_CTX_new_id(kdfnid, impl);
437     } else {
438         if (pkey == NULL)
439             goto end;
440         *pkeysize = EVP_PKEY_size(pkey);
441         ctx = EVP_PKEY_CTX_new(pkey, impl);
442         EVP_PKEY_free(pkey);
443     }
444
445     if (ctx == NULL)
446         goto end;
447
448     switch (pkey_op) {
449     case EVP_PKEY_OP_SIGN:
450         rv = EVP_PKEY_sign_init(ctx);
451         break;
452
453     case EVP_PKEY_OP_VERIFY:
454         rv = EVP_PKEY_verify_init(ctx);
455         break;
456
457     case EVP_PKEY_OP_VERIFYRECOVER:
458         rv = EVP_PKEY_verify_recover_init(ctx);
459         break;
460
461     case EVP_PKEY_OP_ENCRYPT:
462         rv = EVP_PKEY_encrypt_init(ctx);
463         break;
464
465     case EVP_PKEY_OP_DECRYPT:
466         rv = EVP_PKEY_decrypt_init(ctx);
467         break;
468
469     case EVP_PKEY_OP_DERIVE:
470         rv = EVP_PKEY_derive_init(ctx);
471         break;
472     }
473
474     if (rv <= 0) {
475         EVP_PKEY_CTX_free(ctx);
476         ctx = NULL;
477     }
478
479  end:
480     OPENSSL_free(passin);
481     return ctx;
482
483 }
484
485 static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file,
486                       ENGINE* e)
487 {
488     EVP_PKEY *peer = NULL;
489     ENGINE* engine = NULL;
490     int ret;
491
492     if (peerform == FORMAT_ENGINE)
493         engine = e;
494     peer = load_pubkey(file, peerform, 0, NULL, engine, "Peer Key");
495     if (!peer) {
496         BIO_printf(bio_err, "Error reading peer key %s\n", file);
497         ERR_print_errors(bio_err);
498         return 0;
499     }
500
501     ret = EVP_PKEY_derive_set_peer(ctx, peer);
502
503     EVP_PKEY_free(peer);
504     if (ret <= 0)
505         ERR_print_errors(bio_err);
506     return ret;
507 }
508
509 static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op,
510                     unsigned char *out, size_t *poutlen,
511                     unsigned char *in, size_t inlen)
512 {
513     int rv = 0;
514     switch (pkey_op) {
515     case EVP_PKEY_OP_VERIFYRECOVER:
516         rv = EVP_PKEY_verify_recover(ctx, out, poutlen, in, inlen);
517         break;
518
519     case EVP_PKEY_OP_SIGN:
520         rv = EVP_PKEY_sign(ctx, out, poutlen, in, inlen);
521         break;
522
523     case EVP_PKEY_OP_ENCRYPT:
524         rv = EVP_PKEY_encrypt(ctx, out, poutlen, in, inlen);
525         break;
526
527     case EVP_PKEY_OP_DECRYPT:
528         rv = EVP_PKEY_decrypt(ctx, out, poutlen, in, inlen);
529         break;
530
531     case EVP_PKEY_OP_DERIVE:
532         rv = EVP_PKEY_derive(ctx, out, poutlen);
533         break;
534
535     }
536     return rv;
537 }