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