Standardize progress callback for dhparam, dsaparam, etc.
[openssl.git] / apps / dhparam.c
1 /*
2  * Copyright 1995-2021 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 <openssl/opensslconf.h>
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <time.h>
15 #include <string.h>
16 #include "apps.h"
17 #include "progs.h"
18 #include <openssl/bio.h>
19 #include <openssl/err.h>
20 #include <openssl/bn.h>
21 #include <openssl/dsa.h>
22 #include <openssl/dh.h>
23 #include <openssl/x509.h>
24 #include <openssl/pem.h>
25 #include <openssl/core_names.h>
26 #include <openssl/core_dispatch.h>
27 #include <openssl/param_build.h>
28 #include <openssl/encoder.h>
29 #include <openssl/decoder.h>
30
31 #define DEFBITS 2048
32
33 static EVP_PKEY *dsa_to_dh(EVP_PKEY *dh);
34
35 typedef enum OPTION_choice {
36     OPT_COMMON,
37     OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT,
38     OPT_ENGINE, OPT_CHECK, OPT_TEXT, OPT_NOOUT,
39     OPT_DSAPARAM, OPT_2, OPT_3, OPT_5,
40     OPT_R_ENUM, OPT_PROV_ENUM
41 } OPTION_CHOICE;
42
43 const OPTIONS dhparam_options[] = {
44     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [numbits]\n"},
45
46     OPT_SECTION("General"),
47     {"help", OPT_HELP, '-', "Display this summary"},
48     {"check", OPT_CHECK, '-', "Check the DH parameters"},
49 #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_DEPRECATED_3_0)
50     {"dsaparam", OPT_DSAPARAM, '-',
51      "Read or generate DSA parameters, convert to DH"},
52 #endif
53 #ifndef OPENSSL_NO_ENGINE
54     {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
55 #endif
56
57     OPT_SECTION("Input"),
58     {"in", OPT_IN, '<', "Input file"},
59     {"inform", OPT_INFORM, 'F', "Input format, DER or PEM"},
60
61     OPT_SECTION("Output"),
62     {"out", OPT_OUT, '>', "Output file"},
63     {"outform", OPT_OUTFORM, 'F', "Output format, DER or PEM"},
64     {"text", OPT_TEXT, '-', "Print a text form of the DH parameters"},
65     {"noout", OPT_NOOUT, '-', "Don't output any DH parameters"},
66     {"2", OPT_2, '-', "Generate parameters using 2 as the generator value"},
67     {"3", OPT_3, '-', "Generate parameters using 3 as the generator value"},
68     {"5", OPT_5, '-', "Generate parameters using 5 as the generator value"},
69
70     OPT_R_OPTIONS,
71     OPT_PROV_OPTIONS,
72
73     OPT_PARAMETERS(),
74     {"numbits", 0, 0, "Number of bits if generating parameters (optional)"},
75     {NULL}
76 };
77
78 int dhparam_main(int argc, char **argv)
79 {
80     BIO *in = NULL, *out = NULL;
81     EVP_PKEY *pkey = NULL, *tmppkey = NULL;
82     EVP_PKEY_CTX *ctx = NULL;
83     char *infile = NULL, *outfile = NULL, *prog;
84     ENGINE *e = NULL;
85     int dsaparam = 0;
86     int text = 0, ret = 1, num = 0, g = 0;
87     int informat = FORMAT_PEM, outformat = FORMAT_PEM, check = 0, noout = 0;
88     OPTION_CHOICE o;
89
90     prog = opt_init(argc, argv, dhparam_options);
91     while ((o = opt_next()) != OPT_EOF) {
92         switch (o) {
93         case OPT_EOF:
94         case OPT_ERR:
95  opthelp:
96             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
97             goto end;
98         case OPT_HELP:
99             opt_help(dhparam_options);
100             ret = 0;
101             goto end;
102         case OPT_INFORM:
103             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
104                 goto opthelp;
105             break;
106         case OPT_OUTFORM:
107             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
108                 goto opthelp;
109             break;
110         case OPT_IN:
111             infile = opt_arg();
112             break;
113         case OPT_OUT:
114             outfile = opt_arg();
115             break;
116         case OPT_ENGINE:
117             e = setup_engine(opt_arg(), 0);
118             break;
119         case OPT_CHECK:
120             check = 1;
121             break;
122         case OPT_TEXT:
123             text = 1;
124             break;
125         case OPT_DSAPARAM:
126             dsaparam = 1;
127             break;
128         case OPT_2:
129             g = 2;
130             break;
131         case OPT_3:
132             g = 3;
133             break;
134         case OPT_5:
135             g = 5;
136             break;
137         case OPT_NOOUT:
138             noout = 1;
139             break;
140         case OPT_R_CASES:
141             if (!opt_rand(o))
142                 goto end;
143             break;
144         case OPT_PROV_CASES:
145             if (!opt_provider(o))
146                 goto end;
147             break;
148         }
149     }
150
151     /* One optional argument, bitsize to generate. */
152     argc = opt_num_rest();
153     argv = opt_rest();
154     if (argc == 1) {
155         if (!opt_int(argv[0], &num) || num <= 0)
156             goto opthelp;
157     } else if (!opt_check_rest_arg(NULL)) {
158         goto opthelp;
159     }
160     if (!app_RAND_load())
161         goto end;
162
163     if (g && !num)
164         num = DEFBITS;
165
166     if (dsaparam && g) {
167         BIO_printf(bio_err,
168                    "Error, generator may not be chosen for DSA parameters\n");
169         goto end;
170     }
171
172     out = bio_open_default(outfile, 'w', outformat);
173     if (out == NULL)
174         goto end;
175
176     /* DH parameters */
177     if (num && !g)
178         g = 2;
179
180     if (num) {
181         const char *alg = dsaparam ? "DSA" : "DH";
182
183         ctx = EVP_PKEY_CTX_new_from_name(NULL, alg, NULL);
184         if (ctx == NULL) {
185             BIO_printf(bio_err,
186                         "Error, %s param generation context allocation failed\n",
187                         alg);
188             goto end;
189         }
190         EVP_PKEY_CTX_set_cb(ctx, progress_cb);
191         EVP_PKEY_CTX_set_app_data(ctx, bio_err);
192         BIO_printf(bio_err,
193                     "Generating %s parameters, %d bit long %sprime\n",
194                     alg, num, dsaparam ? "" : "safe ");
195
196         if (EVP_PKEY_paramgen_init(ctx) <= 0) {
197             BIO_printf(bio_err,
198                         "Error, unable to initialise %s parameters\n",
199                         alg);
200             goto end;
201         }
202
203         if (dsaparam) {
204             if (!EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, num)) {
205                 BIO_printf(bio_err, "Error, unable to set DSA prime length\n");
206                 goto end;
207             }
208         } else {
209             if (!EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, num)) {
210                 BIO_printf(bio_err, "Error, unable to set DH prime length\n");
211                 goto end;
212             }
213             if (!EVP_PKEY_CTX_set_dh_paramgen_generator(ctx, g)) {
214                 BIO_printf(bio_err, "Error, unable to set generator\n");
215                 goto end;
216             }
217         }
218
219         tmppkey = app_paramgen(ctx, alg);
220         EVP_PKEY_CTX_free(ctx);
221         ctx = NULL;
222         if (dsaparam) {
223             pkey = dsa_to_dh(tmppkey);
224             if (pkey == NULL)
225                 goto end;
226             EVP_PKEY_free(tmppkey);
227         } else {
228             pkey = tmppkey;
229         }
230         tmppkey = NULL;
231     } else {
232         OSSL_DECODER_CTX *decoderctx = NULL;
233         const char *keytype = "DH";
234         int done;
235
236         in = bio_open_default(infile, 'r', informat);
237         if (in == NULL)
238             goto end;
239
240         do {
241             /*
242              * We assume we're done unless we explicitly want to retry and set
243              * this to 0 below.
244              */
245             done = 1;
246             /*
247             * We set NULL for the keytype to allow any key type. We don't know
248             * if we're going to get DH or DHX (or DSA in the event of dsaparam).
249             * We check that we got one of those key types afterwards.
250             */
251             decoderctx
252                 = OSSL_DECODER_CTX_new_for_pkey(&tmppkey,
253                                                 (informat == FORMAT_ASN1)
254                                                     ? "DER" : "PEM",
255                                                 NULL,
256                                                 (informat == FORMAT_ASN1)
257                                                     ? keytype : NULL,
258                                                 OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
259                                                 NULL, NULL);
260
261             if (decoderctx != NULL
262                     && !OSSL_DECODER_from_bio(decoderctx, in)
263                     && informat == FORMAT_ASN1
264                     && strcmp(keytype, "DH") == 0) {
265                 /*
266                 * When reading DER we explicitly state the expected keytype
267                 * because, unlike PEM, there is no header to declare what
268                 * the contents of the DER file are. The decoders just try
269                 * and guess. Unfortunately with DHX key types they may guess
270                 * wrong and think we have a DSA keytype. Therefore we try
271                 * both DH and DHX sequentially.
272                 */
273                 keytype = "DHX";
274                 /*
275                  * BIO_reset() returns 0 for success for file BIOs only!!!
276                  * This won't work for stdin (and never has done)
277                  */
278                 if (BIO_reset(in) == 0)
279                     done = 0;
280             }
281             OSSL_DECODER_CTX_free(decoderctx);
282         } while (!done);
283         if (tmppkey == NULL) {
284             BIO_printf(bio_err, "Error, unable to load parameters\n");
285             goto end;
286         }
287
288         if (dsaparam) {
289             if (!EVP_PKEY_is_a(tmppkey, "DSA")) {
290                 BIO_printf(bio_err, "Error, unable to load DSA parameters\n");
291                 goto end;
292             }
293             pkey = dsa_to_dh(tmppkey);
294             if (pkey == NULL)
295                 goto end;
296         } else {
297             if (!EVP_PKEY_is_a(tmppkey, "DH")
298                     && !EVP_PKEY_is_a(tmppkey, "DHX")) {
299                 BIO_printf(bio_err, "Error, unable to load DH parameters\n");
300                 goto end;
301             }
302             pkey = tmppkey;
303             tmppkey = NULL;
304         }
305     }
306
307     if (text)
308         EVP_PKEY_print_params(out, pkey, 4, NULL);
309
310     if (check) {
311         ctx = EVP_PKEY_CTX_new_from_pkey(NULL, pkey, NULL);
312         if (ctx == NULL) {
313             BIO_printf(bio_err, "Error, failed to check DH parameters\n");
314             goto end;
315         }
316         if (!EVP_PKEY_param_check(ctx)) {
317             BIO_printf(bio_err, "Error, invalid parameters generated\n");
318             goto end;
319         }
320         BIO_printf(bio_err, "DH parameters appear to be ok.\n");
321     }
322
323     if (!noout) {
324         OSSL_ENCODER_CTX *ectx =
325             OSSL_ENCODER_CTX_new_for_pkey(pkey,
326                                           OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS,
327                                           outformat == FORMAT_ASN1
328                                               ? "DER" : "PEM",
329                                           NULL, NULL);
330
331         if (ectx == NULL || !OSSL_ENCODER_to_bio(ectx, out)) {
332             OSSL_ENCODER_CTX_free(ectx);
333             BIO_printf(bio_err, "Error, unable to write DH parameters\n");
334             goto end;
335         }
336         OSSL_ENCODER_CTX_free(ectx);
337     }
338     ret = 0;
339  end:
340     if (ret != 0)
341         ERR_print_errors(bio_err);
342     BIO_free(in);
343     BIO_free_all(out);
344     EVP_PKEY_free(pkey);
345     EVP_PKEY_free(tmppkey);
346     EVP_PKEY_CTX_free(ctx);
347     release_engine(e);
348     return ret;
349 }
350
351 /*
352  * Historically we had the low level call DSA_dup_DH() to do this.
353  * That is now deprecated with no replacement. Since we still need to do this
354  * for backwards compatibility reasons, we do it "manually".
355  */
356 static EVP_PKEY *dsa_to_dh(EVP_PKEY *dh)
357 {
358     OSSL_PARAM_BLD *tmpl = NULL;
359     OSSL_PARAM *params = NULL;
360     BIGNUM *bn_p = NULL, *bn_q = NULL, *bn_g = NULL;
361     EVP_PKEY_CTX *ctx = NULL;
362     EVP_PKEY *pkey = NULL;
363
364     if (!EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_P, &bn_p)
365             || !EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_Q, &bn_q)
366             || !EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_G, &bn_g)) {
367         BIO_printf(bio_err, "Error, failed to set DH parameters\n");
368         goto err;
369     }
370
371     if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
372             || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P,
373                                         bn_p)
374             || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_Q,
375                                         bn_q)
376             || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G,
377                                         bn_g)
378             || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
379         BIO_printf(bio_err, "Error, failed to set DH parameters\n");
380         goto err;
381     }
382
383     ctx = EVP_PKEY_CTX_new_from_name(NULL, "DHX", NULL);
384     if (ctx == NULL
385             || EVP_PKEY_fromdata_init(ctx) <= 0
386             || EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params) <= 0) {
387         BIO_printf(bio_err, "Error, failed to set DH parameters\n");
388         goto err;
389     }
390
391  err:
392     EVP_PKEY_CTX_free(ctx);
393     OSSL_PARAM_free(params);
394     OSSL_PARAM_BLD_free(tmpl);
395     BN_free(bn_p);
396     BN_free(bn_q);
397     BN_free(bn_g);
398     return pkey;
399 }
400