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