2 * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
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
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>
34 #define BITS "default_bits"
35 #define KEYFILE "default_keyfile"
36 #define PROMPT "prompt"
37 #define DISTINGUISHED_NAME "distinguished_name"
38 #define ATTRIBUTES "attributes"
39 #define V3_EXTENSIONS "x509_extensions"
40 #define REQ_EXTENSIONS "req_extensions"
41 #define STRING_MASK "string_mask"
42 #define UTF8_IN "utf8"
44 #define DEFAULT_KEY_LENGTH 2048
45 #define MIN_KEY_LENGTH 512
46 #define DEFAULT_DAYS 30 /* default cert validity period in days */
47 #define UNSET_DAYS -2 /* -1 may be used for testing expiration checks */
48 #define EXT_COPY_UNSET -1
50 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj,
51 int mutlirdn, int attribs, unsigned long chtype);
52 static int prompt_info(X509_REQ *req,
53 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
54 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
55 int attribs, unsigned long chtype);
56 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
57 STACK_OF(CONF_VALUE) *attr, int attribs,
58 unsigned long chtype);
59 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
60 char *value, int nid, int n_min, int n_max,
61 unsigned long chtype);
62 static int add_DN_object(X509_NAME *n, char *text, const char *def,
63 char *value, int nid, int n_min, int n_max,
64 unsigned long chtype, int mval);
65 static int build_data(char *text, const char *def, char *value,
66 int n_min, int n_max, char *buf, const int buf_size,
67 const char *desc1, const char *desc2);
68 static int req_check_len(int len, int n_min, int n_max);
69 static int check_end(const char *str, const char *end);
70 static int join(char buf[], size_t buf_size, const char *name,
71 const char *tail, const char *desc);
72 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
73 char **pkeytype, long *pkeylen,
74 ENGINE *keygen_engine);
76 static const char *section = "req";
77 static CONF *req_conf = NULL;
78 static CONF *addext_conf = NULL;
81 typedef enum OPTION_choice {
83 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
84 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
85 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
86 OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
87 OPT_VERIFY, OPT_NOENC, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
88 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT,
89 OPT_X509, OPT_X509V1, OPT_CA, OPT_CAKEY,
90 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL,
91 OPT_COPY_EXTENSIONS, OPT_EXTENSIONS, OPT_REQEXTS, OPT_ADDEXT,
93 OPT_SECTION, OPT_QUIET,
94 OPT_R_ENUM, OPT_PROV_ENUM
97 const OPTIONS req_options[] = {
98 OPT_SECTION("General"),
99 {"help", OPT_HELP, '-', "Display this summary"},
100 #ifndef OPENSSL_NO_ENGINE
101 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
102 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
103 "Specify engine to be used for key generation operations"},
105 {"in", OPT_IN, '<', "X.509 request input file (default stdin)"},
106 {"inform", OPT_INFORM, 'F',
107 "CSR input format to use (PEM or DER; by default try PEM first)"},
108 {"verify", OPT_VERIFY, '-', "Verify self-signature on the request"},
110 OPT_SECTION("Certificate"),
111 {"new", OPT_NEW, '-', "New request"},
112 {"config", OPT_CONFIG, '<', "Request template file"},
113 {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
114 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
115 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
116 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
117 {"text", OPT_TEXT, '-', "Text form of request"},
118 {"x509", OPT_X509, '-',
119 "Output an X.509 certificate structure instead of a cert request"},
120 {"x509v1", OPT_X509V1, '-', "Request cert generation with X.509 version 1"},
121 {"CA", OPT_CA, '<', "Issuer cert to use for signing a cert, implies -x509"},
122 {"CAkey", OPT_CAKEY, 's',
123 "Issuer private key to use with -CA; default is -CA arg"},
124 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
125 {"subj", OPT_SUBJ, 's', "Set or modify subject of request or cert"},
126 {"subject", OPT_SUBJECT, '-',
127 "Print the subject of the output request or cert"},
128 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
129 "Deprecated; multi-valued RDNs support is always on."},
130 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
131 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
132 {"copy_extensions", OPT_COPY_EXTENSIONS, 's',
133 "copy extensions from request when using -x509"},
134 {"extensions", OPT_EXTENSIONS, 's',
135 "Cert or request extension section (override value in config file)"},
136 {"reqexts", OPT_REQEXTS, 's', "An alias for -extensions"},
137 {"addext", OPT_ADDEXT, 's',
138 "Additional cert extension key=value pair (may be given more than once)"},
139 {"precert", OPT_PRECERT, '-', "Add a poison extension to generated cert (implies -new)"},
141 OPT_SECTION("Keys and Signing"),
142 {"key", OPT_KEY, 's', "Key for signing, and to include unless -in given"},
143 {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"},
144 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
145 {"keyout", OPT_KEYOUT, '>', "File to write private key to"},
146 {"passin", OPT_PASSIN, 's', "Private key and certificate password source"},
147 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
148 {"newkey", OPT_NEWKEY, 's',
149 "Generate new key with [<alg>:]<nbits> or <alg>[:<file>] or param:<file>"},
150 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
151 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
152 {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
153 {"", OPT_MD, '-', "Any supported digest"},
155 OPT_SECTION("Output"),
156 {"out", OPT_OUT, '>', "Output file"},
157 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
158 {"batch", OPT_BATCH, '-',
159 "Do not ask anything during request generation"},
160 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
161 {"quiet", OPT_QUIET, '-', "Terse output"},
162 {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"},
163 {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"},
164 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
165 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
166 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
174 * An LHASH of strings, where each string is an extension name.
176 static unsigned long ext_name_hash(const OPENSSL_STRING *a)
178 return OPENSSL_LH_strhash((const char *)a);
181 static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
183 return strcmp((const char *)a, (const char *)b);
186 static void exts_cleanup(OPENSSL_STRING *x)
188 OPENSSL_free((char *)x);
192 * Is the |kv| key already duplicated?
193 * Return 0 if unique, -1 on runtime error, -2 on syntax error; 1 if found.
195 static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
201 /* Skip leading whitespace, make a copy. */
202 while (isspace(_UC(*kv)))
204 if ((p = strchr(kv, '=')) == NULL) {
205 BIO_printf(bio_err, "Parse error on -addext: missing '='\n");
209 if ((kv = OPENSSL_strdup(kv)) == NULL)
212 /* Skip trailing space before the equal sign. */
213 for (p = kv + off; p > kv; --p)
214 if (!isspace(_UC(p[-1])))
217 BIO_printf(bio_err, "Parse error on -addext: missing key\n");
223 /* Finally have a clean "key"; see if it's there [by attempt to add it]. */
224 p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING *)kv);
226 BIO_printf(bio_err, "Duplicate extension name: %s\n", kv);
229 } else if (lh_OPENSSL_STRING_error(addexts)) {
237 int req_main(int argc, char **argv)
239 ASN1_INTEGER *serial = NULL;
241 ENGINE *e = NULL, *gen_eng = NULL;
242 EVP_PKEY *pkey = NULL, *CAkey = NULL;
243 EVP_PKEY_CTX *genctx = NULL;
244 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL, *vfyopts = NULL;
245 LHASH_OF(OPENSSL_STRING) *addexts = NULL;
246 X509 *new_x509 = NULL, *CAcert = NULL;
247 X509_REQ *req = NULL;
248 EVP_CIPHER *cipher = NULL;
249 int ext_copy = EXT_COPY_UNSET;
250 BIO *addext_bio = NULL;
251 char *extsect = NULL;
252 const char *infile = NULL, *CAfile = NULL, *CAkeyfile = NULL;
253 char *outfile = NULL, *keyfile = NULL, *digest = NULL;
254 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
255 char *passin = NULL, *passout = NULL;
256 char *nofree_passin = NULL, *nofree_passout = NULL;
258 X509_NAME *fsubj = NULL;
259 char *template = default_config_file, *keyout = NULL;
260 const char *keyalg = NULL;
262 int days = UNSET_DAYS;
263 int ret = 1, gen_x509 = 0, i = 0, newreq = 0, verbose = 0, progress = 1;
264 int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyform = FORMAT_UNDEF;
265 int modulus = 0, multirdn = 1, verify = 0, noout = 0, text = 0;
266 int noenc = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0, x509v1 = 0;
267 long newkey_len = -1;
268 unsigned long chtype = MBSTRING_ASC, reqflag = 0;
270 #ifndef OPENSSL_NO_DES
271 cipher = (EVP_CIPHER *)EVP_des_ede3_cbc();
274 opt_set_unknown_name("digest");
275 prog = opt_init(argc, argv, req_options);
276 while ((o = opt_next()) != OPT_EOF) {
281 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
284 opt_help(req_options);
288 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
292 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
296 e = setup_engine(opt_arg(), 0);
298 case OPT_KEYGEN_ENGINE:
299 #ifndef OPENSSL_NO_ENGINE
300 gen_eng = setup_engine(opt_arg(), 0);
301 if (gen_eng == NULL) {
302 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
317 template = opt_arg();
323 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
336 passargin = opt_arg();
339 passargout = opt_arg();
346 if (!opt_provider(o))
354 if (pkeyopts == NULL)
355 pkeyopts = sk_OPENSSL_STRING_new_null();
357 || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
362 sigopts = sk_OPENSSL_STRING_new_null();
363 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
368 vfyopts = sk_OPENSSL_STRING_new_null();
369 if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
400 chtype = MBSTRING_UTF8;
403 if (!set_nameopt(opt_arg()))
407 if (!set_cert_ex(&reqflag, opt_arg()))
424 CAkeyfile = opt_arg();
427 days = atoi(opt_arg());
429 BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n",
435 if (serial != NULL) {
436 BIO_printf(bio_err, "Serial number supplied twice\n");
439 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
449 case OPT_MULTIVALUE_RDN:
452 case OPT_COPY_EXTENSIONS:
453 if (!set_ext_copy(&ext_copy, opt_arg())) {
454 BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n",
465 if (addexts == NULL) {
466 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
467 addext_bio = BIO_new(BIO_s_mem());
468 if (addexts == NULL || addext_bio == NULL)
471 i = duplicated(addexts, p);
475 BIO_printf(bio_err, "Internal error handling -addext %s\n", p);
476 if (i < 0 || BIO_printf(addext_bio, "%s\n", p) < 0)
480 newreq = precert = 1;
483 digest = opt_unknown();
488 /* No extra arguments. */
489 if (!opt_check_rest_arg(NULL))
492 if (!app_RAND_load())
496 if (days != UNSET_DAYS)
497 BIO_printf(bio_err, "Ignoring -days without -x509; not generating a certificate\n");
498 if (ext_copy == EXT_COPY_NONE)
499 BIO_printf(bio_err, "Ignoring -copy_extensions 'none' when -x509 is not given\n");
501 if (infile == NULL) {
506 "Warning: Will read cert request from stdin since no -in option is given\n");
509 if (!app_passwd(passargin, passargout, &passin, &passout)) {
510 BIO_printf(bio_err, "Error getting passwords\n");
514 if ((req_conf = app_load_config_verbose(template, verbose)) == NULL)
516 if (addext_bio != NULL) {
519 "Using additional configuration from -addext options\n");
520 if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
523 if (template != default_config_file && !app_load_modules(req_conf))
526 if (req_conf != NULL) {
527 p = app_conf_try_string(req_conf, NULL, "oid_file");
529 BIO *oid_bio = BIO_new_file(p, "r");
531 if (oid_bio == NULL) {
534 "Problems opening '%s' for extra OIDs\n", p);
536 OBJ_create_objects(oid_bio);
541 if (!add_oid_section(req_conf))
544 /* Check that any specified digest is fetchable */
545 if (digest != NULL) {
546 if (!opt_check_md(digest))
549 /* No digest specified, default to configuration */
550 p = app_conf_try_string(req_conf, section, "default_md");
556 extsect = app_conf_try_string(req_conf, section,
557 gen_x509 ? V3_EXTENSIONS : REQ_EXTENSIONS);
558 if (extsect != NULL) {
559 /* Check syntax of extension section in config file */
562 X509V3_set_ctx_test(&ctx);
563 X509V3_set_nconf(&ctx, req_conf);
564 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extsect, NULL)) {
566 "Error checking %s extension section %s\n",
567 gen_x509 ? "x509" : "request", extsect);
571 if (addext_conf != NULL) {
572 /* Check syntax of command line extensions */
575 X509V3_set_ctx_test(&ctx);
576 X509V3_set_nconf(&ctx, req_conf);
577 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
578 BIO_printf(bio_err, "Error checking extensions defined using -addext\n");
584 passin = nofree_passin =
585 app_conf_try_string(req_conf, section, "input_password");
588 passout = nofree_passout =
589 app_conf_try_string(req_conf, section, "output_password");
591 p = app_conf_try_string(req_conf, section, STRING_MASK);
592 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
593 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
597 if (chtype != MBSTRING_UTF8) {
598 p = app_conf_try_string(req_conf, section, UTF8_IN);
599 if (p != NULL && strcmp(p, "yes") == 0)
600 chtype = MBSTRING_UTF8;
603 if (keyfile != NULL) {
604 pkey = load_key(keyfile, keyform, 0, passin, e, "private key");
607 app_RAND_load_conf(req_conf, section);
609 if (keyalg != NULL && pkey != NULL) {
611 "Warning: Not generating key via given -newkey option since -key is given\n");
612 /* Better throw an error in this case */
614 if (newreq && pkey == NULL) {
615 app_RAND_load_conf(req_conf, section);
617 if (!app_conf_try_number(req_conf, section, BITS, &newkey_len))
618 newkey_len = DEFAULT_KEY_LENGTH;
620 genctx = set_keygen_ctx(keyalg, &keyalgstr, &newkey_len, gen_eng);
624 if (newkey_len < MIN_KEY_LENGTH
625 && (EVP_PKEY_CTX_is_a(genctx, "RSA")
626 || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS")
627 || EVP_PKEY_CTX_is_a(genctx, "DSA"))) {
628 BIO_printf(bio_err, "Private key length too short, needs to be at least %d bits, not %ld.\n",
629 MIN_KEY_LENGTH, newkey_len);
633 if (newkey_len > OPENSSL_RSA_MAX_MODULUS_BITS
634 && (EVP_PKEY_CTX_is_a(genctx, "RSA")
635 || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS")))
637 "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
638 " Your key size is %ld! Larger key size may behave not as expected.\n",
639 OPENSSL_RSA_MAX_MODULUS_BITS, newkey_len);
641 #ifndef OPENSSL_NO_DSA
642 if (EVP_PKEY_CTX_is_a(genctx, "DSA")
643 && newkey_len > OPENSSL_DSA_MAX_MODULUS_BITS)
645 "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
646 " Your key size is %ld! Larger key size may behave not as expected.\n",
647 OPENSSL_DSA_MAX_MODULUS_BITS, newkey_len);
650 if (pkeyopts != NULL) {
652 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
653 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
654 if (pkey_ctrl_string(genctx, genopt) <= 0) {
655 BIO_printf(bio_err, "Key parameter error \"%s\"\n", genopt);
661 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
663 EVP_PKEY_CTX_set_cb(genctx, progress_cb);
665 pkey = app_keygen(genctx, keyalgstr, newkey_len, verbose);
669 EVP_PKEY_CTX_free(genctx);
672 if (keyout == NULL && keyfile == NULL)
673 keyout = app_conf_try_string(req_conf, section, KEYFILE);
675 if (pkey != NULL && (keyfile == NULL || keyout != NULL)) {
677 BIO_printf(bio_err, "Writing private key to ");
679 BIO_printf(bio_err, "stdout\n");
681 BIO_printf(bio_err, "'%s'\n", keyout);
683 out = bio_open_owner(keyout, outformat, newreq);
687 p = app_conf_try_string(req_conf, section, "encrypt_rsa_key");
689 p = app_conf_try_string(req_conf, section, "encrypt_key");
690 if (p != NULL && strcmp(p, "no") == 0)
697 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
698 NULL, 0, NULL, passout)) {
699 if ((ERR_GET_REASON(ERR_peek_error()) ==
700 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
709 BIO_printf(bio_err, "-----\n");
713 * subj is expected to be in the format /type0=value0/type1=value1/type2=...
714 * where characters may be escaped by \
717 && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL)
723 "Warning: Not placing -key in cert or request since request is used\n");
724 req = load_csr_autofmt(infile /* if NULL, reads from stdin */,
725 informat, vfyopts, "X509 request");
728 } else if (infile != NULL) {
730 "Warning: Ignoring -in option since -new or -newkey or -precert is given\n");
731 /* Better throw an error in this case, as done in the x509 app */
734 if (CAkeyfile == NULL)
736 if (CAkeyfile != NULL) {
737 if (CAfile == NULL) {
739 "Warning: Ignoring -CAkey option since no -CA option is given\n");
741 if ((CAkey = load_key(CAkeyfile, FORMAT_UNDEF,
744 ? "issuer private key from -CAkey arg"
745 : "issuer private key from -CA arg")) == NULL)
749 if (CAfile != NULL) {
750 if ((CAcert = load_cert_pass(CAfile, FORMAT_UNDEF, 1, passin,
751 "issuer cert from -CA arg")) == NULL)
753 if (!X509_check_private_key(CAcert, CAkey)) {
755 "Issuer CA certificate and key do not match\n");
759 if (newreq || gen_x509) {
760 if (CAcert == NULL && pkey == NULL) {
761 BIO_printf(bio_err, "Must provide a signature key using -key or"
762 " provide -CA / -CAkey\n");
767 req = X509_REQ_new_ex(app_get0_libctx(), app_get0_propq());
772 if (!make_REQ(req, pkey, fsubj, multirdn, !gen_x509, chtype)) {
773 BIO_printf(bio_err, "Error making certificate request\n");
776 /* Note that -x509 can take over -key and -subj option values. */
779 EVP_PKEY *pub_key = X509_REQ_get0_pubkey(req);
780 EVP_PKEY *issuer_key = CAcert != NULL ? CAkey : pkey;
782 X509_NAME *issuer = CAcert != NULL ? X509_get_subject_name(CAcert) :
783 X509_REQ_get_subject_name(req);
784 X509_NAME *n_subj = fsubj != NULL ? fsubj :
785 X509_REQ_get_subject_name(req);
787 if (CAcert != NULL && keyfile != NULL)
789 "Warning: Not using -key or -newkey for signing since -CA option is given\n");
791 if ((new_x509 = X509_new_ex(app_get0_libctx(),
792 app_get0_propq())) == NULL)
795 if (serial != NULL) {
796 if (!X509_set_serialNumber(new_x509, serial))
799 if (!rand_serial(NULL, X509_get_serialNumber(new_x509)))
803 if (!X509_set_issuer_name(new_x509, issuer))
805 if (days == UNSET_DAYS) {
808 if (!set_cert_times(new_x509, NULL, NULL, days))
810 if (!X509_set_subject_name(new_x509, n_subj))
812 if (!pub_key || !X509_set_pubkey(new_x509, pub_key))
814 if (ext_copy == EXT_COPY_UNSET) {
816 BIO_printf(bio_err, "Warning: No -copy_extensions given; ignoring any extensions in the request\n");
817 } else if (!copy_extensions(new_x509, req, ext_copy)) {
818 BIO_printf(bio_err, "Error copying extensions from request\n");
822 /* Set up V3 context struct */
823 X509V3_set_ctx(&ext_ctx, CAcert != NULL ? CAcert : new_x509,
824 new_x509, NULL, NULL, X509V3_CTX_REPLACE);
825 /* prepare fallback for AKID, but only if issuer cert == new_x509 */
826 if (CAcert == NULL) {
827 if (!X509V3_set_issuer_pkey(&ext_ctx, issuer_key))
829 if (!cert_matches_key(new_x509, issuer_key))
831 "Warning: Signature key and public key of cert do not match\n");
833 X509V3_set_nconf(&ext_ctx, req_conf);
837 && !X509V3_EXT_add_nconf(req_conf, &ext_ctx, extsect, new_x509)) {
838 BIO_printf(bio_err, "Error adding x509 extensions from section %s\n",
842 if (addext_conf != NULL
843 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
845 BIO_printf(bio_err, "Error adding x509 extensions defined via -addext\n");
849 /* If a pre-cert was requested, we need to add a poison extension */
851 if (X509_add1_ext_i2d(new_x509, NID_ct_precert_poison,
853 BIO_printf(bio_err, "Error adding poison extension\n");
858 i = do_X509_sign(new_x509, x509v1, issuer_key, digest, sigopts,
867 "Warning: Ignoring -precert flag since no cert is produced\n");
869 /* Set up V3 context struct */
870 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, X509V3_CTX_REPLACE);
871 X509V3_set_nconf(&ext_ctx, req_conf);
875 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx, extsect, req)) {
876 BIO_printf(bio_err, "Error adding request extensions from section %s\n",
880 if (addext_conf != NULL
881 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
883 BIO_printf(bio_err, "Error adding request extensions defined via -addext\n");
886 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
892 if (subj != NULL && !newreq && !gen_x509) {
894 BIO_printf(out, "Modifying subject of certificate request\n");
895 print_name(out, "Old subject=", X509_REQ_get_subject_name(req));
898 if (!X509_REQ_set_subject_name(req, fsubj)) {
899 BIO_printf(bio_err, "Error modifying subject of certificate request\n");
904 print_name(out, "New subject=", X509_REQ_get_subject_name(req));
909 EVP_PKEY *tpubkey = pkey;
911 if (tpubkey == NULL) {
912 tpubkey = X509_REQ_get0_pubkey(req);
917 i = do_X509_REQ_verify(req, tpubkey, vfyopts);
922 BIO_printf(bio_err, "Certificate request self-signature verify failure\n");
925 BIO_printf(bio_out, "Certificate request self-signature verify OK\n");
928 if (noout && !text && !modulus && !subject && !pubkey) {
933 out = bio_open_default(outfile,
934 keyout != NULL && outfile != NULL &&
935 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
941 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
943 if (tpubkey == NULL) {
944 BIO_printf(bio_err, "Error getting public key\n");
947 PEM_write_bio_PUBKEY(out, tpubkey);
952 ret = X509_print_ex(out, new_x509, get_nameopt(), reqflag);
954 ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
958 BIO_printf(bio_err, "Error printing certificate\n");
960 BIO_printf(bio_err, "Error printing certificate request\n");
966 print_name(out, "subject=", gen_x509
967 ? X509_get_subject_name(new_x509)
968 : X509_REQ_get_subject_name(req));
975 tpubkey = X509_get0_pubkey(new_x509);
977 tpubkey = X509_REQ_get0_pubkey(req);
978 if (tpubkey == NULL) {
979 BIO_puts(bio_err, "Modulus is unavailable\n");
982 BIO_puts(out, "Modulus=");
983 if (EVP_PKEY_is_a(tpubkey, "RSA") || EVP_PKEY_is_a(tpubkey, "RSA-PSS")) {
986 if (!EVP_PKEY_get_bn_param(tpubkey, "n", &n))
991 BIO_puts(out, "Wrong Algorithm type");
996 if (!noout && !gen_x509) {
997 if (outformat == FORMAT_ASN1)
998 i = i2d_X509_REQ_bio(out, req);
1000 i = PEM_write_bio_X509_REQ_NEW(out, req);
1002 i = PEM_write_bio_X509_REQ(out, req);
1004 BIO_printf(bio_err, "Unable to write certificate request\n");
1008 if (!noout && gen_x509 && new_x509 != NULL) {
1009 if (outformat == FORMAT_ASN1)
1010 i = i2d_X509_bio(out, new_x509);
1012 i = PEM_write_bio_X509(out, new_x509);
1014 BIO_printf(bio_err, "Unable to write X509 certificate\n");
1021 ERR_print_errors(bio_err);
1023 NCONF_free(req_conf);
1024 NCONF_free(addext_conf);
1025 BIO_free(addext_bio);
1027 EVP_PKEY_free(pkey);
1028 EVP_PKEY_CTX_free(genctx);
1029 sk_OPENSSL_STRING_free(pkeyopts);
1030 sk_OPENSSL_STRING_free(sigopts);
1031 sk_OPENSSL_STRING_free(vfyopts);
1032 lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
1033 lh_OPENSSL_STRING_free(addexts);
1034 #ifndef OPENSSL_NO_ENGINE
1035 release_engine(gen_eng);
1037 OPENSSL_free(keyalgstr);
1039 X509_NAME_free(fsubj);
1040 X509_free(new_x509);
1042 EVP_PKEY_free(CAkey);
1043 ASN1_INTEGER_free(serial);
1045 if (passin != nofree_passin)
1046 OPENSSL_free(passin);
1047 if (passout != nofree_passout)
1048 OPENSSL_free(passout);
1052 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj,
1053 int multirdn, int attribs, unsigned long chtype)
1057 STACK_OF(CONF_VALUE) *dn_sk = NULL, *attr_sk = NULL;
1058 char *tmp, *dn_sect, *attr_sect;
1060 tmp = app_conf_try_string(req_conf, section, PROMPT);
1061 if (tmp != NULL && strcmp(tmp, "no") == 0)
1064 dn_sect = app_conf_try_string(req_conf, section, DISTINGUISHED_NAME);
1065 if (dn_sect != NULL) {
1066 dn_sk = NCONF_get_section(req_conf, dn_sect);
1067 if (dn_sk == NULL) {
1068 BIO_printf(bio_err, "Unable to get '%s' section\n", dn_sect);
1073 attr_sect = app_conf_try_string(req_conf, section, ATTRIBUTES);
1074 if (attr_sect != NULL) {
1075 attr_sk = NCONF_get_section(req_conf, attr_sect);
1076 if (attr_sk == NULL) {
1077 BIO_printf(bio_err, "Unable to get '%s' section\n", attr_sect);
1082 /* so far there is only version 1 */
1083 if (!X509_REQ_set_version(req, X509_REQ_VERSION_1))
1087 i = X509_REQ_set_subject_name(req, fsubj);
1089 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1091 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1096 if (!X509_REQ_set_pubkey(req, pkey))
1104 static int prompt_info(X509_REQ *req,
1105 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1106 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1107 int attribs, unsigned long chtype)
1117 X509_NAME *subj = X509_REQ_get_subject_name(req);
1121 "You are about to be asked to enter information that will be incorporated\n");
1122 BIO_printf(bio_err, "into your certificate request.\n");
1124 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1126 "There are quite a few fields but you can leave some blank\n");
1128 "For some fields there will be a default value,\n");
1130 "If you enter '.', the field will be left blank.\n");
1131 BIO_printf(bio_err, "-----\n");
1134 if (sk_CONF_VALUE_num(dn_sk)) {
1139 if (sk_CONF_VALUE_num(dn_sk) <= i)
1142 v = sk_CONF_VALUE_value(dn_sk, i);
1145 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1146 !check_end(type, "_default") || !check_end(type, "_value"))
1149 * Skip past any leading X. X: X, etc to allow for multiple
1152 for (p = v->name; *p; p++)
1153 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1165 /* If OBJ not recognised ignore it */
1166 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1168 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1170 if ((def = app_conf_try_string(req_conf, dn_sect, buf)) == NULL)
1173 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1175 if ((value = app_conf_try_string(req_conf, dn_sect, buf)) == NULL)
1178 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1180 if (!app_conf_try_number(req_conf, dn_sect, buf, &n_min))
1183 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1185 if (!app_conf_try_number(req_conf, dn_sect, buf, &n_max))
1188 if (!add_DN_object(subj, v->value, def, value, nid,
1189 n_min, n_max, chtype, mval))
1192 if (X509_NAME_entry_count(subj) == 0) {
1193 BIO_printf(bio_err, "Error: No objects specified in config file\n");
1198 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1201 "\nPlease enter the following 'extra' attributes\n");
1203 "to be sent with your certificate request\n");
1210 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1213 v = sk_CONF_VALUE_value(attr_sk, i);
1215 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1218 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1220 def = app_conf_try_string(req_conf, attr_sect, buf);
1224 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1226 value = app_conf_try_string(req_conf, attr_sect, buf);
1228 if (!join(buf, sizeof(buf), type, "_min", "Name"))
1230 if (!app_conf_try_number(req_conf, attr_sect, buf, &n_min))
1233 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1235 if (!app_conf_try_number(req_conf, attr_sect, buf, &n_max))
1238 if (!add_attribute_object(req,
1239 v->value, def, value, nid, n_min,
1245 BIO_printf(bio_err, "No template, please set one up.\n");
1253 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1254 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1255 unsigned long chtype)
1257 int i, spec_char, plus_char;
1263 subj = X509_REQ_get_subject_name(req);
1265 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1267 v = sk_CONF_VALUE_value(dn_sk, i);
1271 * Skip past any leading X. X: X, etc to allow for multiple instances
1273 for (p = v->name; *p; p++) {
1274 #ifndef CHARSET_EBCDIC
1275 spec_char = (*p == ':' || *p == ',' || *p == '.');
1277 spec_char = (*p == os_toascii[':'] || *p == os_toascii[',']
1278 || *p == os_toascii['.']);
1287 #ifndef CHARSET_EBCDIC
1288 plus_char = (*type == '+');
1290 plus_char = (*type == os_toascii['+']);
1298 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1299 (unsigned char *)v->value, -1, -1,
1305 if (!X509_NAME_entry_count(subj)) {
1306 BIO_printf(bio_err, "Error: No objects specified in config file\n");
1310 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1311 v = sk_CONF_VALUE_value(attr_sk, i);
1312 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1313 (unsigned char *)v->value, -1))
1320 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1321 char *value, int nid, int n_min, int n_max,
1322 unsigned long chtype, int mval)
1327 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1328 "DN value", "DN default");
1329 if ((ret == 0) || (ret == 1))
1333 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1334 (unsigned char *)buf, -1, -1, mval))
1340 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1341 char *value, int nid, int n_min,
1342 int n_max, unsigned long chtype)
1347 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1348 "Attribute value", "Attribute default");
1349 if ((ret == 0) || (ret == 1))
1353 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1354 (unsigned char *)buf, -1)) {
1355 BIO_printf(bio_err, "Error adding attribute\n");
1362 static int build_data(char *text, const char *def, char *value,
1363 int n_min, int n_max, char *buf, const int buf_size,
1364 const char *desc1, const char *desc2)
1369 BIO_printf(bio_err, "%s [%s]:", text, def);
1370 (void)BIO_flush(bio_err);
1371 if (value != NULL) {
1372 if (!join(buf, buf_size, value, "\n", desc1))
1374 BIO_printf(bio_err, "%s\n", value);
1378 if (!fgets(buf, buf_size, stdin))
1388 if (buf[0] == '\n') {
1389 if ((def == NULL) || (def[0] == '\0'))
1391 if (!join(buf, buf_size, def, "\n", desc2))
1393 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1398 if (buf[i - 1] != '\n') {
1399 BIO_printf(bio_err, "Missing newline at end of input\n");
1403 #ifdef CHARSET_EBCDIC
1404 ebcdic2ascii(buf, buf, i);
1406 if (!req_check_len(i, n_min, n_max)) {
1414 static int req_check_len(int len, int n_min, int n_max)
1416 if (n_min > 0 && len < n_min) {
1418 "String too short, must be at least %d bytes long\n", n_min);
1421 if (n_max >= 0 && len > n_max) {
1423 "String too long, must be at most %d bytes long\n", n_max);
1429 /* Check if the end of a string matches 'end' */
1430 static int check_end(const char *str, const char *end)
1439 tmp = str + slen - elen;
1440 return strcmp(tmp, end);
1444 * Merge the two strings together into the result buffer checking for
1445 * overflow and producing an error message if there is.
1447 static int join(char buf[], size_t buf_size, const char *name,
1448 const char *tail, const char *desc)
1450 const size_t name_len = strlen(name), tail_len = strlen(tail);
1452 if (name_len + tail_len + 1 > buf_size) {
1453 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1456 memcpy(buf, name, name_len);
1457 memcpy(buf + name_len, tail, tail_len + 1);
1461 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1462 char **pkeytype, long *pkeylen,
1463 ENGINE *keygen_engine)
1465 EVP_PKEY_CTX *gctx = NULL;
1466 EVP_PKEY *param = NULL;
1469 const char *keytype = NULL;
1470 size_t keytypelen = 0;
1471 int expect_paramfile = 0;
1472 const char *paramfile = NULL;
1474 /* Treat the first part of gstr, and only that */
1477 * Special case: when no string given, default to RSA and the
1478 * key length given by |*pkeylen|.
1482 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1483 /* Special case: only keylength given from string, so default to RSA */
1485 /* The second part treatment will do the rest */
1487 const char *p = strchr(gstr, ':');
1495 if (strncmp(gstr, "param", len) == 0) {
1496 expect_paramfile = 1;
1499 "Parameter file requested but no path given: %s\n",
1509 gstr = gstr + len + 1;
1514 /* Treat the second part of gstr, if there is one */
1516 /* If the second part starts with a digit, we assume it's a size */
1517 if (!expect_paramfile && gstr[0] >= '0' && gstr[0] <= '9')
1518 keylen = atol(gstr);
1523 if (paramfile != NULL) {
1524 pbio = BIO_new_file(paramfile, "r");
1526 BIO_printf(bio_err, "Cannot open parameter file %s\n", paramfile);
1529 param = PEM_read_bio_Parameters(pbio, NULL);
1531 if (param == NULL) {
1534 (void)BIO_reset(pbio);
1535 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1537 param = X509_get_pubkey(x);
1544 if (param == NULL) {
1545 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1548 if (keytype == NULL) {
1549 keytype = EVP_PKEY_get0_type_name(param);
1550 if (keytype == NULL) {
1551 EVP_PKEY_free(param);
1552 BIO_puts(bio_err, "Unable to determine key type\n");
1559 *pkeytype = OPENSSL_strndup(keytype, keytypelen);
1561 *pkeytype = OPENSSL_strdup(keytype);
1563 if (*pkeytype == NULL) {
1564 BIO_printf(bio_err, "Out of memory\n");
1565 EVP_PKEY_free(param);
1572 if (param != NULL) {
1573 if (!EVP_PKEY_is_a(param, *pkeytype)) {
1574 BIO_printf(bio_err, "Key type does not match parameters\n");
1575 EVP_PKEY_free(param);
1579 if (keygen_engine != NULL)
1580 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1582 gctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(),
1583 param, app_get0_propq());
1584 *pkeylen = EVP_PKEY_get_bits(param);
1585 EVP_PKEY_free(param);
1587 if (keygen_engine != NULL) {
1588 int pkey_id = get_legacy_pkey_id(app_get0_libctx(), *pkeytype,
1591 if (pkey_id != NID_undef)
1592 gctx = EVP_PKEY_CTX_new_id(pkey_id, keygen_engine);
1594 gctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(),
1595 *pkeytype, app_get0_propq());
1600 BIO_puts(bio_err, "Error allocating keygen context\n");
1604 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1605 BIO_puts(bio_err, "Error initializing keygen context\n");
1606 EVP_PKEY_CTX_free(gctx);
1609 if (keylen == -1 && (EVP_PKEY_CTX_is_a(gctx, "RSA")
1610 || EVP_PKEY_CTX_is_a(gctx, "RSA-PSS")))
1614 OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
1615 size_t bits = keylen;
1618 OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_BITS, &bits);
1619 if (EVP_PKEY_CTX_set_params(gctx, params) <= 0) {
1620 BIO_puts(bio_err, "Error setting keysize\n");
1621 EVP_PKEY_CTX_free(gctx);