GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: usr.bin/openssl/req.c Lines: 512 913 56.1 %
Date: 2017-11-07 Branches: 314 739 42.5 %

Line Branch Exec Source
1
/* $OpenBSD: req.c,v 1.14 2017/01/20 08:57:12 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
/* Until the key-gen callbacks are modified to use newer prototypes, we allow
60
 * deprecated functions for openssl-internal code */
61
#ifdef OPENSSL_NO_DEPRECATED
62
#undef OPENSSL_NO_DEPRECATED
63
#endif
64
65
#include <stdio.h>
66
#include <stdlib.h>
67
#include <limits.h>
68
#include <string.h>
69
#include <time.h>
70
71
#include "apps.h"
72
73
#include <openssl/asn1.h>
74
#include <openssl/bio.h>
75
#include <openssl/bn.h>
76
#include <openssl/conf.h>
77
#include <openssl/err.h>
78
#include <openssl/evp.h>
79
#include <openssl/objects.h>
80
#include <openssl/pem.h>
81
#include <openssl/x509.h>
82
#include <openssl/x509v3.h>
83
84
#include <openssl/dsa.h>
85
86
#include <openssl/rsa.h>
87
88
#define SECTION		"req"
89
90
#define BITS		"default_bits"
91
#define KEYFILE		"default_keyfile"
92
#define PROMPT		"prompt"
93
#define DISTINGUISHED_NAME	"distinguished_name"
94
#define ATTRIBUTES	"attributes"
95
#define V3_EXTENSIONS	"x509_extensions"
96
#define REQ_EXTENSIONS	"req_extensions"
97
#define STRING_MASK	"string_mask"
98
#define UTF8_IN		"utf8"
99
100
#define DEFAULT_KEY_LENGTH	2048
101
#define MIN_KEY_LENGTH		384
102
103
104
/* -inform arg	- input format - default PEM (DER or PEM)
105
 * -outform arg - output format - default PEM
106
 * -in arg	- input file - default stdin
107
 * -out arg	- output file - default stdout
108
 * -verify	- check request signature
109
 * -noout	- don't print stuff out.
110
 * -text	- print out human readable text.
111
 * -nodes	- no des encryption
112
 * -config file	- Load configuration file.
113
 * -key file	- make a request using key in file (or use it for verification).
114
 * -keyform arg	- key file format.
115
 * -newkey	- make a key and a request.
116
 * -modulus	- print RSA modulus.
117
 * -pubkey	- output Public Key.
118
 * -x509	- output a self signed X509 structure instead.
119
 * -asn1-kludge	- output new certificate request in a format that some CA's
120
 *		  require.  This format is wrong
121
 */
122
123
static int make_REQ(X509_REQ * req, EVP_PKEY * pkey, char *dn, int multirdn,
124
    int attribs, unsigned long chtype);
125
static int build_subject(X509_REQ * req, char *subj, unsigned long chtype,
126
    int multirdn);
127
static int prompt_info(X509_REQ * req,
128
    STACK_OF(CONF_VALUE) * dn_sk, char *dn_sect,
129
    STACK_OF(CONF_VALUE) * attr_sk, char *attr_sect, int attribs,
130
    unsigned long chtype);
131
static int auto_info(X509_REQ * req, STACK_OF(CONF_VALUE) * sk,
132
    STACK_OF(CONF_VALUE) * attr, int attribs,
133
    unsigned long chtype);
134
static int add_attribute_object(X509_REQ * req, char *text, const char *def,
135
    char *value, int nid, int n_min,
136
    int n_max, unsigned long chtype);
137
static int add_DN_object(X509_NAME * n, char *text, const char *def, char *value,
138
    int nid, int n_min, int n_max, unsigned long chtype, int mval);
139
static int genpkey_cb(EVP_PKEY_CTX * ctx);
140
static int req_check_len(int len, int n_min, int n_max);
141
static int check_end(const char *str, const char *end);
142
static EVP_PKEY_CTX *set_keygen_ctx(BIO * err, const char *gstr, int *pkey_type,
143
    long *pkeylen, char **palgnam);
144
static CONF *req_conf = NULL;
145
static int batch = 0;
146
147
int
148
req_main(int argc, char **argv)
149
{
150
244
	unsigned long nmflag = 0, reqflag = 0;
151
	int ex = 1, x509 = 0, days = 30;
152
	X509 *x509ss = NULL;
153
	X509_REQ *req = NULL;
154
	EVP_PKEY_CTX *genctx = NULL;
155
	const char *keyalg = NULL;
156
122
	char *keyalgstr = NULL;
157
	STACK_OF(OPENSSL_STRING) * pkeyopts = NULL, *sigopts = NULL;
158
122
	EVP_PKEY *pkey = NULL;
159
122
	int i = 0, badops = 0, newreq = 0, verbose = 0, pkey_type = -1;
160
122
	long newkey = -1;
161
	BIO *in = NULL, *out = NULL;
162
	int informat, outformat, verify = 0, noout = 0, text = 0, keyform = FORMAT_PEM;
163
	int nodes = 0, kludge = 0, newhdr = 0, subject = 0, pubkey = 0;
164
	char *infile, *outfile, *prog, *keyfile = NULL, *template = NULL,
165
	*keyout = NULL;
166
	char *extensions = NULL;
167
	char *req_exts = NULL;
168
	const EVP_CIPHER *cipher = NULL;
169
	ASN1_INTEGER *serial = NULL;
170
	int modulus = 0;
171
	char *passargin = NULL, *passargout = NULL;
172
122
	char *passin = NULL, *passout = NULL;
173
	char *p;
174
	char *subj = NULL;
175
	int multirdn = 0;
176
	const EVP_MD *md_alg = NULL, *digest = NULL;
177
	unsigned long chtype = MBSTRING_ASC;
178
179
122
	if (single_execution) {
180
122
		if (pledge("stdio cpath wpath rpath tty flock", NULL) == -1) {
181
			perror("pledge");
182
			exit(1);
183
		}
184
	}
185
186
122
	req_conf = NULL;
187
122
	cipher = EVP_aes_256_cbc();
188
122
	digest = EVP_sha256();
189
190
	infile = NULL;
191
	outfile = NULL;
192
	informat = FORMAT_PEM;
193
	outformat = FORMAT_PEM;
194
195
122
	prog = argv[0];
196
122
	argc--;
197
122
	argv++;
198
1708
	while (argc >= 1) {
199
740
		if (strcmp(*argv, "-inform") == 0) {
200
			if (--argc < 1)
201
				goto bad;
202
			informat = str2fmt(*(++argv));
203
740
		} else if (strcmp(*argv, "-outform") == 0) {
204
			if (--argc < 1)
205
				goto bad;
206
			outformat = str2fmt(*(++argv));
207
		}
208
740
		else if (strcmp(*argv, "-key") == 0) {
209
8
			if (--argc < 1)
210
				goto bad;
211
8
			keyfile = *(++argv);
212
740
		} else if (strcmp(*argv, "-pubkey") == 0) {
213
			pubkey = 1;
214
732
		} else if (strcmp(*argv, "-new") == 0) {
215
			newreq = 1;
216
732
		} else if (strcmp(*argv, "-config") == 0) {
217
16
			if (--argc < 1)
218
				goto bad;
219
16
			template = *(++argv);
220
626
		} else if (strcmp(*argv, "-keyform") == 0) {
221
			if (--argc < 1)
222
				goto bad;
223
			keyform = str2fmt(*(++argv));
224
610
		} else if (strcmp(*argv, "-in") == 0) {
225
			if (--argc < 1)
226
				goto bad;
227
			infile = *(++argv);
228
610
		} else if (strcmp(*argv, "-out") == 0) {
229
114
			if (--argc < 1)
230
				goto bad;
231
114
			outfile = *(++argv);
232
610
		} else if (strcmp(*argv, "-keyout") == 0) {
233
106
			if (--argc < 1)
234
				goto bad;
235
106
			keyout = *(++argv);
236
496
		} else if (strcmp(*argv, "-passin") == 0) {
237
			if (--argc < 1)
238
				goto bad;
239
			passargin = *(++argv);
240
390
		} else if (strcmp(*argv, "-passout") == 0) {
241
40
			if (--argc < 1)
242
				goto bad;
243
40
			passargout = *(++argv);
244
390
		} else if (strcmp(*argv, "-newkey") == 0) {
245
66
			if (--argc < 1)
246
				goto bad;
247
66
			keyalg = *(++argv);
248
			newreq = 1;
249
350
		} else if (strcmp(*argv, "-pkeyopt") == 0) {
250
			if (--argc < 1)
251
				goto bad;
252
			if (!pkeyopts)
253
				pkeyopts = sk_OPENSSL_STRING_new_null();
254
			if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, *(++argv)))
255
				goto bad;
256
284
		} else if (strcmp(*argv, "-sigopt") == 0) {
257
			if (--argc < 1)
258
				goto bad;
259
			if (!sigopts)
260
				sigopts = sk_OPENSSL_STRING_new_null();
261
			if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv)))
