Convert dhparam to be fully based on EVP
[openssl.git] / apps / dhparam.c
1 /*
2  * Copyright 1995-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 #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/x509.h>
22 #include <openssl/pem.h>
23 #include <openssl/core_names.h>
24 #include <openssl/param_build.h>
25 #include <openssl/decoder.h>
26
27 #define DEFBITS 2048
28
29 static EVP_PKEY *dsa_to_dh(EVP_PKEY *dh);
30 static int gendh_cb(EVP_PKEY_CTX *ctx);
31
32 typedef enum OPTION_choice {
33     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
34     OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT,
35     OPT_ENGINE, OPT_CHECK, OPT_TEXT, OPT_NOOUT,
36     OPT_DSAPARAM, OPT_2, OPT_3, OPT_5,
37     OPT_R_ENUM, OPT_PROV_ENUM
38 } OPTION_CHOICE;
39
40 const OPTIONS dhparam_options[] = {
41     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [numbits]\n"},
42
43     OPT_SECTION("General"),
44     {"help", OPT_HELP, '-', "Display this summary"},
45     {"check", OPT_CHECK, '-', "Check the DH parameters"},
46 #ifndef OPENSSL_NO_DSA
47     {"dsaparam", OPT_DSAPARAM, '-',
48      "Read or generate DSA parameters, convert to DH"},
49 #endif
50 #ifndef OPENSSL_NO_ENGINE
51     {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
52 #endif
53
54     OPT_SECTION("Input"),
55     {"in", OPT_IN, '<', "Input file"},
56     {"inform", OPT_INFORM, 'F', "Input format, DER or PEM"},
57
58     OPT_SECTION("Output"),
59     {"out", OPT_OUT, '>', "Output file"},
60     {"outform", OPT_OUTFORM, 'F', "Output format, DER or PEM"},
61     {"text", OPT_TEXT, '-', "Print a text form of the DH parameters"},
62     {"noout", OPT_NOOUT, '-', "Don't output any DH parameters"},
63     {"2", OPT_2, '-', "Generate parameters using 2 as the generator value"},
64     {"3", OPT_3, '-', "Generate parameters using 3 as the generator value"},
65     {"5", OPT_5, '-', "Generate parameters using 5 as the generator value"},
66
67     OPT_R_OPTIONS,
68     OPT_PROV_OPTIONS,
69
70     OPT_PARAMETERS(),
71     {"numbits", 0, 0, "Number of bits if generating parameters (optional)"},
72     {NULL}
73 };
74
75 int dhparam_main(int argc, char **argv)
76 {
77     BIO *in = NULL, *out = NULL;
78     DH *dh = NULL, *alloc_dh = NULL;
79     EVP_PKEY *pkey = NULL, *tmppkey = NULL;
80     EVP_PKEY_CTX *ctx = NULL;
81     char *infile = NULL, *outfile = NULL, *prog;
82     ENGINE *e = NULL;
83 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
84     int dsaparam = 0;
85 #endif
86     int i, 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 # ifdef OPENSSL_NO_DEPRECATED_3_0
127             BIO_printf(bio_err, "The dsaparam option is deprecated.\n");
128 # else
129             dsaparam = 1;
130 # endif
131             break;
132         case OPT_2:
133             g = 2;
134             break;
135         case OPT_3:
136             g = 3;
137             break;
138         case OPT_5:
139             g = 5;
140             break;
141         case OPT_NOOUT:
142             noout = 1;
143             break;
144         case OPT_R_CASES:
145             if (!opt_rand(o))
146                 goto end;
147             break;
148         case OPT_PROV_CASES:
149             if (!opt_provider(o))
150                 goto end;
151             break;
152         }
153     }
154     argc = opt_num_rest();
155     argv = opt_rest();
156
157     if (argv[0] != NULL && (!opt_int(argv[0], &num) || num <= 0))
158         goto end;
159
160     if (g && !num)
161         num = DEFBITS;
162
163     if (dsaparam && g) {
164         BIO_printf(bio_err,
165                    "Error, generator may not be chosen for DSA parameters\n");
166         goto end;
167     }
168
169     out = bio_open_default(outfile, 'w', outformat);
170     if (out == NULL)
171         goto end;
172
173     /* DH parameters */
174     if (num && !g)
175         g = 2;
176
177     if (num) {
178         const char *alg = dsaparam ? "DSA" : "DH";
179
180         ctx = EVP_PKEY_CTX_new_from_name(NULL, alg, NULL);
181         if (ctx == NULL) {
182             BIO_printf(bio_err,
183                         "Error, %s param generation context allocation failed\n",
184                         alg);
185             goto end;
186         }
187         EVP_PKEY_CTX_set_cb(ctx, gendh_cb);
188         EVP_PKEY_CTX_set_app_data(ctx, bio_err);
189         BIO_printf(bio_err,
190                     "Generating %s parameters, %d bit long %sprime\n",
191                     alg, num, dsaparam ? "" : "safe ");
192
193         if (!EVP_PKEY_paramgen_init(ctx)) {
194             BIO_printf(bio_err,
195                         "Error, unable to initialise %s parameters\n",
196                         alg);
197             goto end;
198         }
199
200         if (dsaparam) {
201             if (!EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, num)) {
202                 BIO_printf(bio_err, "Error, unable to set DSA prime length\n");
203                 goto end;
204             }
205         } else {
206             if (!EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, num)) {
207                 BIO_printf(bio_err, "Error, unable to set DH prime length\n");
208                 goto end;
209             }
210             if (!EVP_PKEY_CTX_set_dh_paramgen_generator(ctx, g)) {
211                 BIO_printf(bio_err, "Error, unable to set generator\n");
212                 goto end;
213             }
214         }
215
216         if (!EVP_PKEY_paramgen(ctx, &tmppkey)) {
217             BIO_printf(bio_err, "Error, %s generation failed\n", alg);
218             goto end;
219         }
220
221         EVP_PKEY_CTX_free(ctx);
222         ctx = NULL;
223         if (dsaparam) {
224             pkey = dsa_to_dh(tmppkey);
225             if (pkey == NULL)
226                 goto end;
227             EVP_PKEY_free(tmppkey);
228         } else {
229             pkey = tmppkey;
230         }
231         tmppkey = NULL;
232     } else {
233         OSSL_DECODER_CTX *decoderctx = NULL;
234         const char *keytype = "DH";
235         int done;
236
237         in = bio_open_default(infile, 'r', informat);
238         if (in == NULL)
239             goto end;
240
241         do {
242             /*
243              * We assume we're done unless we explicitly want to retry and set
244              * this to 0 below.
245              */
246             done = 1;
247             /*
248             * We set NULL for the keytype to allow any key type. We don't know
249             * if we're going to get DH or DHX (or DSA in the event of dsaparam).
250             * We check that we got one of those key types afterwards.
251             */
252             decoderctx
253                 = OSSL_DECODER_CTX_new_by_EVP_PKEY(&tmppkey,
254                                                     (informat == FORMAT_ASN1)
255                                                     ? "DER" : "PEM",
256                                                     (informat == FORMAT_ASN1)
257                                                     ? keytype : NULL,
258                                                     NULL, NULL);
259
260             if (decoderctx != NULL
261                     && !OSSL_DECODER_from_bio(decoderctx, in)
262                     && informat == FORMAT_ASN1
263                     && strcmp(keytype, "DH") == 0) {
264                 /*
265                 * When reading DER we explicitly state the expected keytype
266                 * because, unlike PEM, there is no header to declare what
267                 * the contents of the DER file are. The decoders just try
268                 * and guess. Unfortunately with DHX key types they may guess
269                 * wrong and think we have a DSA keytype. Therefore we try
270                 * both DH and DHX sequentially.
271                 */
272                 keytype = "DHX";
273                 /*
274                     * BIO_reset() returns 0 for success for file BIOs only!!!
275                     * This won't work for stdin (and never has done)
276                     * TODO: We should fix this at some point
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_name(NULL, "DH", 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) /* DH_check(dh, &i) */) {
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         if (num != 0) {
322             /*
323              * We have generated parameters but DH_check() indicates they are
324              * invalid! This should never happen!
325              */
326             BIO_printf(bio_err, "Error, invalid parameters generated\n");
327             goto end;
328         }
329     }
330
331     if (!noout) {
332         const BIGNUM *q;
333         /* Temporary: FIXME */
334         dh = EVP_PKEY_get0_DH(pkey);
335         DH_get0_pqg(dh, NULL, &q, NULL);
336         if (outformat == FORMAT_ASN1) {
337             if (q != NULL)
338                 i = ASN1_i2d_bio_of(DH, i2d_DHxparams, out, dh);
339             else
340                 i = ASN1_i2d_bio_of(DH, i2d_DHparams, out, dh);
341         } else if (q != NULL) {
342             i = PEM_write_bio_DHxparams(out, dh);
343         } else {
344             i = PEM_write_bio_DHparams(out, dh);
345         }
346         if (!i) {
347             BIO_printf(bio_err, "Error, unable to write DH parameters\n");
348             goto end;
349         }
350     }
351     ret = 0;
352  end:
353     if (ret != 0)
354         ERR_print_errors(bio_err);
355     DH_free(alloc_dh);
356     BIO_free(in);
357     BIO_free_all(out);
358     EVP_PKEY_free(pkey);
359     EVP_PKEY_free(tmppkey);
360     EVP_PKEY_CTX_free(ctx);
361     release_engine(e);
362     return ret;
363 }
364
365 /*
366  * Historically we had the low level call DSA_dup_DH() to do this.
367  * That is now deprecated with no replacement. Since we still need to do this
368  * for backwards compatibility reasons, we do it "manually".
369  */
370 static EVP_PKEY *dsa_to_dh(EVP_PKEY *dh)
371 {
372     OSSL_PARAM_BLD *tmpl = NULL;
373     OSSL_PARAM *params = NULL;
374     BIGNUM *bn_p = NULL, *bn_q = NULL, *bn_g = NULL;
375     EVP_PKEY_CTX *ctx = NULL;
376     EVP_PKEY *pkey = NULL;
377
378     if (!EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_P, &bn_p)
379             || !EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_Q, &bn_q)
380             || !EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_G, &bn_g)) {
381         BIO_printf(bio_err, "Error, failed to set DH parameters\n");
382         goto err;
383     }
384
385     if ((tmpl = OSSL_PARAM_BLD_new()) == NULL
386             || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P,
387                                         bn_p)
388             || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_Q,
389                                         bn_q)
390             || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G,
391                                         bn_g)
392             || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
393         BIO_printf(bio_err, "Error, failed to set DH parameters\n");
394         goto err;
395     }
396
397     ctx = EVP_PKEY_CTX_new_from_name(NULL, "DHX", NULL);
398     if (ctx == NULL
399             || !EVP_PKEY_param_fromdata_init(ctx)
400             || !EVP_PKEY_fromdata(ctx, &pkey, params)) {
401         BIO_printf(bio_err, "Error, failed to set DH parameters\n");
402         goto err;
403     }
404
405  err:
406     EVP_PKEY_CTX_free(ctx);
407     OSSL_PARAM_BLD_free_params(params);
408     OSSL_PARAM_BLD_free(tmpl);
409     BN_free(bn_p);
410     BN_free(bn_q);
411     BN_free(bn_g);
412     return pkey;
413 }
414
415 static int gendh_cb(EVP_PKEY_CTX *ctx)
416 {
417     int p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
418     BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
419     static const char symbols[] = ".+*\n";
420     char c = (p >= 0 && (size_t)p < sizeof(symbols) - 1) ? symbols[p] : '?';
421
422     BIO_write(b, &c, 1);
423     (void)BIO_flush(b);
424     return 1;
425 }