APPS: Fix 'openssl dhparam'
[oweals/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 #ifndef OPENSSL_NO_DEPRECATED_3_0
11 /* We need to use some deprecated APIs */
12 # define OPENSSL_SUPPRESS_DEPRECATED
13 #endif
14 #include <openssl/opensslconf.h>
15
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <time.h>
19 #include <string.h>
20 #include "apps.h"
21 #include "progs.h"
22 #include <openssl/bio.h>
23 #include <openssl/err.h>
24 #include <openssl/bn.h>
25 #include <openssl/dh.h>
26 #include <openssl/x509.h>
27 #include <openssl/pem.h>
28
29 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
30 # include <openssl/dsa.h>
31 #endif
32
33 #define DEFBITS 2048
34
35 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
36 static int dh_cb(int p, int n, BN_GENCB *cb);
37 #endif
38 static int gendh_cb(EVP_PKEY_CTX *ctx);
39
40 typedef enum OPTION_choice {
41     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
42     OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT,
43     OPT_ENGINE, OPT_CHECK, OPT_TEXT, OPT_NOOUT,
44     OPT_DSAPARAM, OPT_C, OPT_2, OPT_3, OPT_5,
45     OPT_R_ENUM, OPT_PROV_ENUM
46 } OPTION_CHOICE;
47
48 const OPTIONS dhparam_options[] = {
49     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [numbits]\n"},
50
51     OPT_SECTION("General"),
52     {"help", OPT_HELP, '-', "Display this summary"},
53     {"check", OPT_CHECK, '-', "Check the DH parameters"},
54 #ifndef OPENSSL_NO_DSA
55     {"dsaparam", OPT_DSAPARAM, '-',
56      "Read or generate DSA parameters, convert to DH"},
57 #endif
58 #ifndef OPENSSL_NO_ENGINE
59     {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
60 #endif
61
62     OPT_SECTION("Input"),
63     {"in", OPT_IN, '<', "Input file"},
64     {"inform", OPT_INFORM, 'F', "Input format, DER or PEM"},
65
66     OPT_SECTION("Output"),
67     {"out", OPT_OUT, '>', "Output file"},
68     {"outform", OPT_OUTFORM, 'F', "Output format, DER or PEM"},
69     {"text", OPT_TEXT, '-', "Print a text form of the DH parameters"},
70     {"noout", OPT_NOOUT, '-', "Don't output any DH parameters"},
71     {"C", OPT_C, '-', "Print C code"},
72     {"2", OPT_2, '-', "Generate parameters using 2 as the generator value"},
73     {"3", OPT_3, '-', "Generate parameters using 3 as the generator value"},
74     {"5", OPT_5, '-', "Generate parameters using 5 as the generator value"},
75
76     OPT_R_OPTIONS,
77     OPT_PROV_OPTIONS,
78
79     OPT_PARAMETERS(),
80     {"numbits", 0, 0, "Number of bits if generating parameters (optional)"},
81     {NULL}
82 };
83
84 int dhparam_main(int argc, char **argv)
85 {
86     BIO *in = NULL, *out = NULL;
87     DH *dh = NULL, *alloc_dh = NULL;
88     EVP_PKEY *pkey = NULL;
89     EVP_PKEY_CTX *ctx = NULL;
90     char *infile = NULL, *outfile = NULL, *prog;
91     ENGINE *e = NULL;
92 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
93     int dsaparam = 0;
94 #endif
95     int i, text = 0, C = 0, ret = 1, num = 0, g = 0;
96     int informat = FORMAT_PEM, outformat = FORMAT_PEM, check = 0, noout = 0;
97     OPTION_CHOICE o;
98
99     prog = opt_init(argc, argv, dhparam_options);
100     while ((o = opt_next()) != OPT_EOF) {
101         switch (o) {
102         case OPT_EOF:
103         case OPT_ERR:
104  opthelp:
105             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
106             goto end;
107         case OPT_HELP:
108             opt_help(dhparam_options);
109             ret = 0;
110             goto end;
111         case OPT_INFORM:
112             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
113                 goto opthelp;
114             break;
115         case OPT_OUTFORM:
116             if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
117                 goto opthelp;
118             break;
119         case OPT_IN:
120             infile = opt_arg();
121             break;
122         case OPT_OUT:
123             outfile = opt_arg();
124             break;
125         case OPT_ENGINE:
126             e = setup_engine(opt_arg(), 0);
127             break;
128         case OPT_CHECK:
129             check = 1;
130             break;
131         case OPT_TEXT:
132             text = 1;
133             break;
134         case OPT_DSAPARAM:
135 #ifndef OPENSSL_NO_DSA
136 # ifdef OPENSSL_NO_DEPRECATED_3_0
137             BIO_printf(bio_err, "The dsaparam option is deprecated.\n");
138 # else
139             dsaparam = 1;
140 # endif
141 #endif
142             break;
143         case OPT_C:
144             C = 1;
145             break;
146         case OPT_2:
147             g = 2;
148             break;
149         case OPT_3:
150             g = 3;
151             break;
152         case OPT_5:
153             g = 5;
154             break;
155         case OPT_NOOUT:
156             noout = 1;
157             break;
158         case OPT_R_CASES:
159             if (!opt_rand(o))
160                 goto end;
161             break;
162         case OPT_PROV_CASES:
163             if (!opt_provider(o))
164                 goto end;
165             break;
166         }
167     }
168     argc = opt_num_rest();
169     argv = opt_rest();
170
171     if (argv[0] != NULL && (!opt_int(argv[0], &num) || num <= 0))
172         goto end;
173
174     if (g && !num)
175         num = DEFBITS;
176
177 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
178     if (dsaparam && g) {
179         BIO_printf(bio_err,
180                    "generator may not be chosen for DSA parameters\n");
181         goto end;
182     }
183 #endif
184
185     out = bio_open_default(outfile, 'w', outformat);
186     if (out == NULL)
187         goto end;
188
189     /* DH parameters */
190     if (num && !g)
191         g = 2;
192
193     if (num) {
194
195
196 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
197         if (dsaparam) {
198             DSA *dsa = DSA_new();
199             BN_GENCB *cb  = BN_GENCB_new();
200
201             if (cb == NULL) {
202                 ERR_print_errors(bio_err);
203                 goto end;
204             }
205
206             BN_GENCB_set(cb, dh_cb, bio_err);
207
208             BIO_printf(bio_err,
209                        "Generating DSA parameters, %d bit long prime\n", num);
210             if (dsa == NULL
211                 || !DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL,
212                                                cb)) {
213                 DSA_free(dsa);
214                 BN_GENCB_free(cb);
215                 ERR_print_errors(bio_err);
216                 goto end;
217             }
218
219             dh = alloc_dh = DSA_dup_DH(dsa);
220             DSA_free(dsa);
221             BN_GENCB_free(cb);
222             if (dh == NULL) {
223                 ERR_print_errors(bio_err);
224                 goto end;
225             }
226         } else
227 #endif
228         {
229             ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
230             if (ctx == NULL) {
231                 ERR_print_errors(bio_err);
232                 BIO_printf(bio_err,
233                            "Error, DH key generation context allocation failed\n");
234                 goto end;
235             }
236             EVP_PKEY_CTX_set_cb(ctx, gendh_cb);
237             EVP_PKEY_CTX_set_app_data(ctx, bio_err);
238             BIO_printf(bio_err,
239                        "Generating DH parameters, %d bit long safe prime, generator %d\n",
240                        num, g);
241             BIO_printf(bio_err, "This is going to take a long time\n");
242             if (!EVP_PKEY_paramgen_init(ctx)) {
243                 BIO_printf(bio_err,
244                            "Error, unable to initialise DH param generation\n");
245                 ERR_print_errors(bio_err);
246                 goto end;
247             }
248
249             if (!EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, num)) {
250                 BIO_printf(bio_err, "Error, unable to set DH prime length\n");
251                 ERR_print_errors(bio_err);
252                 goto end;
253             }
254             if (!EVP_PKEY_paramgen(ctx, &pkey)) {
255                 BIO_printf(bio_err, "Error, DH generation failed\n");
256                 ERR_print_errors(bio_err);
257                 goto end;
258             }
259             dh = EVP_PKEY_get0_DH(pkey);
260         }
261     } else {
262         in = bio_open_default(infile, 'r', informat);
263         if (in == NULL)
264             goto end;
265
266 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
267         if (dsaparam) {
268             DSA *dsa;
269
270             if (informat == FORMAT_ASN1)
271                 dsa = d2i_DSAparams_bio(in, NULL);
272             else                /* informat == FORMAT_PEM */
273                 dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);
274
275             if (dsa == NULL) {
276                 BIO_printf(bio_err, "unable to load DSA parameters\n");
277                 ERR_print_errors(bio_err);
278                 goto end;
279             }
280
281             dh = alloc_dh = DSA_dup_DH(dsa);
282             DSA_free(dsa);
283             if (dh == NULL) {
284                 ERR_print_errors(bio_err);
285                 goto end;
286             }
287         } else
288 #endif
289         {
290             if (informat == FORMAT_ASN1) {
291                 /*
292                  * We have no PEM header to determine what type of DH params it
293                  * is. We'll just try both.
294                  */
295                 dh = alloc_dh = ASN1_d2i_bio_of(DH, DH_new, d2i_DHparams, in, NULL);
296                 /* BIO_reset() returns 0 for success for file BIOs only!!! */
297                 if (dh == NULL && BIO_reset(in) == 0)
298                     dh = alloc_dh = ASN1_d2i_bio_of(DH, DH_new, d2i_DHxparams, in, NULL);
299             } else {
300                 /* informat == FORMAT_PEM */
301                 dh = alloc_dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
302             }
303
304             if (dh == NULL) {
305                 BIO_printf(bio_err, "unable to load DH parameters\n");
306                 ERR_print_errors(bio_err);
307                 goto end;
308             }
309         }
310         /* dh != NULL */
311     }
312
313     if (text)
314         EVP_PKEY_print_params(out, pkey, 4, NULL);
315
316     if (check) {
317         if (!EVP_PKEY_param_check(ctx) /* DH_check(dh, &i) */) {
318             ERR_print_errors(bio_err);
319             BIO_printf(bio_err, "ERROR: Invalid parameters generated\n");
320             goto end;
321         }
322         BIO_printf(bio_err, "DH parameters appear to be ok.\n");
323         if (num != 0) {
324             /*
325              * We have generated parameters but DH_check() indicates they are
326              * invalid! This should never happen!
327              */
328             BIO_printf(bio_err, "ERROR: Invalid parameters generated\n");
329             goto end;
330         }
331     }
332     if (C) {
333         unsigned char *data;
334         int len, bits;
335         const BIGNUM *pbn, *gbn;
336
337         dh = EVP_PKEY_get0_DH(pkey);
338         len = EVP_PKEY_size(pkey);
339         bits = EVP_PKEY_size(pkey);
340         DH_get0_pqg(dh, &pbn, NULL, &gbn);
341         data = app_malloc(len, "print a BN");
342
343         BIO_printf(out, "static DH *get_dh%d(void)\n{\n", bits);
344         print_bignum_var(out, pbn, "dhp", bits, data);
345         print_bignum_var(out, gbn, "dhg", bits, data);
346         BIO_printf(out, "    DH *dh = DH_new();\n"
347                         "    BIGNUM *p, *g;\n"
348                         "\n"
349                         "    if (dh == NULL)\n"
350                         "        return NULL;\n");
351         BIO_printf(out, "    p = BN_bin2bn(dhp_%d, sizeof(dhp_%d), NULL);\n",
352                    bits, bits);
353         BIO_printf(out, "    g = BN_bin2bn(dhg_%d, sizeof(dhg_%d), NULL);\n",
354                    bits, bits);
355         BIO_printf(out, "    if (p == NULL || g == NULL\n"
356                         "            || !DH_set0_pqg(dh, p, NULL, g)) {\n"
357                         "        DH_free(dh);\n"
358                         "        BN_free(p);\n"
359                         "        BN_free(g);\n"
360                         "        return NULL;\n"
361                         "    }\n");
362         if (DH_get_length(dh) > 0)
363             BIO_printf(out,
364                         "    if (!DH_set_length(dh, %ld)) {\n"
365                         "        DH_free(dh);\n"
366                         "        return NULL;\n"
367                         "    }\n", DH_get_length(dh));
368         BIO_printf(out, "    return dh;\n}\n");
369         OPENSSL_free(data);
370     }
371
372     if (!noout) {
373         const BIGNUM *q;
374         DH_get0_pqg(dh, NULL, &q, NULL);
375         if (outformat == FORMAT_ASN1) {
376             if (q != NULL)
377                 i = ASN1_i2d_bio_of(DH, i2d_DHxparams, out, dh);
378             else
379                 i = ASN1_i2d_bio_of(DH, i2d_DHparams, out, dh);
380         } else if (q != NULL) {
381             i = PEM_write_bio_DHxparams(out, dh);
382         } else {
383             i = PEM_write_bio_DHparams(out, dh);
384         }
385         if (!i) {
386             BIO_printf(bio_err, "unable to write DH parameters\n");
387             ERR_print_errors(bio_err);
388             goto end;
389         }
390     }
391     ret = 0;
392  end:
393     DH_free(alloc_dh);
394     BIO_free(in);
395     BIO_free_all(out);
396     EVP_PKEY_free(pkey);
397     EVP_PKEY_CTX_free(ctx);
398     release_engine(e);
399     return ret;
400 }
401
402 static int common_dh_cb(int p, BIO *b)
403 {
404     static const char symbols[] = ".+*\n";
405     char c = (p >= 0 && (size_t)p < sizeof(symbols) - 1) ? symbols[p] : '?';
406
407     BIO_write(b, &c, 1);
408     (void)BIO_flush(b);
409     return 1;
410 }
411
412 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
413 static int dh_cb(int p, int n, BN_GENCB *cb)
414 {
415     return common_dh_cb(p, BN_GENCB_get_arg(cb));
416 }
417 #endif
418
419 static int gendh_cb(EVP_PKEY_CTX *ctx)
420 {
421     return common_dh_cb(EVP_PKEY_CTX_get_keygen_info(ctx, 0),
422                         EVP_PKEY_CTX_get_app_data(ctx));
423 }