262
				goto bad;
263
284
		} else if (strcmp(*argv, "-batch") == 0)
264
58
			batch = 1;
265
226
		else if (strcmp(*argv, "-newhdr") == 0)
266
			newhdr = 1;
267
226
		else if (strcmp(*argv, "-modulus") == 0)
268
			modulus = 1;
269
226
		else if (strcmp(*argv, "-verify") == 0)
270
			verify = 1;
271
226
		else if (strcmp(*argv, "-nodes") == 0)
272
58
			nodes = 1;
273
168
		else if (strcmp(*argv, "-noout") == 0)
274
			noout = 1;
275
168
		else if (strcmp(*argv, "-verbose") == 0)
276
			verbose = 1;
277
168
		else if (strcmp(*argv, "-utf8") == 0)
278
			chtype = MBSTRING_UTF8;
279
168
		else if (strcmp(*argv, "-nameopt") == 0) {
280
			if (--argc < 1)
281
				goto bad;
282
			if (!set_name_ex(&nmflag, *(++argv)))
283
				goto bad;
284
168
		} else if (strcmp(*argv, "-reqopt") == 0) {
285
			if (--argc < 1)
286
				goto bad;
287
			if (!set_cert_ex(&reqflag, *(++argv)))
288
				goto bad;
289
168
		} else if (strcmp(*argv, "-subject") == 0)
290
			subject = 1;
291
168
		else if (strcmp(*argv, "-text") == 0)
292
			text = 1;
293
168
		else if (strcmp(*argv, "-x509") == 0)
294
54
			x509 = 1;
295
114
		else if (strcmp(*argv, "-asn1-kludge") == 0)
296
			kludge = 1;
297
114
		else if (strcmp(*argv, "-no-asn1-kludge") == 0)
298
			kludge = 0;
299
114
		else if (strcmp(*argv, "-subj") == 0) {
300
90
			if (--argc < 1)
301
				goto bad;
302
90
			subj = *(++argv);
303
114
		} else if (strcmp(*argv, "-multivalue-rdn") == 0)
304
			multirdn = 1;
305
24
		else if (strcmp(*argv, "-days") == 0) {
306
16
			const char *errstr;
307
308
16
			if (--argc < 1)
309
				goto bad;
310
16
			days = strtonum(*(++argv), 1, INT_MAX, &errstr);
311
16
			if (errstr) {
312
				BIO_printf(bio_err, "bad -days %s, using 0: %s\n",
313
				    *argv, errstr);
314
				days = 30;
315
			}
316

72
		} else if (strcmp(*argv, "-set_serial") == 0) {
317
			if (--argc < 1)
318
				goto bad;
319
			serial = s2i_ASN1_INTEGER(NULL, *(++argv));
320
			if (!serial)
321
				goto bad;
322
8
		} else if (strcmp(*argv, "-extensions") == 0) {
323
			if (--argc < 1)
324
				goto bad;
325
			extensions = *(++argv);
326
8
		} else if (strcmp(*argv, "-reqexts") == 0) {
327
			if (--argc < 1)
328
				goto bad;
329
			req_exts = *(++argv);
330
8
		} else if ((md_alg = EVP_get_digestbyname(&((*argv)[1]))) != NULL) {
331
			/* ok */
332
			digest = md_alg;
333
		} else {
334
8
			BIO_printf(bio_err, "unknown option %s\n", *argv);
335
			badops = 1;
336
8
			break;
337
		}
338
732
		argc--;
339
732
		argv++;
340
	}
341
342
122
	if (badops) {
343
bad:
344
8
		BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog);
345
8
		BIO_printf(bio_err, "where options  are\n");
346
8
		BIO_printf(bio_err, " -inform arg    input format - DER or PEM\n");
347
8
		BIO_printf(bio_err, " -outform arg   output format - DER or PEM\n");
348
8
		BIO_printf(bio_err, " -in arg        input file\n");
349
8
		BIO_printf(bio_err, " -out arg       output file\n");
350
8
		BIO_printf(bio_err, " -text          text form of request\n");
351
8
		BIO_printf(bio_err, " -pubkey        output public key\n");
352
8
		BIO_printf(bio_err, " -noout         do not output REQ\n");
353
8
		BIO_printf(bio_err, " -verify        verify signature on REQ\n");
354
8
		BIO_printf(bio_err, " -modulus       RSA modulus\n");
355
8
		BIO_printf(bio_err, " -nodes         don't encrypt the output key\n");
356
8
		BIO_printf(bio_err, " -subject       output the request's subject\n");
357
8
		BIO_printf(bio_err, " -passin        private key password source\n");
358
8
		BIO_printf(bio_err, " -key file      use the private key contained in file\n");
359
8
		BIO_printf(bio_err, " -keyform arg   key file format\n");
360
8
		BIO_printf(bio_err, " -keyout arg    file to send the key to\n");
361
8
		BIO_printf(bio_err, " -newkey rsa:bits generate a new RSA key of 'bits' in size\n");
362
8
		BIO_printf(bio_err, " -newkey dsa:file generate a new DSA key, parameters taken from CA in 'file'\n");
363
8
		BIO_printf(bio_err, " -newkey ec:file generate a new EC key, parameters taken from CA in 'file'\n");
364
8
		BIO_printf(bio_err, " -[digest]      Digest to sign with (md5, sha1, md4)\n");
365
8
		BIO_printf(bio_err, " -config file   request template file.\n");
366
8
		BIO_printf(bio_err, " -subj arg      set or modify request subject\n");
367
8
		BIO_printf(bio_err, " -multivalue-rdn enable support for multivalued RDNs\n");
368
8
		BIO_printf(bio_err, " -new           new request.\n");
369
8
		BIO_printf(bio_err, " -batch         do not ask anything during request generation\n");
