Rename OPENSSL_CTX prefix to OSSL_LIB_CTX
[openssl.git] / apps / genpkey.c
1 /*
2  * Copyright 2006-2020 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 /* We need to use some engine deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
12
13 #include <stdio.h>
14 #include <string.h>
15 #include "apps.h"
16 #include "progs.h"
17 #include <openssl/pem.h>
18 #include <openssl/err.h>
19 #include <openssl/evp.h>
20 #ifndef OPENSSL_NO_ENGINE
21 # include <openssl/engine.h>
22 #endif
23
24 static int init_keygen_file(EVP_PKEY_CTX **pctx, const char *file, ENGINE *e,
25                             OSSL_LIB_CTX *libctx, const char *propq);
26 static int genpkey_cb(EVP_PKEY_CTX *ctx);
27
28 typedef enum OPTION_choice {
29     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
30     OPT_ENGINE, OPT_OUTFORM, OPT_OUT, OPT_PASS, OPT_PARAMFILE,
31     OPT_ALGORITHM, OPT_PKEYOPT, OPT_GENPARAM, OPT_TEXT, OPT_CIPHER,
32     OPT_CONFIG,
33     OPT_PROV_ENUM
34 } OPTION_CHOICE;
35
36 const OPTIONS genpkey_options[] = {
37     OPT_SECTION("General"),
38     {"help", OPT_HELP, '-', "Display this summary"},
39 #ifndef OPENSSL_NO_ENGINE
40     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
41 #endif
42     {"paramfile", OPT_PARAMFILE, '<', "Parameters file"},
43     {"algorithm", OPT_ALGORITHM, 's', "The public key algorithm"},
44     {"pkeyopt", OPT_PKEYOPT, 's',
45      "Set the public key algorithm option as opt:value"},
46      OPT_CONFIG_OPTION,
47
48     OPT_SECTION("Output"),
49     {"out", OPT_OUT, '>', "Output file"},
50     {"outform", OPT_OUTFORM, 'F', "output format (DER or PEM)"},
51     {"pass", OPT_PASS, 's', "Output file pass phrase source"},
52     {"genparam", OPT_GENPARAM, '-', "Generate parameters, not key"},
53     {"text", OPT_TEXT, '-', "Print the in text"},
54     {"", OPT_CIPHER, '-', "Cipher to use to encrypt the key"},
55
56     OPT_PROV_OPTIONS,
57
58     /* This is deliberately last. */
59     {OPT_HELP_STR, 1, 1,
60      "Order of options may be important!  See the documentation.\n"},
61     {NULL}
62 };
63
64 int genpkey_main(int argc, char **argv)
65 {
66     CONF *conf = NULL;
67     BIO *in = NULL, *out = NULL;
68     ENGINE *e = NULL;
69     EVP_PKEY *pkey = NULL;
70     EVP_PKEY_CTX *ctx = NULL;
71     char *outfile = NULL, *passarg = NULL, *pass = NULL, *prog;
72     const EVP_CIPHER *cipher = NULL;
73     OPTION_CHOICE o;
74     int outformat = FORMAT_PEM, text = 0, ret = 1, rv, do_param = 0;
75     int private = 0;
76     OSSL_LIB_CTX *libctx = app_get0_libctx();
77     const char *propq = app_get0_propq();
78
79     prog = opt_init(argc, argv, genpkey_options);
80     while ((o = opt_next()) != OPT_EOF) {
81         switch (o) {
82         case OPT_EOF:
83         case OPT_ERR:
84  opthelp:
85             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
86             goto end;
87         case OPT_HELP:
88             ret = 0;
89             opt_help(genpkey_options);
90             goto end;
91         case OPT_OUTFORM:
92             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
93                 goto opthelp;
94             break;
95         case OPT_OUT:
96             outfile = opt_arg();
97             break;
98         case OPT_PASS:
99             passarg = opt_arg();
100             break;
101         case OPT_ENGINE:
102             e = setup_engine(opt_arg(), 0);
103             break;
104         case OPT_PARAMFILE:
105             if (do_param == 1)
106                 goto opthelp;
107             if (!init_keygen_file(&ctx, opt_arg(), e, libctx, propq))
108                 goto end;
109             break;
110         case OPT_ALGORITHM:
111             if (!init_gen_str(&ctx, opt_arg(), e, do_param, libctx, propq))
112                 goto end;
113             break;
114         case OPT_PKEYOPT:
115             if (ctx == NULL) {
116                 BIO_printf(bio_err, "%s: No keytype specified.\n", prog);
117                 goto opthelp;
118             }
119             if (pkey_ctrl_string(ctx, opt_arg()) <= 0) {
120                 BIO_printf(bio_err,
121                            "%s: Error setting %s parameter:\n",
122                            prog, opt_arg());
123                 ERR_print_errors(bio_err);
124                 goto end;
125             }
126             break;
127         case OPT_GENPARAM:
128             if (ctx != NULL) {
129                 BIO_printf(bio_err,
130                            "%s: '-genparam' option must be set before"
131                             " the '-algorithm' option.\n", prog);
132                 goto opthelp;
133             }
134             do_param = 1;
135             break;
136         case OPT_TEXT:
137             text = 1;
138             break;
139         case OPT_CIPHER:
140             if (!opt_cipher(opt_unknown(), &cipher)
141                 || do_param == 1)
142                 goto opthelp;
143             if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE ||
144                 EVP_CIPHER_mode(cipher) == EVP_CIPH_CCM_MODE ||
145                 EVP_CIPHER_mode(cipher) == EVP_CIPH_XTS_MODE ||
146                 EVP_CIPHER_mode(cipher) == EVP_CIPH_OCB_MODE) {
147                 BIO_printf(bio_err, "%s: cipher mode not supported\n", prog);
148                 goto end;
149             }
150             break;
151         case OPT_CONFIG:
152             conf = app_load_config_modules(opt_arg());
153             if (conf == NULL)
154                 goto end;
155             break;
156         case OPT_PROV_CASES:
157             if (!opt_provider(o))
158                 goto end;
159             break;
160         }
161     }
162     argc = opt_num_rest();
163     if (argc != 0)
164         goto opthelp;
165
166     private = do_param ? 0 : 1;
167
168     if (ctx == NULL)
169         goto opthelp;
170
171     if (!app_passwd(passarg, NULL, &pass, NULL)) {
172         BIO_puts(bio_err, "Error getting password\n");
173         goto end;
174     }
175
176     out = bio_open_owner(outfile, outformat, private);
177     if (out == NULL)
178         goto end;
179
180     EVP_PKEY_CTX_set_cb(ctx, genpkey_cb);
181     EVP_PKEY_CTX_set_app_data(ctx, bio_err);
182
183     if (do_param) {
184         if (EVP_PKEY_paramgen(ctx, &pkey) <= 0) {
185             BIO_puts(bio_err, "Error generating parameters\n");
186             ERR_print_errors(bio_err);
187             goto end;
188         }
189     } else {
190         if (EVP_PKEY_keygen(ctx, &pkey) <= 0) {
191             BIO_puts(bio_err, "Error generating key\n");
192             ERR_print_errors(bio_err);
193             goto end;
194         }
195     }
196
197     if (do_param) {
198         rv = PEM_write_bio_Parameters(out, pkey);
199     } else if (outformat == FORMAT_PEM) {
200         assert(private);
201         rv = PEM_write_bio_PrivateKey(out, pkey, cipher, NULL, 0, NULL, pass);
202     } else if (outformat == FORMAT_ASN1) {
203         assert(private);
204         rv = i2d_PrivateKey_bio(out, pkey);
205     } else {
206         BIO_printf(bio_err, "Bad format specified for key\n");
207         goto end;
208     }
209
210     ret = 0;
211
212     if (rv <= 0) {
213         BIO_puts(bio_err, "Error writing key\n");
214         ERR_print_errors(bio_err);
215         ret = 1;
216     }
217
218     if (text) {
219         if (do_param)
220             rv = EVP_PKEY_print_params(out, pkey, 0, NULL);
221         else
222             rv = EVP_PKEY_print_private(out, pkey, 0, NULL);
223
224         if (rv <= 0) {
225             BIO_puts(bio_err, "Error printing key\n");
226             ERR_print_errors(bio_err);
227             ret = 1;
228         }
229     }
230
231  end:
232     EVP_PKEY_free(pkey);
233     EVP_PKEY_CTX_free(ctx);
234     BIO_free_all(out);
235     BIO_free(in);
236     release_engine(e);
237     OPENSSL_free(pass);
238     NCONF_free(conf);
239     return ret;
240 }
241
242 static int init_keygen_file(EVP_PKEY_CTX **pctx, const char *file, ENGINE *e,
243                             OSSL_LIB_CTX *libctx, const char *propq)
244 {
245     BIO *pbio;
246     EVP_PKEY *pkey = NULL;
247     EVP_PKEY_CTX *ctx = NULL;
248     if (*pctx) {
249         BIO_puts(bio_err, "Parameters already set!\n");
250         return 0;
251     }
252
253     pbio = BIO_new_file(file, "r");
254     if (pbio == NULL) {
255         BIO_printf(bio_err, "Can't open parameter file %s\n", file);
256         return 0;
257     }
258
259     pkey = PEM_read_bio_Parameters(pbio, NULL);
260     BIO_free(pbio);
261
262     if (pkey == NULL) {
263         BIO_printf(bio_err, "Error reading parameter file %s\n", file);
264         return 0;
265     }
266
267     if (e != NULL)
268         ctx = EVP_PKEY_CTX_new(pkey, e);
269     else
270         ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq);
271     if (ctx == NULL)
272         goto err;
273     if (EVP_PKEY_keygen_init(ctx) <= 0)
274         goto err;
275     EVP_PKEY_free(pkey);
276     *pctx = ctx;
277     return 1;
278
279  err:
280     BIO_puts(bio_err, "Error initializing context\n");
281     ERR_print_errors(bio_err);
282     EVP_PKEY_CTX_free(ctx);
283     EVP_PKEY_free(pkey);
284     return 0;
285
286 }
287
288 int init_gen_str(EVP_PKEY_CTX **pctx,
289                  const char *algname, ENGINE *e, int do_param,
290                  OSSL_LIB_CTX *libctx, const char *propq)
291 {
292     EVP_PKEY_CTX *ctx = NULL;
293     const EVP_PKEY_ASN1_METHOD *ameth;
294     ENGINE *tmpeng = NULL;
295     int pkey_id;
296
297     if (*pctx) {
298         BIO_puts(bio_err, "Algorithm already set!\n");
299         return 0;
300     }
301
302     if (libctx == NULL || e != NULL) {
303         ameth = EVP_PKEY_asn1_find_str(&tmpeng, algname, -1);
304
305 #if !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_DEPRECATED_3_0)
306         if (ameth == NULL && e != NULL)
307             ameth = ENGINE_get_pkey_asn1_meth_str(e, algname, -1);
308 #endif
309         if (ameth == NULL) {
310             BIO_printf(bio_err, "Algorithm %s not found\n", algname);
311             return 0;
312         }
313         ERR_clear_error();
314
315         EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL, ameth);
316 #if !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_DEPRECATED_3_0)
317         ENGINE_finish(tmpeng);
318 #endif
319         ctx = EVP_PKEY_CTX_new_id(pkey_id, e);
320     } else {
321         ctx = EVP_PKEY_CTX_new_from_name(libctx, algname, propq);
322     }
323
324     if (!ctx)
325         goto err;
326     if (do_param) {
327         if (EVP_PKEY_paramgen_init(ctx) <= 0)
328             goto err;
329     } else {
330         if (EVP_PKEY_keygen_init(ctx) <= 0)
331             goto err;
332     }
333
334     *pctx = ctx;
335     return 1;
336
337  err:
338     BIO_printf(bio_err, "Error initializing %s context\n", algname);
339     ERR_print_errors(bio_err);
340     EVP_PKEY_CTX_free(ctx);
341     return 0;
342
343 }
344
345 static int genpkey_cb(EVP_PKEY_CTX *ctx)
346 {
347     char c = '*';
348     BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
349     int p;
350     p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
351     if (p == 0)
352         c = '.';
353     if (p == 1)
354         c = '+';
355     if (p == 2)
356         c = '*';
357     if (p == 3)
358         c = '\n';
359     BIO_write(b, &c, 1);
360     (void)BIO_flush(b);
361     return 1;
362 }