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