xref: /dragonfly/crypto/libressl/apps/openssl/rsa.c (revision 6f5ec8b5)
1 /* $OpenBSD: rsa.c,v 1.16 2022/01/14 09:26:41 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>
60 
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <time.h>
65 
66 #include "apps.h"
67 #include "progs.h"
68 
69 #include <openssl/bio.h>
70 #include <openssl/bn.h>
71 #include <openssl/err.h>
72 #include <openssl/evp.h>
73 #include <openssl/pem.h>
74 #include <openssl/rsa.h>
75 #include <openssl/x509.h>
76 
77 static struct {
78 	int check;
79 	const EVP_CIPHER *enc;
80 	char *infile;
81 	int informat;
82 	int modulus;
83 	int noout;
84 	char *outfile;
85 	int outformat;
86 	char *passargin;
87 	char *passargout;
88 	int pubin;
89 	int pubout;
90 	int pvk_encr;
91 	int text;
92 } rsa_config;
93 
94 static int
95 rsa_opt_cipher(int argc, char **argv, int *argsused)
96 {
97 	char *name = argv[0];
98 
99 	if (*name++ != '-')
100 		return (1);
101 
102 	if ((rsa_config.enc = EVP_get_cipherbyname(name)) == NULL) {
103 		fprintf(stderr, "Invalid cipher '%s'\n", name);
104 		return (1);
105 	}
106 
107 	*argsused = 1;
108 	return (0);
109 }
110 
111 static const struct option rsa_options[] = {
112 	{
113 		.name = "check",
114 		.desc = "Check consistency of RSA private key",
115 		.type = OPTION_FLAG,
116 		.opt.flag = &rsa_config.check,
117 	},
118 	{
119 		.name = "in",
120 		.argname = "file",
121 		.desc = "Input file (default stdin)",
122 		.type = OPTION_ARG,
123 		.opt.arg = &rsa_config.infile,
124 	},
125 	{
126 		.name = "inform",
127 		.argname = "format",
128 		.desc = "Input format (DER, NET or PEM (default))",
129 		.type = OPTION_ARG_FORMAT,
130 		.opt.value = &rsa_config.informat,
131 	},
132 	{
133 		.name = "modulus",
134 		.desc = "Print the RSA key modulus",
135 		.type = OPTION_FLAG,
136 		.opt.flag = &rsa_config.modulus,
137 	},
138 	{
139 		.name = "noout",
140 		.desc = "Do not print encoded version of the key",
141 		.type = OPTION_FLAG,
142 		.opt.flag = &rsa_config.noout,
143 	},
144 	{
145 		.name = "out",
146 		.argname = "file",
147 		.desc = "Output file (default stdout)",
148 		.type = OPTION_ARG,
149 		.opt.arg = &rsa_config.outfile,
150 	},
151 	{
152 		.name = "outform",
153 		.argname = "format",
154 		.desc = "Output format (DER, NET or PEM (default PEM))",
155 		.type = OPTION_ARG_FORMAT,
156 		.opt.value = &rsa_config.outformat,
157 	},
158 	{
159 		.name = "passin",
160 		.argname = "src",
161 		.desc = "Input file passphrase source",
162 		.type = OPTION_ARG,
163 		.opt.arg = &rsa_config.passargin,
164 	},
165 	{
166 		.name = "passout",
167 		.argname = "src",
168 		.desc = "Output file passphrase source",
169 		.type = OPTION_ARG,
170 		.opt.arg = &rsa_config.passargout,
171 	},
172 	{
173 		.name = "pubin",
174 		.desc = "Expect a public key (default private key)",
175 		.type = OPTION_VALUE,
176 		.value = 1,
177 		.opt.value = &rsa_config.pubin,
178 	},
179 	{
180 		.name = "pubout",
181 		.desc = "Output a public key (default private key)",
182 		.type = OPTION_VALUE,
183 		.value = 1,
184 		.opt.value = &rsa_config.pubout,
185 	},
186 	{
187 		.name = "pvk-none",
188 		.type = OPTION_VALUE,
189 		.value = 0,
190 		.opt.value = &rsa_config.pvk_encr,
191 	},
192 	{
193 		.name = "pvk-strong",
194 		.type = OPTION_VALUE,
195 		.value = 2,
196 		.opt.value = &rsa_config.pvk_encr,
197 	},
198 	{
199 		.name = "pvk-weak",
200 		.type = OPTION_VALUE,
201 		.value = 1,
202 		.opt.value = &rsa_config.pvk_encr,
203 	},
204 	{
205 		.name = "RSAPublicKey_in",
206 		.type = OPTION_VALUE,
207 		.value = 2,
208 		.opt.value = &rsa_config.pubin,
209 	},
210 	{
211 		.name = "RSAPublicKey_out",
212 		.type = OPTION_VALUE,
213 		.value = 2,
214 		.opt.value = &rsa_config.pubout,
215 	},
216 	{
217 		.name = "text",
218 		.desc = "Print in plain text in addition to encoded",
219 		.type = OPTION_FLAG,
220 		.opt.flag = &rsa_config.text,
221 	},
222 	{
223 		.name = NULL,
224 		.type = OPTION_ARGV_FUNC,
225 		.opt.argvfunc = rsa_opt_cipher,
226 	},
227 	{ NULL }
228 };
229 
230 static void
231 rsa_usage()
232 {
233 	int n = 0;
234 
235 	fprintf(stderr,
236 	    "usage: rsa [-ciphername] [-check] [-in file] "
237 	    "[-inform fmt]\n"
238 	    "    [-modulus] [-noout] [-out file] [-outform fmt] "
239 	    "[-passin src]\n"
240 	    "    [-passout src] [-pubin] [-pubout] [-text]\n\n");
241 	options_usage(rsa_options);
242 	fprintf(stderr, "\n");
243 
244 	fprintf(stderr, "Valid ciphername values:\n\n");
245 	OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, show_cipher, &n);
246 	fprintf(stderr, "\n");
247 }
248 
249 int
250 rsa_main(int argc, char **argv)
251 {
252 	int ret = 1;
253 	RSA *rsa = NULL;
254 	int i;
255 	BIO *out = NULL;
256 	char *passin = NULL, *passout = NULL;
257 
258 	if (single_execution) {
259 		if (pledge("stdio cpath wpath rpath tty", NULL) == -1) {
260 			perror("pledge");
261 			exit(1);
262 		}
263 	}
264 
265 	memset(&rsa_config, 0, sizeof(rsa_config));
266 	rsa_config.pvk_encr = 2;
267 	rsa_config.informat = FORMAT_PEM;
268 	rsa_config.outformat = FORMAT_PEM;
269 
270 	if (options_parse(argc, argv, rsa_options, NULL, NULL) != 0) {
271 		rsa_usage();
272 		goto end;
273 	}
274 
275 	if (!app_passwd(bio_err, rsa_config.passargin, rsa_config.passargout,
276 	    &passin, &passout)) {
277 		BIO_printf(bio_err, "Error getting passwords\n");
278 		goto end;
279 	}
280 	if (rsa_config.check && rsa_config.pubin) {
281 		BIO_printf(bio_err, "Only private keys can be checked\n");
282 		goto end;
283 	}
284 	out = BIO_new(BIO_s_file());
285 
286 	{
287 		EVP_PKEY *pkey;
288 
289 		if (rsa_config.pubin) {
290 			int tmpformat = -1;
291 			if (rsa_config.pubin == 2) {
292 				if (rsa_config.informat == FORMAT_PEM)
293 					tmpformat = FORMAT_PEMRSA;
294 				else if (rsa_config.informat == FORMAT_ASN1)
295 					tmpformat = FORMAT_ASN1RSA;
296 			} else
297 				tmpformat = rsa_config.informat;
298 
299 			pkey = load_pubkey(bio_err, rsa_config.infile,
300 			    tmpformat, 1, passin, "Public Key");
301 		} else
302 			pkey = load_key(bio_err, rsa_config.infile,
303 			    rsa_config.informat, 1, passin, "Private Key");
304 
305 		if (pkey != NULL)
306 			rsa = EVP_PKEY_get1_RSA(pkey);
307 		EVP_PKEY_free(pkey);
308 	}
309 
310 	if (rsa == NULL) {
311 		ERR_print_errors(bio_err);
312 		goto end;
313 	}
314 	if (rsa_config.outfile == NULL) {
315 		BIO_set_fp(out, stdout, BIO_NOCLOSE);
316 	} else {
317 		if (BIO_write_filename(out, rsa_config.outfile) <= 0) {
318 			perror(rsa_config.outfile);
319 			goto end;
320 		}
321 	}
322 
323 	if (rsa_config.text)
324 		if (!RSA_print(out, rsa, 0)) {
325 			perror(rsa_config.outfile);
326 			ERR_print_errors(bio_err);
327 			goto end;
328 		}
329 	if (rsa_config.modulus) {
330 		BIO_printf(out, "Modulus=");
331 		BN_print(out, RSA_get0_n(rsa));
332 		BIO_printf(out, "\n");
333 	}
334 	if (rsa_config.check) {
335 		int r = RSA_check_key(rsa);
336 
337 		if (r == 1)
338 			BIO_printf(out, "RSA key ok\n");
339 		else if (r == 0) {
340 			unsigned long err;
341 
342 			while ((err = ERR_peek_error()) != 0 &&
343 			    ERR_GET_LIB(err) == ERR_LIB_RSA &&
344 			    ERR_GET_FUNC(err) == RSA_F_RSA_CHECK_KEY &&
345 			    ERR_GET_REASON(err) != ERR_R_MALLOC_FAILURE) {
346 				BIO_printf(out, "RSA key error: %s\n",
347 				    ERR_reason_error_string(err));
348 				ERR_get_error();	/* remove e from error
349 							 * stack */
350 			}
351 		}
352 		if (r == -1 || ERR_peek_error() != 0) {	/* should happen only if
353 							 * r == -1 */
354 			ERR_print_errors(bio_err);
355 			goto end;
356 		}
357 	}
358 	if (rsa_config.noout) {
359 		ret = 0;
360 		goto end;
361 	}
362 	BIO_printf(bio_err, "writing RSA key\n");
363 	if (rsa_config.outformat == FORMAT_ASN1) {
364 		if (rsa_config.pubout || rsa_config.pubin) {
365 			if (rsa_config.pubout == 2)
366 				i = i2d_RSAPublicKey_bio(out, rsa);
367 			else
368 				i = i2d_RSA_PUBKEY_bio(out, rsa);
369 		} else
370 			i = i2d_RSAPrivateKey_bio(out, rsa);
371 	} else if (rsa_config.outformat == FORMAT_PEM) {
372 		if (rsa_config.pubout || rsa_config.pubin) {
373 			if (rsa_config.pubout == 2)
374 				i = PEM_write_bio_RSAPublicKey(out, rsa);
375 			else
376 				i = PEM_write_bio_RSA_PUBKEY(out, rsa);
377 		} else
378 			i = PEM_write_bio_RSAPrivateKey(out, rsa,
379 			    rsa_config.enc, NULL, 0, NULL, passout);
380 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_RC4)
381 	} else if (rsa_config.outformat == FORMAT_MSBLOB ||
382 	    rsa_config.outformat == FORMAT_PVK) {
383 		EVP_PKEY *pk;
384 		pk = EVP_PKEY_new();
385 		EVP_PKEY_set1_RSA(pk, rsa);
386 		if (rsa_config.outformat == FORMAT_PVK)
387 			i = i2b_PVK_bio(out, pk, rsa_config.pvk_encr, 0,
388 			    passout);
389 		else if (rsa_config.pubin || rsa_config.pubout)
390 			i = i2b_PublicKey_bio(out, pk);
391 		else
392 			i = i2b_PrivateKey_bio(out, pk);
393 		EVP_PKEY_free(pk);
394 #endif
395 	} else {
396 		BIO_printf(bio_err,
397 		    "bad output format specified for outfile\n");
398 		goto end;
399 	}
400 	if (i <= 0) {
401 		BIO_printf(bio_err, "unable to write key\n");
402 		ERR_print_errors(bio_err);
403 	} else
404 		ret = 0;
405 
406  end:
407 	BIO_free_all(out);
408 	RSA_free(rsa);
409 	free(passin);
410 	free(passout);
411 
412 	return (ret);
413 }
414