xref: /openbsd-src/usr.bin/openssl/rsa.c (revision 68dd5bb1859285b71cb62a10bf107b8ad54064d9)
1 /* $OpenBSD: rsa.c,v 1.19 2023/07/23 11:39:29 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 } cfg;
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 ((cfg.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 = &cfg.check,
117 	},
118 	{
119 		.name = "in",
120 		.argname = "file",
121 		.desc = "Input file (default stdin)",
122 		.type = OPTION_ARG,
123 		.opt.arg = &cfg.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 = &cfg.informat,
131 	},
132 	{
133 		.name = "modulus",
134 		.desc = "Print the RSA key modulus",
135 		.type = OPTION_FLAG,
136 		.opt.flag = &cfg.modulus,
137 	},
138 	{
139 		.name = "noout",
140 		.desc = "Do not print encoded version of the key",
141 		.type = OPTION_FLAG,
142 		.opt.flag = &cfg.noout,
143 	},
144 	{
145 		.name = "out",
146 		.argname = "file",
147 		.desc = "Output file (default stdout)",
148 		.type = OPTION_ARG,
149 		.opt.arg = &cfg.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 = &cfg.outformat,
157 	},
158 	{
159 		.name = "passin",
160 		.argname = "src",
161 		.desc = "Input file passphrase source",
162 		.type = OPTION_ARG,
163 		.opt.arg = &cfg.passargin,
164 	},
165 	{
166 		.name = "passout",
167 		.argname = "src",
168 		.desc = "Output file passphrase source",
169 		.type = OPTION_ARG,
170 		.opt.arg = &cfg.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 = &cfg.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 = &cfg.pubout,
185 	},
186 	{
187 		.name = "pvk-none",
188 		.type = OPTION_VALUE,
189 		.value = 0,
190 		.opt.value = &cfg.pvk_encr,
191 	},
192 	{
193 		.name = "pvk-strong",
194 		.type = OPTION_VALUE,
195 		.value = 2,
196 		.opt.value = &cfg.pvk_encr,
197 	},
198 	{
199 		.name = "pvk-weak",
200 		.type = OPTION_VALUE,
201 		.value = 1,
202 		.opt.value = &cfg.pvk_encr,
203 	},
204 	{
205 		.name = "RSAPublicKey_in",
206 		.type = OPTION_VALUE,
207 		.value = 2,
208 		.opt.value = &cfg.pubin,
209 	},
210 	{
211 		.name = "RSAPublicKey_out",
212 		.type = OPTION_VALUE,
213 		.value = 2,
214 		.opt.value = &cfg.pubout,
215 	},
216 	{
217 		.name = "text",
218 		.desc = "Print in plain text in addition to encoded",
219 		.type = OPTION_FLAG,
220 		.opt.flag = &cfg.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(void)
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 (pledge("stdio cpath wpath rpath tty", NULL) == -1) {
259 		perror("pledge");
260 		exit(1);
261 	}
262 
263 	memset(&cfg, 0, sizeof(cfg));
264 	cfg.pvk_encr = 2;
265 	cfg.informat = FORMAT_PEM;
266 	cfg.outformat = FORMAT_PEM;
267 
268 	if (options_parse(argc, argv, rsa_options, NULL, NULL) != 0) {
269 		rsa_usage();
270 		goto end;
271 	}
272 
273 	if (!app_passwd(bio_err, cfg.passargin, cfg.passargout,
274 	    &passin, &passout)) {
275 		BIO_printf(bio_err, "Error getting passwords\n");
276 		goto end;
277 	}
278 	if (cfg.check && cfg.pubin) {
279 		BIO_printf(bio_err, "Only private keys can be checked\n");
280 		goto end;
281 	}
282 	out = BIO_new(BIO_s_file());
283 
284 	{
285 		EVP_PKEY *pkey;
286 
287 		if (cfg.pubin) {
288 			int tmpformat = -1;
289 			if (cfg.pubin == 2) {
290 				if (cfg.informat == FORMAT_PEM)
291 					tmpformat = FORMAT_PEMRSA;
292 				else if (cfg.informat == FORMAT_ASN1)
293 					tmpformat = FORMAT_ASN1RSA;
294 			} else
295 				tmpformat = cfg.informat;
296 
297 			pkey = load_pubkey(bio_err, cfg.infile,
298 			    tmpformat, 1, passin, "Public Key");
299 		} else
300 			pkey = load_key(bio_err, cfg.infile,
301 			    cfg.informat, 1, passin, "Private Key");
302 
303 		if (pkey != NULL)
304 			rsa = EVP_PKEY_get1_RSA(pkey);
305 		EVP_PKEY_free(pkey);
306 	}
307 
308 	if (rsa == NULL) {
309 		ERR_print_errors(bio_err);
310 		goto end;
311 	}
312 	if (cfg.outfile == NULL) {
313 		BIO_set_fp(out, stdout, BIO_NOCLOSE);
314 	} else {
315 		if (BIO_write_filename(out, cfg.outfile) <= 0) {
316 			perror(cfg.outfile);
317 			goto end;
318 		}
319 	}
320 
321 	if (cfg.text)
322 		if (!RSA_print(out, rsa, 0)) {
323 			perror(cfg.outfile);
324 			ERR_print_errors(bio_err);
325 			goto end;
326 		}
327 	if (cfg.modulus) {
328 		BIO_printf(out, "Modulus=");
329 		BN_print(out, RSA_get0_n(rsa));
330 		BIO_printf(out, "\n");
331 	}
332 	if (cfg.check) {
333 		int r = RSA_check_key(rsa);
334 
335 		if (r == 1)
336 			BIO_printf(out, "RSA key ok\n");
337 		else if (r == 0) {
338 			unsigned long err;
339 
340 			while ((err = ERR_peek_error()) != 0 &&
341 			    ERR_GET_LIB(err) == ERR_LIB_RSA &&
342 			    ERR_GET_FUNC(err) == RSA_F_RSA_CHECK_KEY &&
343 			    ERR_GET_REASON(err) != ERR_R_MALLOC_FAILURE) {
344 				BIO_printf(out, "RSA key error: %s\n",
345 				    ERR_reason_error_string(err));
346 				ERR_get_error();	/* remove e from error
347 							 * stack */
348 			}
349 		}
350 		if (r == -1 || ERR_peek_error() != 0) {	/* should happen only if
351 							 * r == -1 */
352 			ERR_print_errors(bio_err);
353 			goto end;
354 		}
355 	}
356 	if (cfg.noout) {
357 		ret = 0;
358 		goto end;
359 	}
360 	BIO_printf(bio_err, "writing RSA key\n");
361 	if (cfg.outformat == FORMAT_ASN1) {
362 		if (cfg.pubout || cfg.pubin) {
363 			if (cfg.pubout == 2)
364 				i = i2d_RSAPublicKey_bio(out, rsa);
365 			else
366 				i = i2d_RSA_PUBKEY_bio(out, rsa);
367 		} else
368 			i = i2d_RSAPrivateKey_bio(out, rsa);
369 	} else if (cfg.outformat == FORMAT_PEM) {
370 		if (cfg.pubout || cfg.pubin) {
371 			if (cfg.pubout == 2)
372 				i = PEM_write_bio_RSAPublicKey(out, rsa);
373 			else
374 				i = PEM_write_bio_RSA_PUBKEY(out, rsa);
375 		} else
376 			i = PEM_write_bio_RSAPrivateKey(out, rsa,
377 			    cfg.enc, NULL, 0, NULL, passout);
378 #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_RC4)
379 	} else if (cfg.outformat == FORMAT_MSBLOB ||
380 	    cfg.outformat == FORMAT_PVK) {
381 		EVP_PKEY *pk;
382 		pk = EVP_PKEY_new();
383 		EVP_PKEY_set1_RSA(pk, rsa);
384 		if (cfg.outformat == FORMAT_PVK)
385 			i = i2b_PVK_bio(out, pk, cfg.pvk_encr, 0,
386 			    passout);
387 		else if (cfg.pubin || cfg.pubout)
388 			i = i2b_PublicKey_bio(out, pk);
389 		else
390 			i = i2b_PrivateKey_bio(out, pk);
391 		EVP_PKEY_free(pk);
392 #endif
393 	} else {
394 		BIO_printf(bio_err,
395 		    "bad output format specified for outfile\n");
396 		goto end;
397 	}
398 	if (i <= 0) {
399 		BIO_printf(bio_err, "unable to write key\n");
400 		ERR_print_errors(bio_err);
401 	} else
402 		ret = 0;
403 
404  end:
405 	BIO_free_all(out);
406 	RSA_free(rsa);
407 	free(passin);
408 	free(passout);
409 
410 	return (ret);
411 }
412