xref: /openbsd/usr.bin/openssl/pkcs8.c (revision b0100c00)
1 /* $OpenBSD: pkcs8.c,v 1.18 2025/01/02 12:31:44 tb Exp $ */
2 /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
3  * project 1999-2004.
4  */
5 /* ====================================================================
6  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58 
59 #include <stdio.h>
60 #include <string.h>
61 
62 #include "apps.h"
63 
64 #include <openssl/err.h>
65 #include <openssl/evp.h>
66 #include <openssl/pem.h>
67 #include <openssl/pkcs12.h>
68 
69 static struct {
70 	const EVP_CIPHER *cipher;
71 	char *infile;
72 	int informat;
73 	int iter;
74 	int nocrypt;
75 	char *outfile;
76 	int outformat;
77 	char *passargin;
78 	char *passargout;
79 	int pbe_nid;
80 	int topk8;
81 } cfg;
82 
83 static int
pkcs8_opt_v1(char * arg)84 pkcs8_opt_v1(char *arg)
85 {
86 	if ((cfg.pbe_nid = OBJ_txt2nid(arg)) == NID_undef) {
87 		fprintf(stderr, "Unknown PBE algorithm '%s'\n", arg);
88 		return (1);
89 	}
90 
91 	return (0);
92 }
93 
94 static int
pkcs8_opt_v2(char * arg)95 pkcs8_opt_v2(char *arg)
96 {
97 	if ((cfg.cipher = EVP_get_cipherbyname(arg)) == NULL) {
98 		fprintf(stderr, "Unknown cipher '%s'\n", arg);
99 		return (1);
100 	}
101 
102 	return (0);
103 }
104 
105 static const struct option pkcs8_options[] = {
106 	{
107 		.name = "in",
108 		.argname = "file",
109 		.desc = "Input file (default stdin)",
110 		.type = OPTION_ARG,
111 		.opt.arg = &cfg.infile,
112 	},
113 	{
114 		.name = "inform",
115 		.argname = "der | pem",
116 		.desc = "Input format (default PEM)",
117 		.type = OPTION_ARG_FORMAT,
118 		.opt.value = &cfg.informat,
119 	},
120 	{
121 		.name = "nocrypt",
122 		.desc = "Use or expect unencrypted private key",
123 		.type = OPTION_FLAG,
124 		.opt.flag = &cfg.nocrypt,
125 	},
126 	{
127 		.name = "noiter",
128 		.desc = "Use 1 as iteration count",
129 		.type = OPTION_VALUE,
130 		.value = 1,
131 		.opt.value = &cfg.iter,
132 	},
133 	{
134 		.name = "out",
135 		.argname = "file",
136 		.desc = "Output file (default stdout)",
137 		.type = OPTION_ARG,
138 		.opt.arg = &cfg.outfile,
139 	},
140 	{
141 		.name = "outform",
142 		.argname = "der | pem",
143 		.desc = "Output format (default PEM)",
144 		.type = OPTION_ARG_FORMAT,
145 		.opt.value = &cfg.outformat,
146 	},
147 	{
148 		.name = "passin",
149 		.argname = "source",
150 		.desc = "Input file passphrase source",
151 		.type = OPTION_ARG,
152 		.opt.arg = &cfg.passargin,
153 	},
154 	{
155 		.name = "passout",
156 		.argname = "source",
157 		.desc = "Output file passphrase source",
158 		.type = OPTION_ARG,
159 		.opt.arg = &cfg.passargout,
160 	},
161 	{
162 		.name = "topk8",
163 		.desc = "Read traditional format key and write PKCS#8 format"
164 		    " key",
165 		.type = OPTION_FLAG,
166 		.opt.flag = &cfg.topk8,
167 	},
168 	{
169 		.name = "v1",
170 		.argname = "algorithm",
171 		.desc = "Use PKCS#5 v1.5 or PKCS#12 with given algorithm",
172 		.type = OPTION_ARG_FUNC,
173 		.opt.argfunc = pkcs8_opt_v1,
174 	},
175 	{
176 		.name = "v2",
177 		.argname = "cipher",
178 		.desc = "Use PKCS#5 v2.0 with given cipher",
179 		.type = OPTION_ARG_FUNC,
180 		.opt.argfunc = pkcs8_opt_v2,
181 	},
182 	{ NULL },
183 };
184 
185 static void
pkcs8_usage(void)186 pkcs8_usage(void)
187 {
188 	fprintf(stderr, "usage: pkcs8 [-in file] [inform der | pem] "
189 	    "[-nocrypt] [-noiter]\n"
190 	    "    [-out file] [-outform der | pem] [-passin arg]\n"
191 	    "    [-passout arg] [-topk8] [-v1 alg] [-v2 alg]\n\n");
192 	options_usage(pkcs8_options);
193 }
194 
195 int
pkcs8_main(int argc,char ** argv)196 pkcs8_main(int argc, char **argv)
197 {
198 	BIO *in = NULL, *out = NULL;
199 	X509_SIG *p8 = NULL;
200 	PKCS8_PRIV_KEY_INFO *p8inf = NULL;
201 	EVP_PKEY *pkey = NULL;
202 	char pass[50], *passin = NULL, *passout = NULL, *p8pass = NULL;
203 	int ret = 1;
204 
205 	if (pledge("stdio cpath wpath rpath tty", NULL) == -1) {
206 		perror("pledge");
207 		exit(1);
208 	}
209 
210 	memset(&cfg, 0, sizeof(cfg));
211 
212 	cfg.iter = PKCS12_DEFAULT_ITER;
213 	cfg.informat = FORMAT_PEM;
214 	cfg.outformat = FORMAT_PEM;
215 	cfg.pbe_nid = -1;
216 
217 	if (options_parse(argc, argv, pkcs8_options, NULL, NULL) != 0) {
218 		pkcs8_usage();
219 		return (1);
220 	}
221 
222 	if (!app_passwd(bio_err, cfg.passargin,
223 	    cfg.passargout, &passin, &passout)) {
224 		BIO_printf(bio_err, "Error getting passwords\n");
225 		goto end;
226 	}
227 	if ((cfg.pbe_nid == -1) && !cfg.cipher)
228 		cfg.pbe_nid = NID_pbeWithMD5AndDES_CBC;
229 
230 	if (cfg.infile) {
231 		if (!(in = BIO_new_file(cfg.infile, "rb"))) {
232 			BIO_printf(bio_err,
233 			    "Can't open input file '%s'\n",
234 			    cfg.infile);
235 			goto end;
236 		}
237 	} else
238 		in = BIO_new_fp(stdin, BIO_NOCLOSE);
239 
240 	if (cfg.outfile) {
241 		if (!(out = BIO_new_file(cfg.outfile, "wb"))) {
242 			BIO_printf(bio_err, "Can't open output file '%s'\n",
243 			    cfg.outfile);
244 			goto end;
245 		}
246 	} else {
247 		out = BIO_new_fp(stdout, BIO_NOCLOSE);
248 	}
249 	if (cfg.topk8) {
250 		pkey = load_key(bio_err, cfg.infile,
251 		    cfg.informat, 1, passin, "key");
252 		if (!pkey)
253 			goto end;
254 		if (!(p8inf = EVP_PKEY2PKCS8(pkey))) {
255 			BIO_printf(bio_err, "Error converting key\n");
256 			ERR_print_errors(bio_err);
257 			goto end;
258 		}
259 		if (cfg.nocrypt) {
260 			if (cfg.outformat == FORMAT_PEM)
261 				PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf);
262 			else if (cfg.outformat == FORMAT_ASN1)
263 				i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf);
264 			else {
265 				BIO_printf(bio_err,
266 				    "Bad format specified for key\n");
267 				goto end;
268 			}
269 		} else {
270 			if (passout)
271 				p8pass = passout;
272 			else {
273 				p8pass = pass;
274 				if (EVP_read_pw_string(pass, sizeof pass,
275 				    "Enter Encryption Password:", 1))
276 					goto end;
277 			}
278 			if (!(p8 = PKCS8_encrypt(cfg.pbe_nid,
279 			    cfg.cipher, p8pass, strlen(p8pass),
280 			    NULL, 0, cfg.iter, p8inf))) {
281 				BIO_printf(bio_err, "Error encrypting key\n");
282 				ERR_print_errors(bio_err);
283 				goto end;
284 			}
285 			if (cfg.outformat == FORMAT_PEM)
286 				PEM_write_bio_PKCS8(out, p8);
287 			else if (cfg.outformat == FORMAT_ASN1)
288 				i2d_PKCS8_bio(out, p8);
289 			else {
290 				BIO_printf(bio_err,
291 				    "Bad format specified for key\n");
292 				goto end;
293 			}
294 		}
295 
296 		ret = 0;
297 		goto end;
298 	}
299 	if (cfg.nocrypt) {
300 		if (cfg.informat == FORMAT_PEM)
301 			p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL,
302 			    NULL, NULL);
303 		else if (cfg.informat == FORMAT_ASN1)
304 			p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL);
305 		else {
306 			BIO_printf(bio_err, "Bad format specified for key\n");
307 			goto end;
308 		}
309 	} else {
310 		if (cfg.informat == FORMAT_PEM)
311 			p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL);
312 		else if (cfg.informat == FORMAT_ASN1)
313 			p8 = d2i_PKCS8_bio(in, NULL);
314 		else {
315 			BIO_printf(bio_err, "Bad format specified for key\n");
316 			goto end;
317 		}
318 
319 		if (!p8) {
320 			BIO_printf(bio_err, "Error reading key\n");
321 			ERR_print_errors(bio_err);
322 			goto end;
323 		}
324 		if (passin)
325 			p8pass = passin;
326 		else {
327 			p8pass = pass;
328 			EVP_read_pw_string(pass, sizeof pass,
329 			    "Enter Password:", 0);
330 		}
331 		p8inf = PKCS8_decrypt(p8, p8pass, strlen(p8pass));
332 	}
333 
334 	if (!p8inf) {
335 		BIO_printf(bio_err, "Error decrypting key\n");
336 		ERR_print_errors(bio_err);
337 		goto end;
338 	}
339 	if (!(pkey = EVP_PKCS82PKEY(p8inf))) {
340 		BIO_printf(bio_err, "Error converting key\n");
341 		ERR_print_errors(bio_err);
342 		goto end;
343 	}
344 	if (cfg.outformat == FORMAT_PEM)
345 		PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL,
346 		    passout);
347 	else if (cfg.outformat == FORMAT_ASN1)
348 		i2d_PrivateKey_bio(out, pkey);
349 	else {
350 		BIO_printf(bio_err, "Bad format specified for key\n");
351 		goto end;
352 	}
353 	ret = 0;
354 
355  end:
356 	X509_SIG_free(p8);
357 	PKCS8_PRIV_KEY_INFO_free(p8inf);
358 	EVP_PKEY_free(pkey);
359 	BIO_free_all(out);
360 	BIO_free(in);
361 	free(passin);
362 	free(passout);
363 
364 	return ret;
365 }
366