370
8
		BIO_printf(bio_err, " -x509          output a x509 structure instead of a cert. req.\n");
371
8
		BIO_printf(bio_err, " -days          number of days a certificate generated by -x509 is valid for.\n");
372
8
		BIO_printf(bio_err, " -set_serial    serial number to use for a certificate generated by -x509.\n");
373
8
		BIO_printf(bio_err, " -newhdr        output \"NEW\" in the header lines\n");
374
8
		BIO_printf(bio_err, " -asn1-kludge   Output the 'request' in a format that is wrong but some CA's\n");
375
8
		BIO_printf(bio_err, "                have been reported as requiring\n");
376
8
		BIO_printf(bio_err, " -extensions .. specify certificate extension section (override value in config file)\n");
377
8
		BIO_printf(bio_err, " -reqexts ..    specify request extension section (override value in config file)\n");
378
8
		BIO_printf(bio_err, " -utf8          input characters are UTF8 (default ASCII)\n");
379
8
		BIO_printf(bio_err, " -nameopt arg    - various certificate name options\n");
380
8
		BIO_printf(bio_err, " -reqopt arg    - various request text options\n\n");
381
8
		goto end;
382
	}
383
384
114
	if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
385
		BIO_printf(bio_err, "Error getting passwords\n");
386
		goto end;
387
	}
388
114
	if (template != NULL) {
389
16
		long errline = -1;
390
391
16
		if (verbose)
392
			BIO_printf(bio_err, "Using configuration from %s\n", template);
393
16
		req_conf = NCONF_new(NULL);
394
16
		i = NCONF_load(req_conf, template, &errline);
395
16
		if (i == 0) {
396
			BIO_printf(bio_err, "error on line %ld of %s\n", errline, template);
397
			goto end;
398
		}
399
32
	} else {
400
98
		req_conf = config;
401
402
98
		if (req_conf == NULL) {
403
			BIO_printf(bio_err, "Unable to load config info from %s\n", default_config_file);
404
			if (newreq)
405
				goto end;
406
98
		} else if (verbose)
407
			BIO_printf(bio_err, "Using configuration from %s\n",
408
			    default_config_file);
409
	}
410
411
114
	if (req_conf != NULL) {
412
114
		if (!load_config(bio_err, req_conf))
413
			goto end;
414
114
		p = NCONF_get_string(req_conf, NULL, "oid_file");
415
114
		if (p == NULL)
416
114
			ERR_clear_error();
417
114
		if (p != NULL) {
418
			BIO *oid_bio;
419
420
			oid_bio = BIO_new_file(p, "r");
421
			if (oid_bio == NULL) {
422
				/*
423
				BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
424
				ERR_print_errors(bio_err);
425
				*/
426
			} else {
427
				OBJ_create_objects(oid_bio);
428
				BIO_free(oid_bio);
429
			}
430
		}
431
	}
432
114
	if (!add_oid_section(bio_err, req_conf))
433
		goto end;
434
435
114
	if (md_alg == NULL) {
436
114
		p = NCONF_get_string(req_conf, SECTION, "default_md");
437
114
		if (p == NULL)
438
114
			ERR_clear_error();
439
114
		if (p != NULL) {
440
			if ((md_alg = EVP_get_digestbyname(p)) != NULL)
441
				digest = md_alg;
442
		}
443
	}
444
114
	if (!extensions) {
445
114
		extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
446
114
		if (!extensions)
447
114
			ERR_clear_error();
448
	}
449
114
	if (extensions) {
450
		/* Check syntax of file */
451
		X509V3_CTX ctx;
452
		X509V3_set_ctx_test(&ctx);
453
		X509V3_set_nconf(&ctx, req_conf);
454
		if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
455
			BIO_printf(bio_err,
456
			    "Error Loading extension section %s\n", extensions);
457
			goto end;
458
		}
459
	}
460
114
	if (!passin) {
461
114
		passin = NCONF_get_string(req_conf, SECTION, "input_password");
462
114
		if (!passin)
463
114
			ERR_clear_error();
464
	}
465
114
	if (!passout) {
466
74
		passout = NCONF_get_string(req_conf, SECTION, "output_password");
467
74
		if (!passout)
468
74
			ERR_clear_error();
469
	}
470
114
	p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
471
114
	if (!p)
472
114
		ERR_clear_error();
473
474

114
	if (p && !ASN1_STRING_set_default_mask_asc(p)) {
475
		BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
476
		goto end;
477
	}
478
114
	if (chtype != MBSTRING_UTF8) {
479
114
		p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
480
114
		if (!p)
481
114
			ERR_clear_error();
482
		else if (!strcmp(p, "yes"))
483
			chtype = MBSTRING_UTF8;
484
	}
485
114
	if (!req_exts) {
486
114
		req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
487
114
		if (!req_exts)
488
114
			ERR_clear_error();
489
	}
490
114
	if (req_exts) {
491
		/* Check syntax of file */
492
		X509V3_CTX ctx;
493
		X509V3_set_ctx_test(&ctx);
494
		X509V3_set_nconf(&ctx, req_conf);
495
		if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
496
			BIO_printf(bio_err,
497
			    "Error Loading request extension section %s\n",
498
			    req_exts);
499
			goto end;
500
		}
501
	}
502
114
	in = BIO_new(BIO_s_file());
503
114
	out = BIO_new(BIO_s_file());
504
114
	if ((in == NULL) || (out == NULL))
505
		goto end;
506
507
114
	if (keyfile != NULL) {
508
8
		pkey = load_key(bio_err, keyfile, keyform, 0, passin,
509
		    "Private Key");
510
8
		if (!pkey) {
511
			/*
512
			 * load_key() has already printed an appropriate
513
			 * message
514
			 */
515
			goto end;
516
		}
517
	}
518
114
	if (newreq && (pkey == NULL)) {
519
106
		if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
520
106
			newkey = DEFAULT_KEY_LENGTH;
521
106
		}
522
106
		if (keyalg) {
523
66
			genctx = set_keygen_ctx(bio_err, keyalg, &pkey_type, &newkey,
524
			    &keyalgstr);
525
66
			if (!genctx)
526
				goto end;
527
		}
528

106
		if (newkey < MIN_KEY_LENGTH && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
529
			BIO_printf(bio_err, "private key length is too short,\n");
530
			BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n", MIN_KEY_LENGTH, newkey);
531
			goto end;
532
		}
533
106
		if (!genctx) {
534
40
			genctx = set_keygen_ctx(bio_err, NULL, &pkey_type, &newkey,
535
			    &keyalgstr);
536
40
			if (!genctx)
537
				goto end;
538
		}
539
106
		if (pkeyopts) {
540
			char *genopt;
541
			for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
542
				genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
543
				if (pkey_ctrl_string(genctx, genopt) <= 0) {
544
					BIO_printf(bio_err,
545
					    "parameter error \"%s\"\n",
546
					    genopt);
547
					ERR_print_errors(bio_err);
548
					goto end;
549
				}
550
			}
551
		}
552
212
		BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
553
106
		    newkey, keyalgstr);
554
555
106
		EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
556
106
		EVP_PKEY_CTX_set_app_data(genctx, bio_err);
557
558
106
		if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
559
			BIO_puts(bio_err, "Error Generating Key\n");
560
			goto end;
561
		}
562
106
		EVP_PKEY_CTX_free(genctx);
563
		genctx = NULL;
