Make error output of dhparams and dsaparams app more consistent
[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                    "Error, 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                 goto end;
203
204             BN_GENCB_set(cb, dh_cb, bio_err);
205
206             BIO_printf(bio_err,
207                        "Generating DSA parameters, %d bit long prime\n", num);
208             if (dsa == NULL
209                 || !DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL,
210                                                cb)) {
211                 DSA_free(dsa);
212                 BN_GENCB_free(cb);
213                 BIO_printf(bio_err, "Error, unable to generate DSA parameters\n");
214                 goto end;
215             }
216
217             dh = alloc_dh = DSA_dup_DH(dsa);
218             DSA_free(dsa);
219             BN_GENCB_free(cb);
220             if (dh == NULL)
221                 goto end;
222         } else
223 #endif
224         {
225             ctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
226             if (ctx == NULL) {
227                 BIO_printf(bio_err,
228                            "Error, DH key generation context allocation failed\n");
229                 goto end;
230             }
231             EVP_PKEY_CTX_set_cb(ctx, gendh_cb);
232             EVP_PKEY_CTX_set_app_data(ctx, bio_err);
233             BIO_printf(bio_err,
234                        "Generating DH parameters, %d bit long safe prime, generator %d\n",
235                        num, g);
236             BIO_printf(bio_err, "This is going to take a long time\n");
237             if (!EVP_PKEY_paramgen_init(ctx)) {
238                 BIO_printf(bio_err,
239                            "Error, unable to initialise DH param generation\n");
240                 goto end;
241             }
242
243             if (!EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, num)) {
244                 BIO_printf(bio_err, "Error, unable to set DH prime length\n");
245                 goto end;
246             }
247             if (!EVP_PKEY_paramgen(ctx, &pkey)) {
248                 BIO_printf(bio_err, "Error, DH generation failed\n");
249                 goto end;
250             }
251             dh = EVP_PKEY_get0_DH(pkey);
252         }
253     } else {
254         in = bio_open_default(infile, 'r', informat);
255         if (in == NULL)
256             goto end;
257
258 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
259         if (dsaparam) {
260             DSA *dsa;
261
262             if (informat == FORMAT_ASN1)
263                 dsa = d2i_DSAparams_bio(in, NULL);
264             else                /* informat == FORMAT_PEM */
265                 dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);
266
267             if (dsa == NULL) {
268                 BIO_printf(bio_err, "Error, unable to load DSA parameters\n");
269                 goto end;
270             }
271
272             dh = alloc_dh = DSA_dup_DH(dsa);
273             DSA_free(dsa);
274             if (dh == NULL)
275                 goto end;
276         } else
277 #endif
278         {
279             if (informat == FORMAT_ASN1) {
280                 /*
281                  * We have no PEM header to determine what type of DH params it
282                  * is. We'll just try both.
283                  */
284                 dh = alloc_dh = ASN1_d2i_bio_of(DH, DH_new, d2i_DHparams, in, NULL);
285                 /* BIO_reset() returns 0 for success for file BIOs only!!! */
286                 if (dh == NULL && BIO_reset(in) == 0)
287                     dh = alloc_dh = ASN1_d2i_bio_of(DH, DH_new, d2i_DHxparams, in, NULL);
288             } else {
289                 /* informat == FORMAT_PEM */
290                 dh = alloc_dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
291             }
292
293             if (dh == NULL) {
294                 BIO_printf(bio_err, "Error, unable to load DH parameters\n");
295                 goto end;
296             }
297         }
298         /* dh != NULL */
299     }
300
301     if (text)
302         EVP_PKEY_print_params(out, pkey, 4, NULL);
303
304     if (check) {
305         if (!EVP_PKEY_param_check(ctx) /* DH_check(dh, &i) */) {
306             BIO_printf(bio_err, "Error, invalid parameters generated\n");
307             goto end;
308         }
309         BIO_printf(bio_err, "DH parameters appear to be ok.\n");
310         if (num != 0) {
311             /*
312              * We have generated parameters but DH_check() indicates they are
313              * invalid! This should never happen!
314              */
315             BIO_printf(bio_err, "Error, invalid parameters generated\n");
316             goto end;
317         }
318     }
319     if (C) {
320         unsigned char *data;
321         int len, bits;
322         const BIGNUM *pbn, *gbn;
323
324         dh = EVP_PKEY_get0_DH(pkey);
325         len = EVP_PKEY_size(pkey);
326         bits = EVP_PKEY_size(pkey);
327         DH_get0_pqg(dh, &pbn, NULL, &gbn);
328         data = app_malloc(len, "print a BN");
329
330         BIO_printf(out, "static DH *get_dh%d(void)\n{\n", bits);
331         print_bignum_var(out, pbn, "dhp", bits, data);
332         print_bignum_var(out, gbn, "dhg", bits, data);
333         BIO_printf(out, "    DH *dh = DH_new();\n"
334                         "    BIGNUM *p, *g;\n"
335                         "\n"
336                         "    if (dh == NULL)\n"
337                         "        return NULL;\n");
338         BIO_printf(out, "    p = BN_bin2bn(dhp_%d, sizeof(dhp_%d), NULL);\n",
339                    bits, bits);
340         BIO_printf(out, "    g = BN_bin2bn(dhg_%d, sizeof(dhg_%d), NULL);\n",
341                    bits, bits);
342         BIO_printf(out, "    if (p == NULL || g == NULL\n"
343                         "            || !DH_set0_pqg(dh, p, NULL, g)) {\n"
344                         "        DH_free(dh);\n"
345                         "        BN_free(p);\n"
346                         "        BN_free(g);\n"
347                         "        return NULL;\n"
348                         "    }\n");
349         if (DH_get_length(dh) > 0)
350             BIO_printf(out,
351                         "    if (!DH_set_length(dh, %ld)) {\n"
352                         "        DH_free(dh);\n"
353                         "        return NULL;\n"
354                         "    }\n", DH_get_length(dh));
355         BIO_printf(out, "    return dh;\n}\n");
356         OPENSSL_free(data);
357     }
358
359     if (!noout) {
360         const BIGNUM *q;
361         DH_get0_pqg(dh, NULL, &q, NULL);
362         if (outformat == FORMAT_ASN1) {
363             if (q != NULL)
364                 i = ASN1_i2d_bio_of(DH, i2d_DHxparams, out, dh);
365             else
366                 i = ASN1_i2d_bio_of(DH, i2d_DHparams, out, dh);
367         } else if (q != NULL) {
368             i = PEM_write_bio_DHxparams(out, dh);
369         } else {
370             i = PEM_write_bio_DHparams(out, dh);
371         }
372         if (!i) {
373             BIO_printf(bio_err, "Error, unable to write DH parameters\n");
374             goto end;
375         }
376     }
377     ret = 0;
378  end:
379     if (ret != 0)
380         ERR_print_errors(bio_err);
381     DH_free(alloc_dh);
382     BIO_free(in);
383     BIO_free_all(out);
384     EVP_PKEY_free(pkey);
385     EVP_PKEY_CTX_free(ctx);
386     release_engine(e);
387     return ret;
388 }
389
390 static int common_dh_cb(int p, BIO *b)
391 {
392     static const char symbols[] = ".+*\n";
393     char c = (p >= 0 && (size_t)p < sizeof(symbols) - 1) ? symbols[p] : '?';
394
395     BIO_write(b, &c, 1);
396     (void)BIO_flush(b);
397     return 1;
398 }
399
400 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_DEPRECATED_3_0)
401 static int dh_cb(int p, int n, BN_GENCB *cb)
402 {
403     return common_dh_cb(p, BN_GENCB_get_arg(cb));
404 }
405 #endif
406
407 static int gendh_cb(EVP_PKEY_CTX *ctx)
408 {
409     return common_dh_cb(EVP_PKEY_CTX_get_keygen_info(ctx, 0),
410                         EVP_PKEY_CTX_get_app_data(ctx));
411 }