]> git.ipfire.org Git - thirdparty/openssl.git/blob - apps/req.c
APPS: make apps strict on app_RAND_load() and app_RAND_write() failure
[thirdparty/openssl.git] / apps / req.c
1 /*
2 * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <time.h>
13 #include <string.h>
14 #include <ctype.h>
15 #include "apps.h"
16 #include "progs.h"
17 #include <openssl/bio.h>
18 #include <openssl/evp.h>
19 #include <openssl/conf.h>
20 #include <openssl/err.h>
21 #include <openssl/asn1.h>
22 #include <openssl/x509.h>
23 #include <openssl/x509v3.h>
24 #include <openssl/objects.h>
25 #include <openssl/pem.h>
26 #include <openssl/bn.h>
27 #include <openssl/lhash.h>
28 #include <openssl/rsa.h>
29 #ifndef OPENSSL_NO_DSA
30 # include <openssl/dsa.h>
31 #endif
32
33 #define BITS "default_bits"
34 #define KEYFILE "default_keyfile"
35 #define PROMPT "prompt"
36 #define DISTINGUISHED_NAME "distinguished_name"
37 #define ATTRIBUTES "attributes"
38 #define V3_EXTENSIONS "x509_extensions"
39 #define REQ_EXTENSIONS "req_extensions"
40 #define STRING_MASK "string_mask"
41 #define UTF8_IN "utf8"
42
43 #define DEFAULT_KEY_LENGTH 2048
44 #define MIN_KEY_LENGTH 512
45 #define DEFAULT_DAYS 30 /* default cert validity period in days */
46 #define UNSET_DAYS -2 /* -1 may be used for testing expiration checks */
47 #define EXT_COPY_UNSET -1
48
49 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj,
50 int mutlirdn, int attribs, unsigned long chtype);
51 static int prompt_info(X509_REQ *req,
52 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
53 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
54 int attribs, unsigned long chtype);
55 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
56 STACK_OF(CONF_VALUE) *attr, int attribs,
57 unsigned long chtype);
58 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
59 char *value, int nid, int n_min, int n_max,
60 unsigned long chtype);
61 static int add_DN_object(X509_NAME *n, char *text, const char *def,
62 char *value, int nid, int n_min, int n_max,
63 unsigned long chtype, int mval);
64 static int genpkey_cb(EVP_PKEY_CTX *ctx);
65 static int build_data(char *text, const char *def, char *value,
66 int n_min, int n_max, char *buf, const int buf_size,
67 const char *desc1, const char *desc2);
68 static int req_check_len(int len, int n_min, int n_max);
69 static int check_end(const char *str, const char *end);
70 static int join(char buf[], size_t buf_size, const char *name,
71 const char *tail, const char *desc);
72 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
73 int *pkey_type, long *pkeylen,
74 char **palgnam, ENGINE *keygen_engine);
75
76 static const char *section = "req";
77 static CONF *req_conf = NULL;
78 static CONF *addext_conf = NULL;
79 static int batch = 0;
80
81 typedef enum OPTION_choice {
82 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
83 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
84 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
85 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
86 OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
87 OPT_VERIFY, OPT_NOENC, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
88 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
89 OPT_CA, OPT_CAKEY,
90 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL,
91 OPT_COPY_EXTENSIONS, OPT_ADDEXT, OPT_EXTENSIONS,
92 OPT_REQEXTS, OPT_PRECERT, OPT_MD,
93 OPT_SECTION,
94 OPT_R_ENUM, OPT_PROV_ENUM
95 } OPTION_CHOICE;
96
97 const OPTIONS req_options[] = {
98 OPT_SECTION("General"),
99 {"help", OPT_HELP, '-', "Display this summary"},
100 #ifndef OPENSSL_NO_ENGINE
101 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
102 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
103 "Specify engine to be used for key generation operations"},
104 #endif
105 {"in", OPT_IN, '<', "X.509 request input file"},
106 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
107 {"verify", OPT_VERIFY, '-', "Verify self-signature on the request"},
108
109 OPT_SECTION("Certificate"),
110 {"new", OPT_NEW, '-', "New request"},
111 {"config", OPT_CONFIG, '<', "Request template file"},
112 {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
113 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
114 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
115 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
116 {"text", OPT_TEXT, '-', "Text form of request"},
117 {"x509", OPT_X509, '-',
118 "Output an x509 structure instead of a cert request"},
119 {"CA", OPT_CA, '<', "Issuer certificate to use with -x509"},
120 {"CAkey", OPT_CAKEY, 's',
121 "Issuer private key to use with -x509; default is -CA arg"},
122 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
123 {"subj", OPT_SUBJ, 's', "Set or modify subject of request or cert"},
124 {"subject", OPT_SUBJECT, '-',
125 "Print the subject of the output request or cert"},
126 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
127 "Deprecated; multi-valued RDNs support is always on."},
128 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
129 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
130 {"copy_extensions", OPT_COPY_EXTENSIONS, 's',
131 "copy extensions from request when using -x509"},
132 {"addext", OPT_ADDEXT, 's',
133 "Additional cert extension key=value pair (may be given more than once)"},
134 {"extensions", OPT_EXTENSIONS, 's',
135 "Cert extension section (override value in config file)"},
136 {"reqexts", OPT_REQEXTS, 's',
137 "Request extension section (override value in config file)"},
138 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
139
140 OPT_SECTION("Keys and Signing"),
141 {"key", OPT_KEY, 's', "Private key to use"},
142 {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"},
143 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
144 {"keyout", OPT_KEYOUT, '>', "File to save newly created private key"},
145 {"passin", OPT_PASSIN, 's', "Private key and certificate password source"},
146 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
147 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
148 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
149 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
150 {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
151 {"", OPT_MD, '-', "Any supported digest"},
152
153 OPT_SECTION("Output"),
154 {"out", OPT_OUT, '>', "Output file"},
155 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
156 {"batch", OPT_BATCH, '-',
157 "Do not ask anything during request generation"},
158 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
159 {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"},
160 {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"},
161 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
162 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
163 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
164
165 OPT_R_OPTIONS,
166 OPT_PROV_OPTIONS,
167 {NULL}
168 };
169
170 /*
171 * An LHASH of strings, where each string is an extension name.
172 */
173 static unsigned long ext_name_hash(const OPENSSL_STRING *a)
174 {
175 return OPENSSL_LH_strhash((const char *)a);
176 }
177
178 static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
179 {
180 return strcmp((const char *)a, (const char *)b);
181 }
182
183 static void exts_cleanup(OPENSSL_STRING *x)
184 {
185 OPENSSL_free((char *)x);
186 }
187
188 /*
189 * Is the |kv| key already duplicated? This is remarkably tricky to get right.
190 * Return 0 if unique, -1 on runtime error; 1 if found or a syntax error.
191 */
192 static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
193 {
194 char *p;
195 size_t off;
196
197 /* Check syntax. */
198 /* Skip leading whitespace, make a copy. */
199 while (*kv && isspace(*kv))
200 if (*++kv == '\0')
201 return 1;
202 if ((p = strchr(kv, '=')) == NULL)
203 return 1;
204 off = p - kv;
205 if ((kv = OPENSSL_strdup(kv)) == NULL)
206 return -1;
207
208 /* Skip trailing space before the equal sign. */
209 for (p = kv + off; p > kv; --p)
210 if (!isspace(p[-1]))
211 break;
212 if (p == kv) {
213 OPENSSL_free(kv);
214 return 1;
215 }
216 *p = '\0';
217
218 /* Finally have a clean "key"; see if it's there [by attempt to add it]. */
219 p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING *)kv);
220 if (p != NULL) {
221 OPENSSL_free(p);
222 return 1;
223 } else if (lh_OPENSSL_STRING_error(addexts)) {
224 OPENSSL_free(kv);
225 return -1;
226 }
227
228 return 0;
229 }
230
231 int req_main(int argc, char **argv)
232 {
233 ASN1_INTEGER *serial = NULL;
234 BIO *out = NULL;
235 ENGINE *e = NULL, *gen_eng = NULL;
236 EVP_PKEY *pkey = NULL, *CAkey = NULL;
237 EVP_PKEY_CTX *genctx = NULL;
238 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL, *vfyopts = NULL;
239 LHASH_OF(OPENSSL_STRING) *addexts = NULL;
240 X509 *new_x509 = NULL, *CAcert = NULL;
241 X509_REQ *req = NULL;
242 const EVP_CIPHER *cipher = NULL;
243 const EVP_MD *md_alg = NULL, *digest = NULL;
244 int ext_copy = EXT_COPY_UNSET;
245 BIO *addext_bio = NULL;
246 char *extensions = NULL;
247 const char *infile = NULL, *CAfile = NULL, *CAkeyfile = NULL;
248 char *outfile = NULL, *keyfile = NULL, *digestname = NULL;
249 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
250 char *passin = NULL, *passout = NULL;
251 char *nofree_passin = NULL, *nofree_passout = NULL;
252 char *req_exts = NULL, *subj = NULL;
253 X509_NAME *fsubj = NULL;
254 char *template = default_config_file, *keyout = NULL;
255 const char *keyalg = NULL;
256 OPTION_CHOICE o;
257 int days = UNSET_DAYS;
258 int ret = 1, gen_x509 = 0, i = 0, newreq = 0, verbose = 0;
259 int pkey_type = -1;
260 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
261 int modulus = 0, multirdn = 1, verify = 0, noout = 0, text = 0;
262 int noenc = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
263 long newkey_len = -1;
264 unsigned long chtype = MBSTRING_ASC, reqflag = 0;
265
266 #ifndef OPENSSL_NO_DES
267 cipher = EVP_des_ede3_cbc();
268 #endif
269
270 prog = opt_init(argc, argv, req_options);
271 while ((o = opt_next()) != OPT_EOF) {
272 switch (o) {
273 case OPT_EOF:
274 case OPT_ERR:
275 opthelp:
276 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
277 goto end;
278 case OPT_HELP:
279 opt_help(req_options);
280 ret = 0;
281 goto end;
282 case OPT_INFORM:
283 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
284 goto opthelp;
285 break;
286 case OPT_OUTFORM:
287 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
288 goto opthelp;
289 break;
290 case OPT_ENGINE:
291 e = setup_engine(opt_arg(), 0);
292 break;
293 case OPT_KEYGEN_ENGINE:
294 #ifndef OPENSSL_NO_ENGINE
295 gen_eng = setup_engine(opt_arg(), 0);
296 if (gen_eng == NULL) {
297 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
298 goto opthelp;
299 }
300 #endif
301 break;
302 case OPT_KEY:
303 keyfile = opt_arg();
304 break;
305 case OPT_PUBKEY:
306 pubkey = 1;
307 break;
308 case OPT_NEW:
309 newreq = 1;
310 break;
311 case OPT_CONFIG:
312 template = opt_arg();
313 break;
314 case OPT_SECTION:
315 section = opt_arg();
316 break;
317 case OPT_KEYFORM:
318 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
319 goto opthelp;
320 break;
321 case OPT_IN:
322 infile = opt_arg();
323 break;
324 case OPT_OUT:
325 outfile = opt_arg();
326 break;
327 case OPT_KEYOUT:
328 keyout = opt_arg();
329 break;
330 case OPT_PASSIN:
331 passargin = opt_arg();
332 break;
333 case OPT_PASSOUT:
334 passargout = opt_arg();
335 break;
336 case OPT_R_CASES:
337 if (!opt_rand(o))
338 goto end;
339 break;
340 case OPT_PROV_CASES:
341 if (!opt_provider(o))
342 goto end;
343 break;
344 case OPT_NEWKEY:
345 keyalg = opt_arg();
346 newreq = 1;
347 break;
348 case OPT_PKEYOPT:
349 if (pkeyopts == NULL)
350 pkeyopts = sk_OPENSSL_STRING_new_null();
351 if (pkeyopts == NULL
352 || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
353 goto opthelp;
354 break;
355 case OPT_SIGOPT:
356 if (!sigopts)
357 sigopts = sk_OPENSSL_STRING_new_null();
358 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
359 goto opthelp;
360 break;
361 case OPT_VFYOPT:
362 if (!vfyopts)
363 vfyopts = sk_OPENSSL_STRING_new_null();
364 if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
365 goto opthelp;
366 break;
367 case OPT_BATCH:
368 batch = 1;
369 break;
370 case OPT_NEWHDR:
371 newhdr = 1;
372 break;
373 case OPT_MODULUS:
374 modulus = 1;
375 break;
376 case OPT_VERIFY:
377 verify = 1;
378 break;
379 case OPT_NODES:
380 case OPT_NOENC:
381 noenc = 1;
382 break;
383 case OPT_NOOUT:
384 noout = 1;
385 break;
386 case OPT_VERBOSE:
387 verbose = 1;
388 break;
389 case OPT_UTF8:
390 chtype = MBSTRING_UTF8;
391 break;
392 case OPT_NAMEOPT:
393 if (!set_nameopt(opt_arg()))
394 goto opthelp;
395 break;
396 case OPT_REQOPT:
397 if (!set_cert_ex(&reqflag, opt_arg()))
398 goto opthelp;
399 break;
400 case OPT_TEXT:
401 text = 1;
402 break;
403 case OPT_X509:
404 gen_x509 = 1;
405 break;
406 case OPT_CA:
407 CAfile = opt_arg();
408 break;
409 case OPT_CAKEY:
410 CAkeyfile = opt_arg();
411 break;
412 case OPT_DAYS:
413 days = atoi(opt_arg());
414 if (days < -1) {
415 BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n",
416 prog);
417 goto end;
418 }
419 break;
420 case OPT_SET_SERIAL:
421 if (serial != NULL) {
422 BIO_printf(bio_err, "Serial number supplied twice\n");
423 goto opthelp;
424 }
425 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
426 if (serial == NULL)
427 goto opthelp;
428 break;
429 case OPT_SUBJECT:
430 subject = 1;
431 break;
432 case OPT_SUBJ:
433 subj = opt_arg();
434 break;
435 case OPT_MULTIVALUE_RDN:
436 /* obsolete */
437 break;
438 case OPT_COPY_EXTENSIONS:
439 if (!set_ext_copy(&ext_copy, opt_arg())) {
440 BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n",
441 opt_arg());
442 goto end;
443 }
444 break;
445 case OPT_ADDEXT:
446 p = opt_arg();
447 if (addexts == NULL) {
448 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
449 addext_bio = BIO_new(BIO_s_mem());
450 if (addexts == NULL || addext_bio == NULL)
451 goto end;
452 }
453 i = duplicated(addexts, p);
454 if (i == 1) {
455 BIO_printf(bio_err, "Duplicate extension: %s\n", p);
456 goto opthelp;
457 }
458 if (i < 0 || BIO_printf(addext_bio, "%s\n", p) < 0)
459 goto end;
460 break;
461 case OPT_EXTENSIONS:
462 extensions = opt_arg();
463 break;
464 case OPT_REQEXTS:
465 req_exts = opt_arg();
466 break;
467 case OPT_PRECERT:
468 newreq = precert = 1;
469 break;
470 case OPT_MD:
471 digestname = opt_unknown();
472 break;
473 }
474 }
475
476 /* No extra arguments. */
477 argc = opt_num_rest();
478 if (argc != 0)
479 goto opthelp;
480
481 if (!app_RAND_load())
482 goto end;
483
484 if (digestname != NULL) {
485 if (!opt_md(digestname, &md_alg))
486 goto opthelp;
487 digest = md_alg;
488 }
489
490 if (!gen_x509) {
491 if (days != UNSET_DAYS)
492 BIO_printf(bio_err, "Ignoring -days without -x509; not generating a certificate\n");
493 if (ext_copy == EXT_COPY_NONE)
494 BIO_printf(bio_err, "Ignoring -copy_extensions 'none' when -x509 is not given\n");
495 }
496 if (gen_x509 && infile == NULL)
497 newreq = 1;
498
499 if (!app_passwd(passargin, passargout, &passin, &passout)) {
500 BIO_printf(bio_err, "Error getting passwords\n");
501 goto end;
502 }
503
504 if ((req_conf = app_load_config_verbose(template, verbose)) == NULL)
505 goto end;
506 if (addext_bio != NULL) {
507 if (verbose)
508 BIO_printf(bio_err,
509 "Using additional configuration from -addext options\n");
510 if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
511 goto end;
512 }
513 if (template != default_config_file && !app_load_modules(req_conf))
514 goto end;
515
516 if (req_conf != NULL) {
517 p = NCONF_get_string(req_conf, NULL, "oid_file");
518 if (p == NULL)
519 ERR_clear_error();
520 if (p != NULL) {
521 BIO *oid_bio;
522
523 oid_bio = BIO_new_file(p, "r");
524 if (oid_bio == NULL) {
525 if (verbose) {
526 BIO_printf(bio_err,
527 "Problems opening '%s' for extra OIDs\n", p);
528 ERR_print_errors(bio_err);
529 }
530 } else {
531 OBJ_create_objects(oid_bio);
532 BIO_free(oid_bio);
533 }
534 }
535 }
536 if (!add_oid_section(req_conf))
537 goto end;
538
539 if (md_alg == NULL) {
540 p = NCONF_get_string(req_conf, section, "default_md");
541 if (p == NULL) {
542 ERR_clear_error();
543 } else {
544 if (!opt_md(p, &md_alg))
545 goto opthelp;
546 digest = md_alg;
547 }
548 }
549
550 if (extensions == NULL) {
551 extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS);
552 if (extensions == NULL)
553 ERR_clear_error();
554 }
555 if (extensions != NULL) {
556 /* Check syntax of file */
557 X509V3_CTX ctx;
558
559 X509V3_set_ctx_test(&ctx);
560 X509V3_set_nconf(&ctx, req_conf);
561 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
562 BIO_printf(bio_err,
563 "Error checking x509 extension section %s\n",
564 extensions);
565 goto end;
566 }
567 }
568 if (addext_conf != NULL) {
569 /* Check syntax of command line extensions */
570 X509V3_CTX ctx;
571
572 X509V3_set_ctx_test(&ctx);
573 X509V3_set_nconf(&ctx, addext_conf);
574 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
575 BIO_printf(bio_err, "Error checking extensions defined using -addext\n");
576 goto end;
577 }
578 }
579
580 if (passin == NULL) {
581 passin = nofree_passin =
582 NCONF_get_string(req_conf, section, "input_password");
583 if (passin == NULL)
584 ERR_clear_error();
585 }
586
587 if (passout == NULL) {
588 passout = nofree_passout =
589 NCONF_get_string(req_conf, section, "output_password");
590 if (passout == NULL)
591 ERR_clear_error();
592 }
593
594 p = NCONF_get_string(req_conf, section, STRING_MASK);
595 if (p == NULL)
596 ERR_clear_error();
597
598 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
599 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
600 goto end;
601 }
602
603 if (chtype != MBSTRING_UTF8) {
604 p = NCONF_get_string(req_conf, section, UTF8_IN);
605 if (p == NULL)
606 ERR_clear_error();
607 else if (strcmp(p, "yes") == 0)
608 chtype = MBSTRING_UTF8;
609 }
610
611 if (req_exts == NULL) {
612 req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS);
613 if (req_exts == NULL)
614 ERR_clear_error();
615 }
616 if (req_exts != NULL) {
617 /* Check syntax of file */
618 X509V3_CTX ctx;
619
620 X509V3_set_ctx_test(&ctx);
621 X509V3_set_nconf(&ctx, req_conf);
622 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
623 BIO_printf(bio_err,
624 "Error checking request extension section %s\n",
625 req_exts);
626 goto end;
627 }
628 }
629
630 if (keyfile != NULL) {
631 pkey = load_key(keyfile, keyform, 0, passin, e, "private key");
632 if (pkey == NULL)
633 goto end;
634 app_RAND_load_conf(req_conf, section);
635 }
636
637 if (newreq && pkey == NULL) {
638 app_RAND_load_conf(req_conf, section);
639
640 if (!NCONF_get_number(req_conf, section, BITS, &newkey_len)) {
641 newkey_len = DEFAULT_KEY_LENGTH;
642 }
643
644 if (keyalg != NULL) {
645 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey_len,
646 &keyalgstr, gen_eng);
647 if (genctx == NULL)
648 goto end;
649 }
650
651 if (newkey_len < MIN_KEY_LENGTH
652 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
653 BIO_printf(bio_err, "Private key length is too short,\n");
654 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld.\n",
655 MIN_KEY_LENGTH, newkey_len);
656 goto end;
657 }
658
659 if (pkey_type == EVP_PKEY_RSA
660 && newkey_len > OPENSSL_RSA_MAX_MODULUS_BITS)
661 BIO_printf(bio_err,
662 "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
663 " Your key size is %ld! Larger key size may behave not as expected.\n",
664 OPENSSL_RSA_MAX_MODULUS_BITS, newkey_len);
665
666 #ifndef OPENSSL_NO_DSA
667 if (pkey_type == EVP_PKEY_DSA
668 && newkey_len > OPENSSL_DSA_MAX_MODULUS_BITS)
669 BIO_printf(bio_err,
670 "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
671 " Your key size is %ld! Larger key size may behave not as expected.\n",
672 OPENSSL_DSA_MAX_MODULUS_BITS, newkey_len);
673 #endif
674
675 if (genctx == NULL) {
676 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey_len,
677 &keyalgstr, gen_eng);
678 if (genctx == NULL)
679 goto end;
680 }
681
682 if (pkeyopts != NULL) {
683 char *genopt;
684 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
685 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
686 if (pkey_ctrl_string(genctx, genopt) <= 0) {
687 BIO_printf(bio_err, "Key parameter error \"%s\"\n", genopt);
688 goto end;
689 }
690 }
691 }
692
693 if (pkey_type == EVP_PKEY_EC) {
694 BIO_printf(bio_err, "Generating an EC private key\n");
695 } else {
696 BIO_printf(bio_err, "Generating a %s private key\n", keyalgstr);
697 }
698
699 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
700 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
701
702 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
703 BIO_puts(bio_err, "Error generating key\n");
704 goto end;
705 }
706
707 EVP_PKEY_CTX_free(genctx);
708 genctx = NULL;
709
710 if (keyout == NULL) {
711 keyout = NCONF_get_string(req_conf, section, KEYFILE);
712 if (keyout == NULL)
713 ERR_clear_error();
714 }
715
716 if (keyout == NULL)
717 BIO_printf(bio_err, "Writing new private key to stdout\n");
718 else
719 BIO_printf(bio_err, "Writing new private key to '%s'\n", keyout);
720 out = bio_open_owner(keyout, outformat, newreq);
721 if (out == NULL)
722 goto end;
723
724 p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
725 if (p == NULL) {
726 ERR_clear_error();
727 p = NCONF_get_string(req_conf, section, "encrypt_key");
728 if (p == NULL)
729 ERR_clear_error();
730 }
731 if ((p != NULL) && (strcmp(p, "no") == 0))
732 cipher = NULL;
733 if (noenc)
734 cipher = NULL;
735
736 i = 0;
737 loop:
738 assert(newreq);
739 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
740 NULL, 0, NULL, passout)) {
741 if ((ERR_GET_REASON(ERR_peek_error()) ==
742 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
743 ERR_clear_error();
744 i++;
745 goto loop;
746 }
747 goto end;
748 }
749 BIO_free(out);
750 out = NULL;
751 BIO_printf(bio_err, "-----\n");
752 }
753
754 /*
755 * subj is expected to be in the format /type0=value0/type1=value1/type2=...
756 * where characters may be escaped by \
757 */
758 if (subj != NULL
759 && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL)
760 goto end;
761
762 if (!newreq) {
763 req = load_csr(infile, informat, "X509 request");
764 if (req == NULL)
765 goto end;
766 }
767
768 if (CAkeyfile == NULL)
769 CAkeyfile = CAfile;
770 if (CAkeyfile != NULL) {
771 if (CAfile == NULL) {
772 BIO_printf(bio_err,
773 "Ignoring -CAkey option since no -CA option is given\n");
774 } else {
775 if ((CAkey = load_key(CAkeyfile, FORMAT_PEM,
776 0, passin, e, "issuer private key")) == NULL)
777 goto end;
778 }
779 }
780 if (CAfile != NULL) {
781 if (!gen_x509) {
782 BIO_printf(bio_err,
783 "Warning: Ignoring -CA option without -x509\n");
784 } else {
785 if (CAkeyfile == NULL) {
786 BIO_printf(bio_err,
787 "Need to give the -CAkey option if using -CA\n");
788 goto end;
789 }
790 if ((CAcert = load_cert_pass(CAfile, 1, passin,
791 "issuer certificate")) == NULL)
792 goto end;
793 if (!X509_check_private_key(CAcert, CAkey)) {
794 BIO_printf(bio_err,
795 "Issuer certificate and key do not match\n");
796 goto end;
797 }
798 }
799 }
800 if (newreq || gen_x509) {
801 if (pkey == NULL /* can happen only if !newreq */) {
802 BIO_printf(bio_err, "Must provide a signature key using -key\n");
803 goto end;
804 }
805
806 if (req == NULL) {
807 req = X509_REQ_new_ex(app_get0_libctx(), app_get0_propq());
808 if (req == NULL) {
809 goto end;
810 }
811
812 if (!make_REQ(req, pkey, fsubj, multirdn, !gen_x509, chtype)){
813 BIO_printf(bio_err, "Error making certificate request\n");
814 goto end;
815 }
816 }
817 if (gen_x509) {
818 EVP_PKEY *pub_key = X509_REQ_get0_pubkey(req);
819 X509V3_CTX ext_ctx;
820 X509_NAME *issuer = CAcert != NULL ? X509_get_subject_name(CAcert) :
821 X509_REQ_get_subject_name(req);
822 X509_NAME *n_subj = fsubj != NULL ? fsubj :
823 X509_REQ_get_subject_name(req);
824
825 if ((new_x509 = X509_new_ex(app_get0_libctx(),
826 app_get0_propq())) == NULL)
827 goto end;
828
829 if (serial != NULL) {
830 if (!X509_set_serialNumber(new_x509, serial))
831 goto end;
832 } else {
833 if (!rand_serial(NULL, X509_get_serialNumber(new_x509)))
834 goto end;
835 }
836
837 if (!X509_set_issuer_name(new_x509, issuer))
838 goto end;
839 if (days == UNSET_DAYS) {
840 days = DEFAULT_DAYS;
841 }
842 if (!set_cert_times(new_x509, NULL, NULL, days))
843 goto end;
844 if (!X509_set_subject_name(new_x509, n_subj))
845 goto end;
846 if (!pub_key || !X509_set_pubkey(new_x509, pub_key))
847 goto end;
848 if (ext_copy == EXT_COPY_UNSET) {
849 BIO_printf(bio_err, "Warning: No -copy_extensions given; ignoring any extensions in the request\n");
850 } else if (!copy_extensions(new_x509, req, ext_copy)) {
851 BIO_printf(bio_err, "Error copying extensions from request\n");
852 goto end;
853 }
854
855 /* Set up V3 context struct */
856 X509V3_set_ctx(&ext_ctx, CAcert != NULL ? CAcert : new_x509,
857 new_x509, NULL, NULL, X509V3_CTX_REPLACE);
858 if (CAcert == NULL) { /* self-issued, possibly self-signed */
859 if (!X509V3_set_issuer_pkey(&ext_ctx, pkey)) /* prepare right AKID */
860 goto end;
861 ERR_set_mark();
862 if (!X509_check_private_key(new_x509, pkey))
863 BIO_printf(bio_err,
864 "Warning: Signature key and public key of cert do not match\n");
865 ERR_pop_to_mark();
866 }
867 X509V3_set_nconf(&ext_ctx, req_conf);
868
869 /* Add extensions */
870 if (extensions != NULL
871 && !X509V3_EXT_add_nconf(req_conf, &ext_ctx, extensions,
872 new_x509)) {
873 BIO_printf(bio_err, "Error adding x509 extensions from section %s\n",
874 extensions);
875 goto end;
876 }
877 if (addext_conf != NULL
878 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
879 new_x509)) {
880 BIO_printf(bio_err, "Error adding extensions defined via -addext\n");
881 goto end;
882 }
883
884 /* If a pre-cert was requested, we need to add a poison extension */
885 if (precert) {
886 if (X509_add1_ext_i2d(new_x509, NID_ct_precert_poison,
887 NULL, 1, 0) != 1) {
888 BIO_printf(bio_err, "Error adding poison extension\n");
889 goto end;
890 }
891 }
892
893 i = do_X509_sign(new_x509, CAcert != NULL ? CAkey : pkey,
894 digest, sigopts, &ext_ctx);
895 if (!i)
896 goto end;
897 } else {
898 X509V3_CTX ext_ctx;
899
900 /* Set up V3 context struct */
901 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
902 X509V3_set_nconf(&ext_ctx, req_conf);
903
904 /* Add extensions */
905 if (req_exts != NULL
906 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
907 req_exts, req)) {
908 BIO_printf(bio_err, "Error adding request extensions from section %s\n",
909 req_exts);
910 goto end;
911 }
912 if (addext_conf != NULL
913 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
914 req)) {
915 BIO_printf(bio_err, "Error adding extensions defined via -addext\n");
916 goto end;
917 }
918 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
919 if (!i)
920 goto end;
921 }
922 }
923
924 if (subj != NULL && !newreq && !gen_x509) {
925 if (verbose) {
926 BIO_printf(out, "Modifying subject of certificate request\n");
927 print_name(out, "Old subject=", X509_REQ_get_subject_name(req));
928 }
929
930 if (!X509_REQ_set_subject_name(req, fsubj)) {
931 BIO_printf(bio_err, "Error modifying subject of certificate request\n");
932 goto end;
933 }
934
935 if (verbose) {
936 print_name(out, "New subject=", X509_REQ_get_subject_name(req));
937 }
938 }
939
940 if (verify) {
941 EVP_PKEY *tpubkey = pkey;
942
943 if (tpubkey == NULL) {
944 tpubkey = X509_REQ_get0_pubkey(req);
945 if (tpubkey == NULL)
946 goto end;
947 }
948
949 i = do_X509_REQ_verify(req, tpubkey, vfyopts);
950
951 if (i < 0) {
952 goto end;
953 } else if (i == 0) {
954 BIO_printf(bio_err, "Certificate request self-signature verify failure\n");
955 ERR_print_errors(bio_err);
956 } else { /* i > 0 */
957 BIO_printf(bio_err, "Certificate request self-signature verify OK\n");
958 }
959 }
960
961 if (noout && !text && !modulus && !subject && !pubkey) {
962 ret = 0;
963 goto end;
964 }
965
966 out = bio_open_default(outfile,
967 keyout != NULL && outfile != NULL &&
968 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
969 outformat);
970 if (out == NULL)
971 goto end;
972
973 if (pubkey) {
974 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
975
976 if (tpubkey == NULL) {
977 BIO_printf(bio_err, "Error getting public key\n");
978 goto end;
979 }
980 PEM_write_bio_PUBKEY(out, tpubkey);
981 }
982
983 if (text) {
984 if (gen_x509)
985 ret = X509_print_ex(out, new_x509, get_nameopt(), reqflag);
986 else
987 ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
988
989 if (ret == 0) {
990 if (gen_x509)
991 BIO_printf(bio_err, "Error printing certificate\n");
992 else
993 BIO_printf(bio_err, "Error printing certificate request\n");
994 goto end;
995 }
996 }
997
998 if (subject) {
999 print_name(out, "subject=", gen_x509
1000 ? X509_get_subject_name(new_x509)
1001 : X509_REQ_get_subject_name(req));
1002 }
1003
1004 if (modulus) {
1005 EVP_PKEY *tpubkey;
1006
1007 if (gen_x509)
1008 tpubkey = X509_get0_pubkey(new_x509);
1009 else
1010 tpubkey = X509_REQ_get0_pubkey(req);
1011 if (tpubkey == NULL) {
1012 fprintf(stdout, "Modulus is unavailable\n");
1013 goto end;
1014 }
1015 fprintf(stdout, "Modulus=");
1016 if (EVP_PKEY_is_a(tpubkey, "RSA")) {
1017 BIGNUM *n;
1018
1019 /* Every RSA key has an 'n' */
1020 EVP_PKEY_get_bn_param(pkey, "n", &n);
1021 BN_print(out, n);
1022 BN_free(n);
1023 } else {
1024 fprintf(stdout, "Wrong Algorithm type");
1025 }
1026 fprintf(stdout, "\n");
1027 }
1028
1029 if (!noout && !gen_x509) {
1030 if (outformat == FORMAT_ASN1)
1031 i = i2d_X509_REQ_bio(out, req);
1032 else if (newhdr)
1033 i = PEM_write_bio_X509_REQ_NEW(out, req);
1034 else
1035 i = PEM_write_bio_X509_REQ(out, req);
1036 if (!i) {
1037 BIO_printf(bio_err, "Unable to write certificate request\n");
1038 goto end;
1039 }
1040 }
1041 if (!noout && gen_x509 && new_x509 != NULL) {
1042 if (outformat == FORMAT_ASN1)
1043 i = i2d_X509_bio(out, new_x509);
1044 else
1045 i = PEM_write_bio_X509(out, new_x509);
1046 if (!i) {
1047 BIO_printf(bio_err, "Unable to write X509 certificate\n");
1048 goto end;
1049 }
1050 }
1051 ret = 0;
1052 end:
1053 if (ret) {
1054 ERR_print_errors(bio_err);
1055 }
1056 NCONF_free(req_conf);
1057 NCONF_free(addext_conf);
1058 BIO_free(addext_bio);
1059 BIO_free_all(out);
1060 EVP_PKEY_free(pkey);
1061 EVP_PKEY_CTX_free(genctx);
1062 sk_OPENSSL_STRING_free(pkeyopts);
1063 sk_OPENSSL_STRING_free(sigopts);
1064 sk_OPENSSL_STRING_free(vfyopts);
1065 lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
1066 lh_OPENSSL_STRING_free(addexts);
1067 #ifndef OPENSSL_NO_ENGINE
1068 release_engine(gen_eng);
1069 #endif
1070 OPENSSL_free(keyalgstr);
1071 X509_REQ_free(req);
1072 X509_NAME_free(fsubj);
1073 X509_free(new_x509);
1074 X509_free(CAcert);
1075 EVP_PKEY_free(CAkey);
1076 ASN1_INTEGER_free(serial);
1077 release_engine(e);
1078 if (passin != nofree_passin)
1079 OPENSSL_free(passin);
1080 if (passout != nofree_passout)
1081 OPENSSL_free(passout);
1082 return ret;
1083 }
1084
1085 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj,
1086 int multirdn, int attribs, unsigned long chtype)
1087 {
1088 int ret = 0, i;
1089 char no_prompt = 0;
1090 STACK_OF(CONF_VALUE) *dn_sk = NULL, *attr_sk = NULL;
1091 char *tmp, *dn_sect, *attr_sect;
1092
1093 tmp = NCONF_get_string(req_conf, section, PROMPT);
1094 if (tmp == NULL)
1095 ERR_clear_error();
1096 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1097 no_prompt = 1;
1098
1099 dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
1100 if (dn_sect == NULL) {
1101 ERR_clear_error();
1102 } else {
1103 dn_sk = NCONF_get_section(req_conf, dn_sect);
1104 if (dn_sk == NULL) {
1105 BIO_printf(bio_err, "Unable to get '%s' section\n", dn_sect);
1106 goto err;
1107 }
1108 }
1109
1110 attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
1111 if (attr_sect == NULL) {
1112 ERR_clear_error();
1113 } else {
1114 attr_sk = NCONF_get_section(req_conf, attr_sect);
1115 if (attr_sk == NULL) {
1116 BIO_printf(bio_err, "Unable to get '%s' section\n", attr_sect);
1117 goto err;
1118 }
1119 }
1120
1121 if (!X509_REQ_set_version(req, 0L)) /* so far there is only version 1 */
1122 goto err;
1123
1124 if (fsubj != NULL)
1125 i = X509_REQ_set_subject_name(req, fsubj);
1126 else if (no_prompt)
1127 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1128 else
1129 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1130 chtype);
1131 if (!i)
1132 goto err;
1133
1134 if (!X509_REQ_set_pubkey(req, pkey))
1135 goto err;
1136
1137 ret = 1;
1138 err:
1139 return ret;
1140 }
1141
1142 static int prompt_info(X509_REQ *req,
1143 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1144 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1145 int attribs, unsigned long chtype)
1146 {
1147 int i;
1148 char *p, *q;
1149 char buf[100];
1150 int nid, mval;
1151 long n_min, n_max;
1152 char *type, *value;
1153 const char *def;
1154 CONF_VALUE *v;
1155 X509_NAME *subj = X509_REQ_get_subject_name(req);
1156
1157 if (!batch) {
1158 BIO_printf(bio_err,
1159 "You are about to be asked to enter information that will be incorporated\n");
1160 BIO_printf(bio_err, "into your certificate request.\n");
1161 BIO_printf(bio_err,
1162 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1163 BIO_printf(bio_err,
1164 "There are quite a few fields but you can leave some blank\n");
1165 BIO_printf(bio_err,
1166 "For some fields there will be a default value,\n");
1167 BIO_printf(bio_err,
1168 "If you enter '.', the field will be left blank.\n");
1169 BIO_printf(bio_err, "-----\n");
1170 }
1171
1172 if (sk_CONF_VALUE_num(dn_sk)) {
1173 i = -1;
1174 start:
1175 for (;;) {
1176 i++;
1177 if (sk_CONF_VALUE_num(dn_sk) <= i)
1178 break;
1179
1180 v = sk_CONF_VALUE_value(dn_sk, i);
1181 p = q = NULL;
1182 type = v->name;
1183 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1184 !check_end(type, "_default") || !check_end(type, "_value"))
1185 continue;
1186 /*
1187 * Skip past any leading X. X: X, etc to allow for multiple
1188 * instances
1189 */
1190 for (p = v->name; *p; p++)
1191 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1192 p++;
1193 if (*p)
1194 type = p;
1195 break;
1196 }
1197 if (*type == '+') {
1198 mval = -1;
1199 type++;
1200 } else {
1201 mval = 0;
1202 }
1203 /* If OBJ not recognised ignore it */
1204 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1205 goto start;
1206 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1207 return 0;
1208 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1209 ERR_clear_error();
1210 def = "";
1211 }
1212
1213 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1214 return 0;
1215 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1216 ERR_clear_error();
1217 value = NULL;
1218 }
1219
1220 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1221 return 0;
1222 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1223 ERR_clear_error();
1224 n_min = -1;
1225 }
1226
1227 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1228 return 0;
1229 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1230 ERR_clear_error();
1231 n_max = -1;
1232 }
1233
1234 if (!add_DN_object(subj, v->value, def, value, nid,
1235 n_min, n_max, chtype, mval))
1236 return 0;
1237 }
1238 if (X509_NAME_entry_count(subj) == 0) {
1239 BIO_printf(bio_err, "Error: No objects specified in config file\n");
1240 return 0;
1241 }
1242
1243 if (attribs) {
1244 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1245 && (!batch)) {
1246 BIO_printf(bio_err,
1247 "\nPlease enter the following 'extra' attributes\n");
1248 BIO_printf(bio_err,
1249 "to be sent with your certificate request\n");
1250 }
1251
1252 i = -1;
1253 start2:
1254 for (;;) {
1255 i++;
1256 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1257 break;
1258
1259 v = sk_CONF_VALUE_value(attr_sk, i);
1260 type = v->name;
1261 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1262 goto start2;
1263
1264 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1265 return 0;
1266 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1267 == NULL) {
1268 ERR_clear_error();
1269 def = "";
1270 }
1271
1272 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1273 return 0;
1274 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1275 == NULL) {
1276 ERR_clear_error();
1277 value = NULL;
1278 }
1279
1280 if (!join(buf, sizeof(buf), type, "_min", "Name"))
1281 return 0;
1282 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1283 ERR_clear_error();
1284 n_min = -1;
1285 }
1286
1287 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1288 return 0;
1289 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1290 ERR_clear_error();
1291 n_max = -1;
1292 }
1293
1294 if (!add_attribute_object(req,
1295 v->value, def, value, nid, n_min,
1296 n_max, chtype))
1297 return 0;
1298 }
1299 }
1300 } else {
1301 BIO_printf(bio_err, "No template, please set one up.\n");
1302 return 0;
1303 }
1304
1305 return 1;
1306
1307 }
1308
1309 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1310 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1311 unsigned long chtype)
1312 {
1313 int i, spec_char, plus_char;
1314 char *p, *q;
1315 char *type;
1316 CONF_VALUE *v;
1317 X509_NAME *subj;
1318
1319 subj = X509_REQ_get_subject_name(req);
1320
1321 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1322 int mval;
1323 v = sk_CONF_VALUE_value(dn_sk, i);
1324 p = q = NULL;
1325 type = v->name;
1326 /*
1327 * Skip past any leading X. X: X, etc to allow for multiple instances
1328 */
1329 for (p = v->name; *p; p++) {
1330 #ifndef CHARSET_EBCDIC
1331 spec_char = (*p == ':' || *p == ',' || *p == '.');
1332 #else
1333 spec_char = (*p == os_toascii[':'] || *p == os_toascii[',']
1334 || *p == os_toascii['.']);
1335 #endif
1336 if (spec_char) {
1337 p++;
1338 if (*p)
1339 type = p;
1340 break;
1341 }
1342 }
1343 #ifndef CHARSET_EBCDIC
1344 plus_char = (*type == '+');
1345 #else
1346 plus_char = (*type == os_toascii['+']);
1347 #endif
1348 if (plus_char) {
1349 type++;
1350 mval = -1;
1351 } else {
1352 mval = 0;
1353 }
1354 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1355 (unsigned char *)v->value, -1, -1,
1356 mval))
1357 return 0;
1358
1359 }
1360
1361 if (!X509_NAME_entry_count(subj)) {
1362 BIO_printf(bio_err, "Error: No objects specified in config file\n");
1363 return 0;
1364 }
1365 if (attribs) {
1366 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1367 v = sk_CONF_VALUE_value(attr_sk, i);
1368 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1369 (unsigned char *)v->value, -1))
1370 return 0;
1371 }
1372 }
1373 return 1;
1374 }
1375
1376 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1377 char *value, int nid, int n_min, int n_max,
1378 unsigned long chtype, int mval)
1379 {
1380 int ret = 0;
1381 char buf[1024];
1382
1383 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1384 "DN value", "DN default");
1385 if ((ret == 0) || (ret == 1))
1386 return ret;
1387 ret = 1;
1388
1389 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1390 (unsigned char *)buf, -1, -1, mval))
1391 ret = 0;
1392
1393 return ret;
1394 }
1395
1396 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1397 char *value, int nid, int n_min,
1398 int n_max, unsigned long chtype)
1399 {
1400 int ret = 0;
1401 char buf[1024];
1402
1403 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1404 "Attribute value", "Attribute default");
1405 if ((ret == 0) || (ret == 1))
1406 return ret;
1407 ret = 1;
1408
1409 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1410 (unsigned char *)buf, -1)) {
1411 BIO_printf(bio_err, "Error adding attribute\n");
1412 ERR_print_errors(bio_err);
1413 ret = 0;
1414 }
1415
1416 return ret;
1417 }
1418
1419 static int build_data(char *text, const char *def, char *value,
1420 int n_min, int n_max, char *buf, const int buf_size,
1421 const char *desc1, const char *desc2)
1422 {
1423 int i;
1424 start:
1425 if (!batch)
1426 BIO_printf(bio_err, "%s [%s]:", text, def);
1427 (void)BIO_flush(bio_err);
1428 if (value != NULL) {
1429 if (!join(buf, buf_size, value, "\n", desc1))
1430 return 0;
1431 BIO_printf(bio_err, "%s\n", value);
1432 } else {
1433 buf[0] = '\0';
1434 if (!batch) {
1435 if (!fgets(buf, buf_size, stdin))
1436 return 0;
1437 } else {
1438 buf[0] = '\n';
1439 buf[1] = '\0';
1440 }
1441 }
1442
1443 if (buf[0] == '\0')
1444 return 0;
1445 if (buf[0] == '\n') {
1446 if ((def == NULL) || (def[0] == '\0'))
1447 return 1;
1448 if (!join(buf, buf_size, def, "\n", desc2))
1449 return 0;
1450 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1451 return 1;
1452 }
1453
1454 i = strlen(buf);
1455 if (buf[i - 1] != '\n') {
1456 BIO_printf(bio_err, "Missing newline at end of input\n");
1457 return 0;
1458 }
1459 buf[--i] = '\0';
1460 #ifdef CHARSET_EBCDIC
1461 ebcdic2ascii(buf, buf, i);
1462 #endif
1463 if (!req_check_len(i, n_min, n_max)) {
1464 if (batch || value)
1465 return 0;
1466 goto start;
1467 }
1468 return 2;
1469 }
1470
1471 static int req_check_len(int len, int n_min, int n_max)
1472 {
1473 if (n_min > 0 && len < n_min) {
1474 BIO_printf(bio_err,
1475 "String too short, must be at least %d bytes long\n", n_min);
1476 return 0;
1477 }
1478 if (n_max >= 0 && len > n_max) {
1479 BIO_printf(bio_err,
1480 "String too long, must be at most %d bytes long\n", n_max);
1481 return 0;
1482 }
1483 return 1;
1484 }
1485
1486 /* Check if the end of a string matches 'end' */
1487 static int check_end(const char *str, const char *end)
1488 {
1489 size_t elen, slen;
1490 const char *tmp;
1491
1492 elen = strlen(end);
1493 slen = strlen(str);
1494 if (elen > slen)
1495 return 1;
1496 tmp = str + slen - elen;
1497 return strcmp(tmp, end);
1498 }
1499
1500 /*
1501 * Merge the two strings together into the result buffer checking for
1502 * overflow and producing an error message if there is.
1503 */
1504 static int join(char buf[], size_t buf_size, const char *name,
1505 const char *tail, const char *desc)
1506 {
1507 const size_t name_len = strlen(name), tail_len = strlen(tail);
1508
1509 if (name_len + tail_len + 1 > buf_size) {
1510 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1511 return 0;
1512 }
1513 memcpy(buf, name, name_len);
1514 memcpy(buf + name_len, tail, tail_len + 1);
1515 return 1;
1516 }
1517
1518 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1519 int *pkey_type, long *pkeylen,
1520 char **palgnam, ENGINE *keygen_engine)
1521 {
1522 EVP_PKEY_CTX *gctx = NULL;
1523 EVP_PKEY *param = NULL;
1524 long keylen = -1;
1525 BIO *pbio = NULL;
1526 const char *paramfile = NULL;
1527
1528 if (gstr == NULL) {
1529 *pkey_type = EVP_PKEY_RSA;
1530 keylen = *pkeylen;
1531 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1532 *pkey_type = EVP_PKEY_RSA;
1533 keylen = atol(gstr);
1534 *pkeylen = keylen;
1535 } else if (strncmp(gstr, "param:", 6) == 0) {
1536 paramfile = gstr + 6;
1537 } else {
1538 const char *p = strchr(gstr, ':');
1539 int len;
1540 ENGINE *tmpeng;
1541 const EVP_PKEY_ASN1_METHOD *ameth;
1542
1543 if (p != NULL)
1544 len = p - gstr;
1545 else
1546 len = strlen(gstr);
1547 /*
1548 * The lookup of a the string will cover all engines so keep a note
1549 * of the implementation.
1550 */
1551
1552 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1553
1554 if (ameth == NULL) {
1555 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1556 return NULL;
1557 }
1558
1559 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1560 #ifndef OPENSSL_NO_ENGINE
1561 finish_engine(tmpeng);
1562 #endif
1563 if (*pkey_type == EVP_PKEY_RSA) {
1564 if (p != NULL) {
1565 keylen = atol(p + 1);
1566 *pkeylen = keylen;
1567 } else {
1568 keylen = *pkeylen;
1569 }
1570 } else if (p != NULL) {
1571 paramfile = p + 1;
1572 }
1573 }
1574
1575 if (paramfile != NULL) {
1576 pbio = BIO_new_file(paramfile, "r");
1577 if (pbio == NULL) {
1578 BIO_printf(bio_err, "Cannot open parameter file %s\n", paramfile);
1579 return NULL;
1580 }
1581 param = PEM_read_bio_Parameters(pbio, NULL);
1582
1583 if (param == NULL) {
1584 X509 *x;
1585
1586 (void)BIO_reset(pbio);
1587 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1588 if (x != NULL) {
1589 param = X509_get_pubkey(x);
1590 X509_free(x);
1591 }
1592 }
1593
1594 BIO_free(pbio);
1595
1596 if (param == NULL) {
1597 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1598 return NULL;
1599 }
1600 if (*pkey_type == -1) {
1601 *pkey_type = EVP_PKEY_id(param);
1602 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1603 BIO_printf(bio_err, "Key type does not match parameters\n");
1604 EVP_PKEY_free(param);
1605 return NULL;
1606 }
1607 }
1608
1609 if (palgnam != NULL) {
1610 const EVP_PKEY_ASN1_METHOD *ameth;
1611 ENGINE *tmpeng;
1612 const char *anam;
1613
1614 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1615 if (ameth == NULL) {
1616 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1617 return NULL;
1618 }
1619 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1620 *palgnam = OPENSSL_strdup(anam);
1621 #ifndef OPENSSL_NO_ENGINE
1622 finish_engine(tmpeng);
1623 #endif
1624 }
1625
1626 if (param != NULL) {
1627 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1628 *pkeylen = EVP_PKEY_bits(param);
1629 EVP_PKEY_free(param);
1630 } else {
1631 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1632 }
1633
1634 if (gctx == NULL) {
1635 BIO_puts(bio_err, "Error allocating keygen context\n");
1636 return NULL;
1637 }
1638
1639 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1640 BIO_puts(bio_err, "Error initializing keygen context\n");
1641 EVP_PKEY_CTX_free(gctx);
1642 return NULL;
1643 }
1644 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1645 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1646 BIO_puts(bio_err, "Error setting RSA keysize\n");
1647 EVP_PKEY_CTX_free(gctx);
1648 return NULL;
1649 }
1650 }
1651
1652 return gctx;
1653 }
1654
1655 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1656 {
1657 char c = '*';
1658 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1659 int p;
1660 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1661 if (p == 0)
1662 c = '.';
1663 if (p == 1)
1664 c = '+';
1665 if (p == 2)
1666 c = '*';
1667 if (p == 3)
1668 c = '\n';
1669 BIO_write(b, &c, 1);
1670 (void)BIO_flush(b);
1671 return 1;
1672 }