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