564
565
106
		if (keyout == NULL) {
566
			keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
567
			if (keyout == NULL)
568
				ERR_clear_error();
569
		}
570
106
		if (keyout == NULL) {
571
			BIO_printf(bio_err, "writing new private key to stdout\n");
572
			BIO_set_fp(out, stdout, BIO_NOCLOSE);
573
		} else {
574
106
			BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
575
106
			if (BIO_write_filename(out, keyout) <= 0) {
576
				perror(keyout);
577
				goto end;
578
			}
579
		}
580
581
106
		p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
582
106
		if (p == NULL) {
583
98
			ERR_clear_error();
584
98
			p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
585
98
			if (p == NULL)
586
98
				ERR_clear_error();
587
		}
588

114
		if ((p != NULL) && (strcmp(p, "no") == 0))
589
8
			cipher = NULL;
590
106
		if (nodes)
591
58
			cipher = NULL;
592
593
106
		i = 0;
594
loop:
595
212
		if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
596
106
			NULL, 0, NULL, passout)) {
597
			if ((ERR_GET_REASON(ERR_peek_error()) ==
598
				PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
599
				ERR_clear_error();
600
				i++;
601
				goto loop;
602
			}
603
			goto end;
604
		}
605
106
		BIO_printf(bio_err, "-----\n");
606
106
	}
607
114
	if (!newreq) {
608
		/*
609
		 * Since we are using a pre-existing certificate request, the
610
		 * kludge 'format' info should not be changed.
611
		 */
612
		kludge = -1;
613
		if (infile == NULL)
614
			BIO_set_fp(in, stdin, BIO_NOCLOSE);
615
		else {
616
			if (BIO_read_filename(in, infile) <= 0) {
617
				perror(infile);
618
				goto end;
619
			}
620
		}
621
622
		if (informat == FORMAT_ASN1)
623
			req = d2i_X509_REQ_bio(in, NULL);
624
		else if (informat == FORMAT_PEM)
625
			req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
626
		else {
627
			BIO_printf(bio_err, "bad input format specified for X509 request\n");
628
			goto end;
629
		}
630
		if (req == NULL) {
631
			BIO_printf(bio_err, "unable to load X509 request\n");
632
			goto end;
633
		}
634
	}
635
114
	if (newreq || x509) {
636
114
		if (pkey == NULL) {
637
			BIO_printf(bio_err, "you need to specify a private key\n");
638
			goto end;
639
		}
640
114
		if (req == NULL) {
641
114
			req = X509_REQ_new();
642
114
			if (req == NULL) {
643
				goto end;
644
			}
645
114
			i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
646
			subj = NULL;	/* done processing '-subj' option */
647

114
			if ((kludge > 0) && !sk_X509_ATTRIBUTE_num(req->req_info->attributes)) {
648
				sk_X509_ATTRIBUTE_free(req->req_info->attributes);
649
				req->req_info->attributes = NULL;
650
			}
651
114
			if (!i) {
652
				BIO_printf(bio_err, "problems making Certificate Request\n");
653
				goto end;
654
			}
655
		}
656
114
		if (x509) {
657
			EVP_PKEY *tmppkey;
658
54
			X509V3_CTX ext_ctx;
659
54
			if ((x509ss = X509_new()) == NULL)
660
				goto end;
661
662
			/* Set version to V3 */
663

54
			if (extensions && !X509_set_version(x509ss, 2))
664
				goto end;
665
54
			if (serial) {
666
				if (!X509_set_serialNumber(x509ss, serial))
667
					goto end;
668
			} else {
669
54
				if (!rand_serial(NULL,
670
54
					X509_get_serialNumber(x509ss)))
671
					goto end;
672
			}
673
674
54
			if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
675
				goto end;
676
54
			if (!X509_gmtime_adj(X509_get_notBefore(x509ss), 0))
677
				goto end;
678
54
			if (!X509_time_adj_ex(X509_get_notAfter(x509ss), days, 0, NULL))
679
				goto end;
680
54
			if (!X509_set_subject_name(x509ss, X509_REQ_get_subject_name(req)))
681
				goto end;
682
54
			tmppkey = X509_REQ_get_pubkey(req);
683

108
			if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
684
				goto end;
685
54
			EVP_PKEY_free(tmppkey);
686
687
			/* Set up V3 context struct */
688
689
54
			X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
690
54
			X509V3_set_nconf(&ext_ctx, req_conf);
691
692
			/* Add extensions */
693

54
			if (extensions && !X509V3_EXT_add_nconf(req_conf,
694
				&ext_ctx, extensions, x509ss)) {
695
				BIO_printf(bio_err,
696
				    "Error Loading extension section %s\n",
697
				    extensions);
698
				goto end;
699
			}
700
54
			i = do_X509_sign(bio_err, x509ss, pkey, digest, sigopts);
701
54
			if (!i) {
702
				ERR_print_errors(bio_err);
703
				goto end;
704
			}
705
216
		} else {
706
60
			X509V3_CTX ext_ctx;
707
708
			/* Set up V3 context struct */
709
710
60
			X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
711
60
			X509V3_set_nconf(&ext_ctx, req_conf);
712
713
			/* Add extensions */
714

60
			if (req_exts && !X509V3_EXT_REQ_add_nconf(req_conf,
715
				&ext_ctx, req_exts, req)) {
716
				BIO_printf(bio_err,
717
				    "Error Loading extension section %s\n",
718
				    req_exts);
719
				goto end;
720
			}
721
60
			i = do_X509_REQ_sign(bio_err, req, pkey, digest, sigopts);
722
60
			if (!i) {
723
				ERR_print_errors(bio_err);
724
				goto end;
725
			}
726
240
		}
727
	}
728
114
	if (subj && x509) {
729
		BIO_printf(bio_err, "Cannot modifiy certificate subject\n");
730
		goto end;
731
	}
732
114
	if (subj && !x509) {
733
		if (verbose) {
734
			BIO_printf(bio_err, "Modifying Request's Subject\n");
735
			print_name(bio_err, "old subject=", X509_REQ_get_subject_name(req), nmflag);
736
		}
737
		if (build_subject(req, subj, chtype, multirdn) == 0) {
738
			BIO_printf(bio_err, "ERROR: cannot modify subject\n");
739
			ex = 1;
740
			goto end;
741
		}
742
		req->req_info->enc.modified = 1;
743
744
		if (verbose) {
745
			print_name(bio_err, "new subject=", X509_REQ_get_subject_name(req), nmflag);
746
		}
747
	}
748
114
	if (verify && !x509) {
749
		int tmp = 0;
750
751
		if (pkey == NULL) {
752
			pkey = X509_REQ_get_pubkey(req);
753
			tmp = 1;
754
			if (pkey == NULL)
755
				goto end;
756
		}
757
		i = X509_REQ_verify(req, pkey);
758
		if (tmp) {
759
			EVP_PKEY_free(pkey);
760
			pkey = NULL;
761
		}
762
		if (i < 0) {
763
			goto end;
764
		} else if (i == 0) {
765
			BIO_printf(bio_err, "verify failure\n");
766
			ERR_print_errors(bio_err);
767
		} else		/* if (i > 0) */
768
			BIO_printf(bio_err, "verify OK\n");
769
	}
770
114
	if (noout && !text && !modulus && !subject && !pubkey) {
771
		ex = 0;
772
		goto end;
773
	}
