xref: /openbsd/usr.bin/openssl/dh.c (revision 4bdff4be)
1 /* $OpenBSD: dh.c,v 1.15 2023/03/06 14:32:05 tb Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 
59 #include <openssl/opensslconf.h>	/* for OPENSSL_NO_DH */
60 
61 #ifndef OPENSSL_NO_DH
62 
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <time.h>
67 
68 #include "apps.h"
69 
70 #include <openssl/bio.h>
71 #include <openssl/bn.h>
72 #include <openssl/err.h>
73 #include <openssl/dh.h>
74 #include <openssl/pem.h>
75 #include <openssl/x509.h>
76 
77 static struct {
78 	int C;
79 	int check;
80 	char *infile;
81 	int informat;
82 	int noout;
83 	char *outfile;
84 	int outformat;
85 	int text;
86 } cfg;
87 
88 static const struct option dh_options[] = {
89 	{
90 		.name = "C",
91 		.desc = "Convert DH parameters into C code",
92 		.type = OPTION_FLAG,
93 		.opt.flag = &cfg.C,
94 	},
95 	{
96 		.name = "check",
97 		.desc = "Check the DH parameters",
98 		.type = OPTION_FLAG,
99 		.opt.flag = &cfg.check,
100 	},
101 	{
102 		.name = "in",
103 		.argname = "file",
104 		.desc = "Input file (default stdin)",
105 		.type = OPTION_ARG,
106 		.opt.arg = &cfg.infile,
107 	},
108 	{
109 		.name = "inform",
110 		.argname = "format",
111 		.desc = "Input format (DER or PEM (default))",
112 		.type = OPTION_ARG_FORMAT,
113 		.opt.value = &cfg.informat,
114 	},
115 	{
116 		.name = "noout",
117 		.desc = "No output",
118 		.type = OPTION_FLAG,
119 		.opt.flag = &cfg.noout,
120 	},
121 	{
122 		.name = "out",
123 		.argname = "file",
124 		.desc = "Output file (default stdout)",
125 		.type = OPTION_ARG,
126 		.opt.arg = &cfg.outfile,
127 	},
128 	{
129 		.name = "outform",
130 		.argname = "format",
131 		.desc = "Output format (DER or PEM (default))",
132 		.type = OPTION_ARG_FORMAT,
133 		.opt.value = &cfg.outformat,
134 	},
135 	{
136 		.name = "text",
137 		.desc = "Print a text form of the DH parameters",
138 		.type = OPTION_FLAG,
139 		.opt.flag = &cfg.text,
140 	},
141 	{ NULL },
142 };
143 
144 static void
145 dh_usage(void)
146 {
147 	fprintf(stderr,
148 	    "usage: dh [-C] [-check] [-in file] [-inform format]\n"
149 	    "    [-noout] [-out file] [-outform format] [-text]\n\n");
150 	options_usage(dh_options);
151 }
152 
153 int
154 dh_main(int argc, char **argv)
155 {
156 	DH *dh = NULL;
157 	int i;
158 	BIO *in = NULL, *out = NULL;
159 	int ret = 1;
160 
161 	if (pledge("stdio cpath wpath rpath", NULL) == -1) {
162 		perror("pledge");
163 		exit(1);
164 	}
165 
166 	memset(&cfg, 0, sizeof(cfg));
167 
168 	cfg.informat = FORMAT_PEM;
169 	cfg.outformat = FORMAT_PEM;
170 
171 	if (options_parse(argc, argv, dh_options, NULL, NULL) != 0) {
172 		dh_usage();
173 		goto end;
174 	}
175 
176 	in = BIO_new(BIO_s_file());
177 	out = BIO_new(BIO_s_file());
178 	if (in == NULL || out == NULL) {
179 		ERR_print_errors(bio_err);
180 		goto end;
181 	}
182 	if (cfg.infile == NULL)
183 		BIO_set_fp(in, stdin, BIO_NOCLOSE);
184 	else {
185 		if (BIO_read_filename(in, cfg.infile) <= 0) {
186 			perror(cfg.infile);
187 			goto end;
188 		}
189 	}
190 	if (cfg.outfile == NULL) {
191 		BIO_set_fp(out, stdout, BIO_NOCLOSE);
192 	} else {
193 		if (BIO_write_filename(out, cfg.outfile) <= 0) {
194 			perror(cfg.outfile);
195 			goto end;
196 		}
197 	}
198 
199 	if (cfg.informat == FORMAT_ASN1)
200 		dh = d2i_DHparams_bio(in, NULL);
201 	else if (cfg.informat == FORMAT_PEM)
202 		dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL);
203 	else {
204 		BIO_printf(bio_err, "bad input format specified\n");
205 		goto end;
206 	}
207 	if (dh == NULL) {
208 		BIO_printf(bio_err, "unable to load DH parameters\n");
209 		ERR_print_errors(bio_err);
210 		goto end;
211 	}
212 	if (cfg.text) {
213 		DHparams_print(out, dh);
214 	}
215 	if (cfg.check) {
216 		if (!DH_check(dh, &i)) {
217 			ERR_print_errors(bio_err);
218 			goto end;
219 		}
220 		if (i & DH_CHECK_P_NOT_PRIME)
221 			printf("p value is not prime\n");
222 		if (i & DH_CHECK_P_NOT_SAFE_PRIME)
223 			printf("p value is not a safe prime\n");
224 		if (i & DH_UNABLE_TO_CHECK_GENERATOR)
225 			printf("unable to check the generator value\n");
226 		if (i & DH_NOT_SUITABLE_GENERATOR)
227 			printf("the g value is not a generator\n");
228 		if (i == 0)
229 			printf("DH parameters appear to be ok.\n");
230 	}
231 	if (cfg.C) {
232 		unsigned char *data;
233 		int len, l, bits;
234 
235 		len = BN_num_bytes(DH_get0_p(dh));
236 		bits = BN_num_bits(DH_get0_p(dh));
237 		data = malloc(len);
238 		if (data == NULL) {
239 			perror("malloc");
240 			goto end;
241 		}
242 		l = BN_bn2bin(DH_get0_p(dh), data);
243 		printf("static unsigned char dh%d_p[] = {", bits);
244 		for (i = 0; i < l; i++) {
245 			if ((i % 12) == 0)
246 				printf("\n\t");
247 			printf("0x%02X, ", data[i]);
248 		}
249 		printf("\n\t};\n");
250 
251 		l = BN_bn2bin(DH_get0_g(dh), data);
252 		printf("static unsigned char dh%d_g[] = {", bits);
253 		for (i = 0; i < l; i++) {
254 			if ((i % 12) == 0)
255 				printf("\n\t");
256 			printf("0x%02X, ", data[i]);
257 		}
258 		printf("\n\t};\n\n");
259 
260 		printf("DH *get_dh%d()\n\t{\n", bits);
261 		printf("\tDH *dh;\n");
262 		printf("\tBIGNUM *p = NULL, *g = NULL;\n\n");
263 		printf("\tif ((dh = DH_new()) == NULL) return(NULL);\n");
264 		printf("\tp = BN_bin2bn(dh%d_p, sizeof(dh%d_p), NULL);\n",
265 		    bits, bits);
266 		printf("\tg = BN_bin2bn(dh%d_g, sizeof(dh%d_g), NULL);\n",
267 		    bits, bits);
268 		printf("\tif (p == NULL || g == NULL)\n");
269 		printf("\t\t{ BN_free(p); BN_free(q); DH_free(dh); return(NULL); }\n");
270 		printf("\tDH_set0_pqg(dh, p, NULL, g);\n");
271 		printf("\treturn(dh);\n\t}\n");
272 		free(data);
273 	}
274 	if (!cfg.noout) {
275 		if (cfg.outformat == FORMAT_ASN1)
276 			i = i2d_DHparams_bio(out, dh);
277 		else if (cfg.outformat == FORMAT_PEM)
278 			i = PEM_write_bio_DHparams(out, dh);
279 		else {
280 			BIO_printf(bio_err, "bad output format specified for outfile\n");
281 			goto end;
282 		}
283 		if (!i) {
284 			BIO_printf(bio_err, "unable to write DH parameters\n");
285 			ERR_print_errors(bio_err);
286 			goto end;
287 		}
288 	}
289 	ret = 0;
290 
291  end:
292 	BIO_free(in);
293 	BIO_free_all(out);
294 	DH_free(dh);
295 
296 	return (ret);
297 }
298 #endif
299