Extend test_ssl_get_shared_ciphers
[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;
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 = 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         }
260     } else {
261         in = bio_open_default(infile, 'r', informat);
262         if (in == NULL)
263             goto end;
264
265 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
266         if (dsaparam) {
267             DSA *dsa;
268
269             if (informat == FORMAT_ASN1)
270                 dsa = d2i_DSAparams_bio(in, NULL);
271             else                /* informat == FORMAT_PEM */
272                 dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);
273
274             if (dsa == NULL) {
275                 BIO_printf(bio_err, "unable to load DSA parameters\n");
276                 ERR_print_errors(bio_err);
277                 goto end;
278             }
279
280             dh = DSA_dup_DH(dsa);
281             DSA_free(dsa);
282             if (dh == NULL) {
283                 ERR_print_errors(bio_err);
284                 goto end;
285             }
286         } else
287 #endif
288         {
289             if (informat == FORMAT_ASN1) {
290                 /*
291                  * We have no PEM header to determine what type of DH params it
292                  * is. We'll just try both.
293                  */
294                 dh = ASN1_d2i_bio_of(DH, DH_new, d2i_DHparams, in, NULL);
295                 /* BIO_reset() returns 0 for success for file BIOs only!!! */
296                 if (dh == NULL && BIO_reset(in) == 0)
297                     dh = ASN1_d2i_bio_of(DH, DH_new, d2i_DHxparams, in, NULL);
298             } else {
299                 /* informat == FORMAT_PEM */
300                 dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
301             }
302
303             if (dh == NULL) {
304                 BIO_printf(bio_err, "unable to load DH parameters\n");
305                 ERR_print_errors(bio_err);
306                 goto end;
307             }
308         }
309         /* dh != NULL */
310     }
311
312     if (text)
313         EVP_PKEY_print_params(out, pkey, 4, NULL);
314
315     if (check) {
316         if (!EVP_PKEY_param_check(ctx) /* DH_check(dh, &i) */) {
317             ERR_print_errors(bio_err);
318             BIO_printf(bio_err, "ERROR: Invalid parameters generated\n");
319             goto end;
320         }
321         BIO_printf(bio_err, "DH parameters appear to be ok.\n");
322         if (num != 0) {
323             /*
324              * We have generated parameters but DH_check() indicates they are
325              * invalid! This should never happen!
326              */
327             BIO_printf(bio_err, "ERROR: Invalid parameters generated\n");
328             goto end;
329         }
330     }
331     if (C) {
332         unsigned char *data;
333         int len, bits;
334         const BIGNUM *pbn, *gbn;
335
336         dh = EVP_PKEY_get0_DH(pkey);
337         len = EVP_PKEY_size(pkey);
338         bits = EVP_PKEY_size(pkey);
339         DH_get0_pqg(dh, &pbn, NULL, &gbn);
340         data = app_malloc(len, "print a BN");
341
342         BIO_printf(out, "static DH *get_dh%d(void)\n{\n", bits);
343         print_bignum_var(out, pbn, "dhp", bits, data);
344         print_bignum_var(out, gbn, "dhg", bits, data);
345         BIO_printf(out, "    DH *dh = DH_new();\n"
346                         "    BIGNUM *p, *g;\n"
347                         "\n"
348                         "    if (dh == NULL)\n"
349                         "        return NULL;\n");
350         BIO_printf(out, "    p = BN_bin2bn(dhp_%d, sizeof(dhp_%d), NULL);\n",
351                    bits, bits);
352         BIO_printf(out, "    g = BN_bin2bn(dhg_%d, sizeof(dhg_%d), NULL);\n",
353                    bits, bits);
354         BIO_printf(out, "    if (p == NULL || g == NULL\n"
355                         "            || !DH_set0_pqg(dh, p, NULL, g)) {\n"
356                         "        DH_free(dh);\n"
357                         "        BN_free(p);\n"
358                         "        BN_free(g);\n"
359                         "        return NULL;\n"
360                         "    }\n");
361         if (DH_get_length(dh) > 0)
362             BIO_printf(out,
363                         "    if (!DH_set_length(dh, %ld)) {\n"
364                         "        DH_free(dh);\n"
365                         "        return NULL;\n"
366                         "    }\n", DH_get_length(dh));
367         BIO_printf(out, "    return dh;\n}\n");
368         OPENSSL_free(data);
369     }
370
371     if (!noout) {
372         const BIGNUM *q;
373         DH_get0_pqg(dh, NULL, &q, NULL);
374         if (outformat == FORMAT_ASN1) {
375             if (q != NULL)
376                 i = ASN1_i2d_bio_of(DH, i2d_DHxparams, out, dh);
377             else
378                 i = ASN1_i2d_bio_of(DH, i2d_DHparams, out, dh);
379         } else if (q != NULL) {
380             i = PEM_write_bio_DHxparams(out, dh);
381         } else {
382             i = PEM_write_bio_DHparams(out, dh);
383         }
384         if (!i) {
385             BIO_printf(bio_err, "unable to write DH parameters\n");
386             ERR_print_errors(bio_err);
387             goto end;
388         }
389     }
390     ret = 0;
391  end:
392     BIO_free(in);
393     BIO_free_all(out);
394     EVP_PKEY_free(pkey);
395     EVP_PKEY_CTX_free(ctx);
396     release_engine(e);
397     return ret;
398 }
399
400 static int common_dh_cb(int p, BIO *b)
401 {
402     static const char symbols[] = ".+*\n";
403     char c = (p >= 0 && (size_t)p < sizeof(symbols) - 1) ? symbols[p] : '?';
404
405     BIO_write(b, &c, 1);
406     (void)BIO_flush(b);
407     return 1;
408 }
409
410 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
411 static int dh_cb(int p, int n, BN_GENCB *cb)
412 {
413     return common_dh_cb(p, BN_GENCB_get_arg(cb));
414 }
415 #endif
416
417 static int gendh_cb(EVP_PKEY_CTX *ctx)
418 {
419     return common_dh_cb(EVP_PKEY_CTX_get_keygen_info(ctx, 0),
420                         EVP_PKEY_CTX_get_app_data(ctx));
421 }