774
114
	if (outfile == NULL) {
775
		BIO_set_fp(out, stdout, BIO_NOCLOSE);
776
	} else {
777

220
		if ((keyout != NULL) && (strcmp(outfile, keyout) == 0))
778
			i = (int) BIO_append_filename(out, outfile);
779
		else
780
114
			i = (int) BIO_write_filename(out, outfile);
781
114
		if (!i) {
782
			perror(outfile);
783
			goto end;
784
		}
785
	}
786
787
114
	if (pubkey) {
788
		EVP_PKEY *tpubkey;
789
		tpubkey = X509_REQ_get_pubkey(req);
790
		if (tpubkey == NULL) {
791
			BIO_printf(bio_err, "Error getting public key\n");
792
			ERR_print_errors(bio_err);
793
			goto end;
794
		}
795
		PEM_write_bio_PUBKEY(out, tpubkey);
796
		EVP_PKEY_free(tpubkey);
797
	}
798
114
	if (text) {
799
		if (x509)
800
			X509_print_ex(out, x509ss, nmflag, reqflag);
801
		else
802
			X509_REQ_print_ex(out, req, nmflag, reqflag);
803
	}
804
114
	if (subject) {
805
		if (x509)
806
			print_name(out, "subject=", X509_get_subject_name(x509ss), nmflag);
807
		else
808
			print_name(out, "subject=", X509_REQ_get_subject_name(req), nmflag);
809
	}
810
114
	if (modulus) {
811
		EVP_PKEY *tpubkey;
812
813
		if (x509)
814
			tpubkey = X509_get_pubkey(x509ss);
815
		else
816
			tpubkey = X509_REQ_get_pubkey(req);
817
		if (tpubkey == NULL) {
818
			fprintf(stdout, "Modulus=unavailable\n");
819
			goto end;
820
		}
821
		fprintf(stdout, "Modulus=");
822
		if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA)
823
			BN_print(out, tpubkey->pkey.rsa->n);
824
		else
825
			fprintf(stdout, "Wrong Algorithm type");
826
		EVP_PKEY_free(tpubkey);
827
		fprintf(stdout, "\n");
828
	}
829
114
	if (!noout && !x509) {
830
60
		if (outformat == FORMAT_ASN1)
831
			i = i2d_X509_REQ_bio(out, req);
832
60
		else if (outformat == FORMAT_PEM) {
833
60
			if (newhdr)
834
				i = PEM_write_bio_X509_REQ_NEW(out, req);
835
			else
836
60
				i = PEM_write_bio_X509_REQ(out, req);
837
		} else {
838
			BIO_printf(bio_err, "bad output format specified for outfile\n");
839
			goto end;
840
		}
841
60
		if (!i) {
842
			BIO_printf(bio_err, "unable to write X509 request\n");
843
			goto end;
844
		}
845
	}
846
114
	if (!noout && x509 && (x509ss != NULL)) {
847
54
		if (outformat == FORMAT_ASN1)
848
			i = i2d_X509_bio(out, x509ss);
849
54
		else if (outformat == FORMAT_PEM)
850
54
			i = PEM_write_bio_X509(out, x509ss);
851
		else {
852
			BIO_printf(bio_err, "bad output format specified for outfile\n");
853
			goto end;
854
		}
855
54
		if (!i) {
856
			BIO_printf(bio_err, "unable to write X509 certificate\n");
857
			goto end;
858
		}
859
	}
860
114
	ex = 0;
861
end:
862
122
	if (ex) {
863
8
		ERR_print_errors(bio_err);
864
8
	}
865

236
	if ((req_conf != NULL) && (req_conf != config))
866
16
		NCONF_free(req_conf);
867
122
	BIO_free(in);
868
122
	BIO_free_all(out);
869
122
	EVP_PKEY_free(pkey);
870
122
	if (genctx)
871
		EVP_PKEY_CTX_free(genctx);
872
122
	if (pkeyopts)
873
		sk_OPENSSL_STRING_free(pkeyopts);
874
122
	if (sigopts)
875
		sk_OPENSSL_STRING_free(sigopts);
876
122
	free(keyalgstr);
877
122
	X509_REQ_free(req);
878
122
	X509_free(x509ss);
879
122
	ASN1_INTEGER_free(serial);
880
122
	if (passargin && passin)
881
		free(passin);
882
122
	if (passargout && passout)
883
40
		free(passout);
884
122
	OBJ_cleanup();
885
886
122
	return (ex);
887
122
}
888
889
static int
890
make_REQ(X509_REQ * req, EVP_PKEY * pkey, char *subj, int multirdn,
891
    int attribs, unsigned long chtype)
892
{
893
	int ret = 0, i;
894
	char no_prompt = 0;
895
	STACK_OF(CONF_VALUE) * dn_sk, *attr_sk = NULL;
896
	char *tmp, *dn_sect, *attr_sect;
897
898
228
	tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
899
114
	if (tmp == NULL)
900
114
		ERR_clear_error();
901

114
	if ((tmp != NULL) && !strcmp(tmp, "no"))
902
		no_prompt = 1;
903
904
114
	dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
905
114
	if (dn_sect == NULL) {
906
		BIO_printf(bio_err, "unable to find '%s' in config\n",
907
		    DISTINGUISHED_NAME);
908
		goto err;
909
	}
910
114
	dn_sk = NCONF_get_section(req_conf, dn_sect);
911
114
	if (dn_sk == NULL) {
912
		BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
913
		goto err;
914
	}
915
114
	attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
916
114
	if (attr_sect == NULL) {
917
64
		ERR_clear_error();
918
		attr_sk = NULL;
919
64
	} else {
920
50
		attr_sk = NCONF_get_section(req_conf, attr_sect);
921
50
		if (attr_sk == NULL) {
922
			BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
923
			goto err;
924
		}
925
	}
926
927
	/* setup version number */
928
114
	if (!X509_REQ_set_version(req, 0L))
929
		goto err;	/* version 1 */
930
931
114
	if (no_prompt)
932
		i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
933
	else {
934
114
		if (subj)
935
90
			i = build_subject(req, subj, chtype, multirdn);
936
		else
937
24
			i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs, chtype);
938
	}
939
114
	if (!i)
940
		goto err;
941
942
114
	if (!X509_REQ_set_pubkey(req, pkey))
943
		goto err;
944
945
114
	ret = 1;
946
err:
947
114
	return (ret);
948
}
949
950
/*
951
 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
952
 * where characters may be escaped by \
953
 */
954
static int
955
build_subject(X509_REQ * req, char *subject, unsigned long chtype, int multirdn)
956
{
957
	X509_NAME *n;
958
959
180
	if (!(n = parse_name(subject, chtype, multirdn)))
960
		return 0;
961
962
180
	if (!X509_REQ_set_subject_name(req, n)) {
963
		X509_NAME_free(n);
964
		return 0;
965
	}
966
90
	X509_NAME_free(n);
967
90
	return 1;
968
90
}
969
970
971
static int
972
prompt_info(X509_REQ * req,
973
    STACK_OF(CONF_VALUE) * dn_sk, char *dn_sect,
974
    STACK_OF(CONF_VALUE) * attr_sk, char *attr_sect, int attribs,
975
    unsigned long chtype)
