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