976
{
977
	int i;
978
	char *p, *q;
979
48
	char buf[100];
980
	int nid, mval;
981
24
	long n_min, n_max;
982
	char *type, *value;
983
	const char *def;
984
	CONF_VALUE *v;
985
	X509_NAME *subj;
986
24
	subj = X509_REQ_get_subject_name(req);
987
988
24
	if (!batch) {
989
24
		BIO_printf(bio_err, "You are about to be asked to enter information that will be incorporated\n");
990
24
		BIO_printf(bio_err, "into your certificate request.\n");
991
24
		BIO_printf(bio_err, "What you are about to enter is what is called a Distinguished Name or a DN.\n");
992
24
		BIO_printf(bio_err, "There are quite a few fields but you can leave some blank\n");
993
24
		BIO_printf(bio_err, "For some fields there will be a default value,\n");
994
24
		BIO_printf(bio_err, "If you enter '.', the field will be left blank.\n");
995
24
		BIO_printf(bio_err, "-----\n");
996
24
	}
997
24
	if (sk_CONF_VALUE_num(dn_sk)) {
998
24
		i = -1;
999
24
start:		for (;;) {
1000
			int ret;
1001
240
			i++;
1002
240
			if (sk_CONF_VALUE_num(dn_sk) <= i)
1003
24
				break;
1004
1005
216
			v = sk_CONF_VALUE_value(dn_sk, i);
1006
			p = q = NULL;
1007
216
			type = v->name;
1008

584
			if (!check_end(type, "_min") || !check_end(type, "_max") ||
1009
200
			    !check_end(type, "_default") ||
1010
160
			    !check_end(type, "_value"))
1011
120
				continue;
1012
			/*
1013
			 * Skip past any leading X. X: X, etc to allow for
1014
			 * multiple instances
1015
			 */
1016
2016
			for (p = v->name; *p; p++)
1017

2832
				if ((*p == ':') || (*p == ',') ||
1018
944
				    (*p == '.')) {
1019
32
					p++;
1020
32
					if (*p)
1021
32
						type = p;
1022
					break;
1023
				}
1024
96
			if (*type == '+') {
1025
				mval = -1;
1026
				type++;
1027
			} else
1028
				mval = 0;
1029
			/* If OBJ not recognised ignore it */
1030
96
			if ((nid = OBJ_txt2nid(type)) == NID_undef)
1031
				goto start;
1032
96
			ret = snprintf(buf, sizeof buf, "%s_default", v->name);
1033

192
			if (ret == -1 || ret >= sizeof(buf)) {
1034
				BIO_printf(bio_err, "Name '%s' too long for default\n",
1035
				    v->name);
1036
				return 0;
1037
			}
1038
96
			if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1039
56
				ERR_clear_error();
1040
				def = "";
1041
56
			}
1042
96
			ret = snprintf(buf, sizeof buf, "%s_value", v->name);
1043

192
			if (ret == -1 || ret >= sizeof(buf)) {
1044
				BIO_printf(bio_err, "Name '%s' too long for value\n",
1045
				    v->name);
1046
				return 0;
1047
			}
1048
96
			if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1049
32
				ERR_clear_error();
1050
				value = NULL;
1051
32
			}
1052
96
			ret = snprintf(buf, sizeof buf, "%s_min", v->name);
1053

192
			if (ret == -1 || ret >= sizeof(buf)) {
1054
				BIO_printf(bio_err, "Name '%s' too long for min\n",
1055
				    v->name);
1056
				return 0;
1057
			}
1058
96
			if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1059
88
				ERR_clear_error();
1060
88
				n_min = -1;
1061
88
			}
1062
96
			ret = snprintf(buf, sizeof buf, "%s_max", v->name);
1063

192
			if (ret == -1 || ret >= sizeof(buf)) {
1064
				BIO_printf(bio_err, "Name '%s' too long for max\n",
1065
				    v->name);
1066
				return 0;
1067
			}
1068
96
			if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1069
88
				ERR_clear_error();
1070
88
				n_max = -1;
1071
88
			}
1072
192
			if (!add_DN_object(subj, v->value, def, value, nid,
1073
96
				n_min, n_max, chtype, mval))
1074
				return 0;
1075

96
		}
1076
24
		if (X509_NAME_entry_count(subj) == 0) {
1077
			BIO_printf(bio_err, "error, no objects specified in config file\n");
1078
			return 0;
1079
		}
1080
24
		if (attribs) {
1081

8
			if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0) &&
1082
			    (!batch)) {
1083
				BIO_printf(bio_err,
1084
				    "\nPlease enter the following 'extra' attributes\n");
1085
				BIO_printf(bio_err,
1086
				    "to be sent with your certificate request\n");
1087
			}
1088
8
			i = -1;
1089
8
start2:			for (;;) {
1090
				int ret;
1091
8
				i++;
1092

8
				if ((attr_sk == NULL) ||
1093
				    (sk_CONF_VALUE_num(attr_sk) <= i))
1094
8
					break;
1095
1096
				v = sk_CONF_VALUE_value(attr_sk, i);
1097
				type = v->name;
1098
				if ((nid = OBJ_txt2nid(type)) == NID_undef)
1099
					goto start2;
1100
				ret = snprintf(buf, sizeof buf, "%s_default", type);
1101
				if (ret == -1 || ret >= sizeof(buf)) {
1102
					BIO_printf(bio_err, "Name '%s' too long for default\n",
1103
					    v->name);
1104
					return 0;
1105
				}
1106
				if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1107
				    == NULL) {
1108
					ERR_clear_error();
1109
					def = "";
1110
				}
1111
				ret = snprintf(buf, sizeof buf, "%s_value", type);
1112
				if (ret == -1 || ret >= sizeof(buf)) {
1113
					BIO_printf(bio_err, "Name '%s' too long for value\n",
1114
					    v->name);
1115
					return 0;
1116
				}
1117
				if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1118
				    == NULL) {
1119
					ERR_clear_error();
1120
					value = NULL;
1121
				}
1122
				ret = snprintf(buf, sizeof buf, "%s_min", type);
1123
				if (ret == -1 || ret >= sizeof(buf)) {
1124
					BIO_printf(bio_err, "Name '%s' too long for min\n",
1125
					    v->name);
1126
					return 0;
1127
				}
1128
				if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1129
					ERR_clear_error();
1130
					n_min = -1;
1131
				}
1132
				ret = snprintf(buf, sizeof buf, "%s_max", type);
1133
				if (ret == -1 || ret >= sizeof(buf)) {
1134
					BIO_printf(bio_err, "Name '%s' too long for max\n",
1135
					    v->name);
1136
					return 0;
1137
				}
1138
				if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1139
					ERR_clear_error();
1140
					n_max = -1;
1141
				}
1142
				if (!add_attribute_object(req,
1143
					v->value, def, value, nid, n_min, n_max, chtype))
1144
					return 0;
1145
			}
1146
		}
1147
	} else {
1148
		BIO_printf(bio_err, "No template, please set one up.\n");
1149
		return 0;
1150
	}
1151
1152
24
	return 1;
1153
1154
24
}
1155
1156
static int
1157
auto_info(X509_REQ * req, STACK_OF(CONF_VALUE) * dn_sk,
1158
    STACK_OF(CONF_VALUE) * attr_sk, int attribs, unsigned long chtype)
1159
{
1160
	int i;
1161
	char *p, *q;
1162
	char *type;
1163
	CONF_VALUE *v;
1164
	X509_NAME *subj;
1165
1166
	subj = X509_REQ_get_subject_name(req);
1167
1168
	for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1169
		int mval;
1170
		v = sk_CONF_VALUE_value(dn_sk, i);
1171
		p = q = NULL;
1172
		type = v->name;
1173
		/*
1174
		 * Skip past any leading X. X: X, etc to allow for multiple
1175
		 * instances
1176
		 */
1177
		for (p = v->name; *p; p++)
1178
			if ((*p == ':') || (*p == ',') || (*p == '.')) {
1179
				p++;
1180
				if (*p)
1181
					type = p;
1182
				break;
1183
			}
1184
		if (*p == '+') {
1185
			p++;
1186
			mval = -1;
1187
		} else
1188
			mval = 0;
1189
		if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1190
			(unsigned char *) v->value, -1, -1, mval))
1191
			return 0;
1192
1193
	}
1194
1195
	if (!X509_NAME_entry_count(subj)) {
1196
		BIO_printf(bio_err, "error, no objects specified in config file\n");
1197
		return 0;
1198
	}
1199
	if (attribs) {
1200
		for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1201
			v = sk_CONF_VALUE_value(attr_sk, i);
1202
			if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1203
				(unsigned char *) v->value, -1))
1204
				return 0;
1205
		}
1206
	}
1207
	return 1;
1208
}
1209
1210
1211
static int
1212
add_DN_object(X509_NAME * n, char *text, const char *def, char *value,
1213
    int nid, int n_min, int n_max, unsigned long chtype, int mval)
1214
{
1215
	int i, ret = 0;
1216
192
	char buf[1024];
1217
start:
1218
96
	if (!batch)
1219
96
		BIO_printf(bio_err, "%s [%s]:", text, def);
1220
96
	(void) BIO_flush(bio_err);
1221
96
	if (value != NULL) {
1222
64
		strlcpy(buf, value, sizeof buf);
1223
64
		strlcat(buf, "\n", sizeof buf);
1224
64
		BIO_printf(bio_err, "%s\n", value);
1225
64
	} else {
1226
32
		buf[0] = '\0';
1227
32
		if (!batch) {
1228
32
			if (!fgets(buf, sizeof buf, stdin))
1229
				return 0;
1230
		} else {
1231
			buf[0] = '\n';
1232
			buf[1] = '\0';
1233
		}
1234
	}
1235
1236
96
	if (buf[0] == '\0')
1237
		return (0);
1238
96
	else if (buf[0] == '\n') {
1239
		if ((def == NULL) || (def[0] == '\0'))
1240
			return (1);
1241
		strlcpy(buf, def, sizeof buf);
1242
		strlcat(buf, "\n", sizeof buf);
1243

96
	} else if ((buf[0] == '.') && (buf[1] == '\n'))
1244
		return (1);
1245
1246
96
	i = strlen(buf);
1247
96
	if (buf[i - 1] != '\n') {
1248
		BIO_printf(bio_err, "weird input :-(\n");
1249
		return (0);
1250
	}
1251
96
	buf[--i] = '\0';
1252
96
	if (!req_check_len(i, n_min, n_max))
1253
		goto start;
1254
96
	if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1255
		(unsigned char *) buf, -1, -1, mval))
1256
		goto err;
1257
96
	ret = 1;
1258
err:
1259
96
	return (ret);
1260
96
}
1261
1262
static int
1263
add_attribute_object(X509_REQ * req, char *text, const char *def,
1264
    char *value, int nid, int n_min,
1265
    int n_max, unsigned long chtype)
1266
{
1267
	int i;
1268
	static char buf[1024];
1269
1270
start:
1271
	if (!batch)
1272
		BIO_printf(bio_err, "%s [%s]:", text, def);
1273
	(void) BIO_flush(bio_err);
1274
	if (value != NULL) {
1275
		strlcpy(buf, value, sizeof buf);
1276
		strlcat(buf, "\n", sizeof buf);
1277
		BIO_printf(bio_err, "%s\n", value);
1278
	} else {
1279
		buf[0] = '\0';
1280
		if (!batch) {
1281
			if (!fgets(buf, sizeof buf, stdin))
1282
				return 0;
1283
		} else {
1284
			buf[0] = '\n';
1285
			buf[1] = '\0';
1286
		}
1287
	}
1288
1289
	if (buf[0] == '\0')
1290
		return (0);
1291
	else if (buf[0] == '\n') {
1292
		if ((def == NULL) || (def[0] == '\0'))
1293
			return (1);
1294
		strlcpy(buf, def, sizeof buf);
1295
		strlcat(buf, "\n", sizeof buf);
1296
	} else if ((buf[0] == '.') && (buf[1] == '\n'))
1297
		return (1);
1298
1299
	i = strlen(buf);
1300
	if (buf[i - 1] != '\n') {
1301
		BIO_printf(bio_err, "weird input :-(\n");
1302
		return (0);
1303
	}
1304
	buf[--i] = '\0';
1305
	if (!req_check_len(i, n_min, n_max))
1306
		goto start;
1307
1308
	if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1309
		(unsigned char *) buf, -1)) {
1310
		BIO_printf(bio_err, "Error adding attribute\n");
1311
		ERR_print_errors(bio_err);
1312
		goto err;
1313
	}
1314
	return (1);
1315
err:
1316
	return (0);
1317
}
1318
1319
static int
1320
req_check_len(int len, int n_min, int n_max)
1321
{
1322

200
	if ((n_min > 0) && (len < n_min)) {
1323
		BIO_printf(bio_err, "string is too short, it needs to be at least %d bytes long\n", n_min);
1324
		return (0);
1325
	}
1326

104
	if ((n_max >= 0) && (len > n_max)) {
1327
		BIO_printf(bio_err, "string is too long, it needs to be less than  %d bytes long\n", n_max);
1328
		return (0);
1329
	}
1330
96
	return (1);
1331
96
}
1332
1333
/* Check if the end of a string matches 'end' */
1334
static int
1335
check_end(const char *str, const char *end)
1336
{
1337
	int elen, slen;
1338
	const char *tmp;
1339
1568
	elen = strlen(end);
1340
784
	slen = strlen(str);
1341
784
	if (elen > slen)
1342
		return 1;
1343
784
	tmp = str + slen - elen;
1344
784
	return strcmp(tmp, end);
1345
784
}
1346
1347
static EVP_PKEY_CTX *
1348
set_keygen_ctx(BIO * err, const char *gstr, int *pkey_type,
1349
    long *pkeylen, char **palgnam)
1350
{
1351
	EVP_PKEY_CTX *gctx = NULL;
1352
	EVP_PKEY *param = NULL;
1353
	long keylen = -1;
1354
	BIO *pbio = NULL;
1355
	const char *paramfile = NULL;
1356
212
	const char *errstr;
1357
1358
106
	if (gstr == NULL) {
1359
40
		*pkey_type = EVP_PKEY_RSA;
1360
40
		keylen = *pkeylen;
1361

172
	} else if (gstr[0] >= '0' && gstr[0] <= '9') {
1362
		*pkey_type = EVP_PKEY_RSA;
1363
		keylen = strtonum(gstr, 0, LONG_MAX, &errstr);
1364
		if (errstr) {
1365
			BIO_printf(err, "bad algorithm %s: %s\n", gstr, errstr);
1366
			return NULL;
1367
		}
1368
		*pkeylen = keylen;
1369
66
	} else if (!strncmp(gstr, "param:", 6))
1370
		paramfile = gstr + 6;
1371
	else {
1372
66
		const char *p = strchr(gstr, ':');
1373
		int len;
1374
		const EVP_PKEY_ASN1_METHOD *ameth;
1375
1376
66
		if (p)
1377
16
			len = p - gstr;
1378
		else
1379
50
			len = strlen(gstr);
1380
1381
66
		ameth = EVP_PKEY_asn1_find_str(NULL, gstr, len);
1382
1383
66
		if (!ameth) {
1384
			BIO_printf(err, "Unknown algorithm %.*s\n", len, gstr);
1385
			return NULL;
1386
		}
1387
66
		EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL,
1388
		    ameth);
1389
66
		if (*pkey_type == EVP_PKEY_RSA) {
1390
58
			if (p) {
1391
8
				keylen = strtonum(p + 1, 0, LONG_MAX, &errstr);
1392
8
				if (errstr) {
1393
					BIO_printf(err, "bad algorithm %s: %s\n",
1394
					    p + 1, errstr);
1395
					return NULL;
1396
				}
1397
8
				*pkeylen = keylen;
1398
8
			} else
1399
50
				keylen = *pkeylen;
1400
8
		} else if (p)
1401
8
			paramfile = p + 1;
1402
66
	}
1403
1404
106
	if (paramfile) {
1405
8
		pbio = BIO_new_file(paramfile, "r");
1406
8
		if (!pbio) {
1407
			BIO_printf(err, "Can't open parameter file %s\n",
1408
			    paramfile);
1409
			return NULL;
1410
		}
1411
8
		param = PEM_read_bio_Parameters(pbio, NULL);
1412
1413
8
		if (!param) {
1414
			X509 *x;
1415
			(void) BIO_reset(pbio);
1416
			x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1417
			if (x) {
1418
				param = X509_get_pubkey(x);
1419
				X509_free(x);
1420
			}
1421
		}
1422
8
		BIO_free(pbio);
1423
1424
8
		if (!param) {
1425
			BIO_printf(err, "Error reading parameter file %s\n",
1426
			    paramfile);
1427
			return NULL;
1428
		}
1429
8
		if (*pkey_type == -1)
1430
			*pkey_type = EVP_PKEY_id(param);
1431
8
		else if (*pkey_type != EVP_PKEY_base_id(param)) {
1432
			BIO_printf(err, "Key Type does not match parameters\n");
1433
			EVP_PKEY_free(param);
1434
			return NULL;
1435
		}
1436
	}
1437
106
	if (palgnam) {
1438
		const EVP_PKEY_ASN1_METHOD *ameth;
1439
106
		const char *anam;
1440
106
		ameth = EVP_PKEY_asn1_find(NULL, *pkey_type);
1441
106
		if (!ameth) {
1442
			BIO_puts(err, "Internal error: can't find key algorithm\n");
1443
			return NULL;
1444
		}
1445
106
		EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1446
106
		*palgnam = strdup(anam);
1447
212
	}
1448
106
	if (param) {
1449
8
		gctx = EVP_PKEY_CTX_new(param, NULL);
1450
8
		*pkeylen = EVP_PKEY_bits(param);
1451
8
		EVP_PKEY_free(param);
1452
8
	} else
1453
98
		gctx = EVP_PKEY_CTX_new_id(*pkey_type, NULL);
1454
1455
106
	if (!gctx) {
1456
		BIO_puts(err, "Error allocating keygen context\n");
1457
		ERR_print_errors(err);
1458
		return NULL;
1459
	}
1460
106
	if (EVP_PKEY_keygen_init(gctx) <= 0) {
1461
		BIO_puts(err, "Error initializing keygen context\n");
1462
		ERR_print_errors(err);
1463
		return NULL;
1464
	}
1465
106
	if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1466
98
		if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1467
			BIO_puts(err, "Error setting RSA keysize\n");
1468
			ERR_print_errors(err);
1469
			EVP_PKEY_CTX_free(gctx);
1470
			return NULL;
1471
		}
1472
	}
1473
1474
106
	return gctx;
1475
106
}
1476
1477
static int
1478
genpkey_cb(EVP_PKEY_CTX * ctx)
1479
{
1480
18134
	char c = '*';
1481
9067
	BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1482
	int p;
1483
9067
	p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1484
9067
	if (p == 0)
1485
8283
		c = '.';
1486
9067
	if (p == 1)
1487
588
		c = '+';
1488
9067
	if (p == 2)
1489
		c = '*';
1490
9067
	if (p == 3)
1491
196
		c = '\n';
1492
9067
	BIO_write(b, &c, 1);
1493
9067
	(void) BIO_flush(b);
1494
9067
	return 1;
1495
9067
}
1496
1497
static int
1498
do_sign_init(BIO * err, EVP_MD_CTX * ctx, EVP_PKEY * pkey,
1499
    const EVP_MD * md, STACK_OF(OPENSSL_STRING) * sigopts)
1500
{
1501
380
	EVP_PKEY_CTX *pkctx = NULL;
1502
	int i;
1503
190
	EVP_MD_CTX_init(ctx);
1504
190
	if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1505
		return 0;
1506
380
	for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1507
		char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1508
		if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1509
			BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1510
			ERR_print_errors(bio_err);
1511
			return 0;
1512
		}
1513
	}
1514
190
	return 1;
1515
190
}
1516
1517
int
1518
do_X509_sign(BIO * err, X509 * x, EVP_PKEY * pkey, const EVP_MD * md,
1519
    STACK_OF(OPENSSL_STRING) * sigopts)
1520
{
1521
	int rv;
1522
244
	EVP_MD_CTX mctx;
1523
122
	EVP_MD_CTX_init(&mctx);
1524
122
	rv = do_sign_init(err, &mctx, pkey, md, sigopts);
1525
122
	if (rv > 0)
1526
122
		rv = X509_sign_ctx(x, &mctx);
1527
122
	EVP_MD_CTX_cleanup(&mctx);
1528
244
	return rv > 0 ? 1 : 0;
1529
122
}
1530
1531
1532
int
1533
do_X509_REQ_sign(BIO * err, X509_REQ * x, EVP_PKEY * pkey, const EVP_MD * md,
1534
    STACK_OF(OPENSSL_STRING) * sigopts)
1535
{
1536
	int rv;
1537
120
	EVP_MD_CTX mctx;
1538
60
	EVP_MD_CTX_init(&mctx);
1539
60
	rv = do_sign_init(err, &mctx, pkey, md, sigopts);
1540
60
	if (rv > 0)
1541
60
		rv = X509_REQ_sign_ctx(x, &mctx);
1542
60
	EVP_MD_CTX_cleanup(&mctx);
1543
120
	return rv > 0 ? 1 : 0;
1544
60
}
1545
1546
1547
1548
int
1549
do_X509_CRL_sign(BIO * err, X509_CRL * x, EVP_PKEY * pkey, const EVP_MD * md,
1550
    STACK_OF(OPENSSL_STRING) * sigopts)
1551
{
1552
	int rv;
1553
16
	EVP_MD_CTX mctx;
1554
8
	EVP_MD_CTX_init(&mctx);
1555
8
	rv = do_sign_init(err, &mctx, pkey, md, sigopts);
1556
8
	if (rv > 0)
1557
8
		rv = X509_CRL_sign_ctx(x, &mctx);
1558
8
	EVP_MD_CTX_cleanup(&mctx);
1559
16
	return rv > 0 ? 1 : 0;
1560
8
}