2 * Copyright 1995-2021 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 genpkey_cb(EVP_PKEY_CTX *ctx);
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);
77 static const char *section = "req";
78 static CONF *req_conf = NULL;
79 static CONF *addext_conf = NULL;
82 typedef enum OPTION_choice {
84 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
85 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
86 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
87 OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
88 OPT_VERIFY, OPT_NOENC, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
89 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
91 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL,
92 OPT_COPY_EXTENSIONS, OPT_ADDEXT, OPT_EXTENSIONS,
93 OPT_REQEXTS, OPT_PRECERT, OPT_MD,
95 OPT_R_ENUM, OPT_PROV_ENUM
98 const OPTIONS req_options[] = {
99 OPT_SECTION("General"),
100 {"help", OPT_HELP, '-', "Display this summary"},
101 #ifndef OPENSSL_NO_ENGINE
102 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
103 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
104 "Specify engine to be used for key generation operations"},
106 {"in", OPT_IN, '<', "X.509 request input file"},
107 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
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 x509 structure instead of a cert request"},
120 {"CA", OPT_CA, '<', "Issuer certificate to use with -x509"},
121 {"CAkey", OPT_CAKEY, 's',
122 "Issuer private key to use with -x509; default is -CA arg"},
123 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
124 {"subj", OPT_SUBJ, 's', "Set or modify subject of request or cert"},
125 {"subject", OPT_SUBJECT, '-',
126 "Print the subject of the output request or cert"},
127 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
128 "Deprecated; multi-valued RDNs support is always on."},
129 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
130 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
131 {"copy_extensions", OPT_COPY_EXTENSIONS, 's',
132 "copy extensions from request when using -x509"},
133 {"addext", OPT_ADDEXT, 's',
134 "Additional cert extension key=value pair (may be given more than once)"},
135 {"extensions", OPT_EXTENSIONS, 's',
136 "Cert extension section (override value in config file)"},
137 {"reqexts", OPT_REQEXTS, 's',
138 "Request extension section (override value in config file)"},
139 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
141 OPT_SECTION("Keys and Signing"),
142 {"key", OPT_KEY, 's', "Private key to use"},
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 {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"},
162 {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"},
163 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
164 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
165 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
173 * An LHASH of strings, where each string is an extension name.
175 static unsigned long ext_name_hash(const OPENSSL_STRING *a)
177 return OPENSSL_LH_strhash((const char *)a);
180 static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
182 return strcmp((const char *)a, (const char *)b);
185 static void exts_cleanup(OPENSSL_STRING *x)
187 OPENSSL_free((char *)x);
191 * Is the |kv| key already duplicated? This is remarkably tricky to get right.
192 * Return 0 if unique, -1 on runtime error; 1 if found or a syntax error.
194 static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
200 /* Skip leading whitespace, make a copy. */
201 while (*kv && isspace(*kv))
204 if ((p = strchr(kv, '=')) == NULL)
207 if ((kv = OPENSSL_strdup(kv)) == NULL)
210 /* Skip trailing space before the equal sign. */
211 for (p = kv + off; p > kv; --p)
220 /* Finally have a clean "key"; see if it's there [by attempt to add it]. */
221 p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING *)kv);
225 } else if (lh_OPENSSL_STRING_error(addexts)) {
233 int req_main(int argc, char **argv)
235 ASN1_INTEGER *serial = NULL;
237 ENGINE *e = NULL, *gen_eng = NULL;
238 EVP_PKEY *pkey = NULL, *CAkey = NULL;
239 EVP_PKEY_CTX *genctx = NULL;
240 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL, *vfyopts = NULL;
241 LHASH_OF(OPENSSL_STRING) *addexts = NULL;
242 X509 *new_x509 = NULL, *CAcert = NULL;
243 X509_REQ *req = NULL;
244 EVP_CIPHER *cipher = NULL;
246 int ext_copy = EXT_COPY_UNSET;
247 BIO *addext_bio = NULL;
248 char *extensions = NULL;
249 const char *infile = NULL, *CAfile = NULL, *CAkeyfile = NULL;
250 char *outfile = NULL, *keyfile = NULL, *digest = NULL;
251 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
252 char *passin = NULL, *passout = NULL;
253 char *nofree_passin = NULL, *nofree_passout = NULL;
254 char *req_exts = NULL, *subj = NULL;
255 X509_NAME *fsubj = NULL;
256 char *template = default_config_file, *keyout = NULL;
257 const char *keyalg = NULL;
259 int days = UNSET_DAYS;
260 int ret = 1, gen_x509 = 0, i = 0, newreq = 0, verbose = 0;
261 int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyform = FORMAT_UNDEF;
262 int modulus = 0, multirdn = 1, verify = 0, noout = 0, text = 0;
263 int noenc = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
264 long newkey_len = -1;
265 unsigned long chtype = MBSTRING_ASC, reqflag = 0;
267 #ifndef OPENSSL_NO_DES
268 cipher = (EVP_CIPHER *)EVP_des_ede3_cbc();
271 prog = opt_init(argc, argv, req_options);
272 while ((o = opt_next()) != OPT_EOF) {
277 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
280 opt_help(req_options);
284 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
288 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
292 e = setup_engine(opt_arg(), 0);
294 case OPT_KEYGEN_ENGINE:
295 #ifndef OPENSSL_NO_ENGINE
296 gen_eng = setup_engine(opt_arg(), 0);
297 if (gen_eng == NULL) {
298 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
313 template = opt_arg();
319 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
332 passargin = opt_arg();
335 passargout = opt_arg();
342 if (!opt_provider(o))
350 if (pkeyopts == NULL)
351 pkeyopts = sk_OPENSSL_STRING_new_null();
353 || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
358 sigopts = sk_OPENSSL_STRING_new_null();
359 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
364 vfyopts = sk_OPENSSL_STRING_new_null();
365 if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
391 chtype = MBSTRING_UTF8;
394 if (!set_nameopt(opt_arg()))
398 if (!set_cert_ex(&reqflag, opt_arg()))
411 CAkeyfile = opt_arg();
414 days = atoi(opt_arg());
416 BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n",
422 if (serial != NULL) {
423 BIO_printf(bio_err, "Serial number supplied twice\n");
426 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
436 case OPT_MULTIVALUE_RDN:
439 case OPT_COPY_EXTENSIONS:
440 if (!set_ext_copy(&ext_copy, opt_arg())) {
441 BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n",
448 if (addexts == NULL) {
449 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
450 addext_bio = BIO_new(BIO_s_mem());
451 if (addexts == NULL || addext_bio == NULL)
454 i = duplicated(addexts, p);
456 BIO_printf(bio_err, "Duplicate extension: %s\n", p);
459 if (i < 0 || BIO_printf(addext_bio, "%s\n", p) < 0)
463 extensions = opt_arg();
466 req_exts = opt_arg();
469 newreq = precert = 1;
472 digest = opt_unknown();
477 /* No extra arguments. */
478 argc = opt_num_rest();
482 if (!app_RAND_load())
486 if (days != UNSET_DAYS)
487 BIO_printf(bio_err, "Ignoring -days without -x509; not generating a certificate\n");
488 if (ext_copy == EXT_COPY_NONE)
489 BIO_printf(bio_err, "Ignoring -copy_extensions 'none' when -x509 is not given\n");
491 if (gen_x509 && infile == NULL)
494 if (!app_passwd(passargin, passargout, &passin, &passout)) {
495 BIO_printf(bio_err, "Error getting passwords\n");
499 if ((req_conf = app_load_config_verbose(template, verbose)) == NULL)
501 if (addext_bio != NULL) {
504 "Using additional configuration from -addext options\n");
505 if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
508 if (template != default_config_file && !app_load_modules(req_conf))
511 if (req_conf != NULL) {
512 p = NCONF_get_string(req_conf, NULL, "oid_file");
516 BIO *oid_bio = BIO_new_file(p, "r");
518 if (oid_bio == NULL) {
521 "Problems opening '%s' for extra OIDs\n", p);
523 OBJ_create_objects(oid_bio);
528 if (!add_oid_section(req_conf))
531 /* Check that any specified digest is fetchable */
532 if (digest != NULL) {
533 if (!opt_md(digest, &md)) {
539 /* No digest specified, default to configuration */
540 p = NCONF_get_string(req_conf, section, "default_md");
547 if (extensions == NULL) {
548 extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS);
549 if (extensions == NULL)
552 if (extensions != NULL) {
553 /* Check syntax of file */
556 X509V3_set_ctx_test(&ctx);
557 X509V3_set_nconf(&ctx, req_conf);
558 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
560 "Error checking x509 extension section %s\n",
565 if (addext_conf != NULL) {
566 /* Check syntax of command line extensions */
569 X509V3_set_ctx_test(&ctx);
570 X509V3_set_nconf(&ctx, addext_conf);
571 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
572 BIO_printf(bio_err, "Error checking extensions defined using -addext\n");
577 if (passin == NULL) {
578 passin = nofree_passin =
579 NCONF_get_string(req_conf, section, "input_password");
584 if (passout == NULL) {
585 passout = nofree_passout =
586 NCONF_get_string(req_conf, section, "output_password");
591 p = NCONF_get_string(req_conf, section, STRING_MASK);
595 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
596 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
600 if (chtype != MBSTRING_UTF8) {
601 p = NCONF_get_string(req_conf, section, UTF8_IN);
604 else if (strcmp(p, "yes") == 0)
605 chtype = MBSTRING_UTF8;
608 if (req_exts == NULL) {
609 req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS);
610 if (req_exts == NULL)
613 if (req_exts != NULL) {
614 /* Check syntax of file */
617 X509V3_set_ctx_test(&ctx);
618 X509V3_set_nconf(&ctx, req_conf);
619 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
621 "Error checking request extension section %s\n",
627 if (keyfile != NULL) {
628 pkey = load_key(keyfile, keyform, 0, passin, e, "private key");
631 app_RAND_load_conf(req_conf, section);
634 if (newreq && pkey == NULL) {
635 app_RAND_load_conf(req_conf, section);
637 if (!NCONF_get_number(req_conf, section, BITS, &newkey_len))
638 newkey_len = DEFAULT_KEY_LENGTH;
640 genctx = set_keygen_ctx(keyalg, &keyalgstr, &newkey_len, gen_eng);
644 if (newkey_len < MIN_KEY_LENGTH
645 && (EVP_PKEY_CTX_is_a(genctx, "RSA")
646 || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS")
647 || EVP_PKEY_CTX_is_a(genctx, "DSA"))) {
648 BIO_printf(bio_err, "Private key length too short, needs to be at least %d bits, not %ld.\n",
649 MIN_KEY_LENGTH, newkey_len);
653 if (newkey_len > OPENSSL_RSA_MAX_MODULUS_BITS
654 && (EVP_PKEY_CTX_is_a(genctx, "RSA")
655 || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS")))
657 "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
658 " Your key size is %ld! Larger key size may behave not as expected.\n",
659 OPENSSL_RSA_MAX_MODULUS_BITS, newkey_len);
661 #ifndef OPENSSL_NO_DSA
662 if (EVP_PKEY_CTX_is_a(genctx, "DSA")
663 && newkey_len > OPENSSL_DSA_MAX_MODULUS_BITS)
665 "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
666 " Your key size is %ld! Larger key size may behave not as expected.\n",
667 OPENSSL_DSA_MAX_MODULUS_BITS, newkey_len);
670 if (pkeyopts != NULL) {
672 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
673 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
674 if (pkey_ctrl_string(genctx, genopt) <= 0) {
675 BIO_printf(bio_err, "Key parameter error \"%s\"\n", genopt);
681 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
682 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
684 pkey = app_keygen(genctx, keyalgstr, newkey_len, verbose);
686 EVP_PKEY_CTX_free(genctx);
689 if (keyout == NULL) {
690 keyout = NCONF_get_string(req_conf, section, KEYFILE);
695 if (pkey != NULL && (keyfile == NULL || keyout != NULL)) {
697 BIO_printf(bio_err, "Writing private key to ");
699 BIO_printf(bio_err, "stdout\n");
701 BIO_printf(bio_err, "'%s'\n", keyout);
703 out = bio_open_owner(keyout, outformat, newreq);
707 p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
710 p = NCONF_get_string(req_conf, section, "encrypt_key");
714 if ((p != NULL) && (strcmp(p, "no") == 0))
721 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
722 NULL, 0, NULL, passout)) {
723 if ((ERR_GET_REASON(ERR_peek_error()) ==
724 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
733 BIO_printf(bio_err, "-----\n");
737 * subj is expected to be in the format /type0=value0/type1=value1/type2=...
738 * where characters may be escaped by \
741 && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL)
745 req = load_csr(infile, informat, "X509 request");
750 if (CAkeyfile == NULL)
752 if (CAkeyfile != NULL) {
753 if (CAfile == NULL) {
755 "Ignoring -CAkey option since no -CA option is given\n");
757 if ((CAkey = load_key(CAkeyfile, FORMAT_UNDEF,
758 0, passin, e, "issuer private key")) == NULL)
762 if (CAfile != NULL) {
765 "Warning: Ignoring -CA option without -x509\n");
767 if (CAkeyfile == NULL) {
769 "Need to give the -CAkey option if using -CA\n");
772 if ((CAcert = load_cert_pass(CAfile, FORMAT_UNDEF, 1, passin,
773 "issuer certificate")) == NULL)
775 if (!X509_check_private_key(CAcert, CAkey)) {
777 "Issuer certificate and key do not match\n");
782 if (newreq || gen_x509) {
783 if (pkey == NULL /* can happen only if !newreq */) {
784 BIO_printf(bio_err, "Must provide a signature key using -key\n");
789 req = X509_REQ_new_ex(app_get0_libctx(), app_get0_propq());
794 if (!make_REQ(req, pkey, fsubj, multirdn, !gen_x509, chtype)){
795 BIO_printf(bio_err, "Error making certificate request\n");
800 EVP_PKEY *pub_key = X509_REQ_get0_pubkey(req);
802 X509_NAME *issuer = CAcert != NULL ? X509_get_subject_name(CAcert) :
803 X509_REQ_get_subject_name(req);
804 X509_NAME *n_subj = fsubj != NULL ? fsubj :
805 X509_REQ_get_subject_name(req);
807 if ((new_x509 = X509_new_ex(app_get0_libctx(),
808 app_get0_propq())) == NULL)
811 if (serial != NULL) {
812 if (!X509_set_serialNumber(new_x509, serial))
815 if (!rand_serial(NULL, X509_get_serialNumber(new_x509)))
819 if (!X509_set_issuer_name(new_x509, issuer))
821 if (days == UNSET_DAYS) {
824 if (!set_cert_times(new_x509, NULL, NULL, days))
826 if (!X509_set_subject_name(new_x509, n_subj))
828 if (!pub_key || !X509_set_pubkey(new_x509, pub_key))
830 if (ext_copy == EXT_COPY_UNSET) {
831 BIO_printf(bio_err, "Warning: No -copy_extensions given; ignoring any extensions in the request\n");
832 } else if (!copy_extensions(new_x509, req, ext_copy)) {
833 BIO_printf(bio_err, "Error copying extensions from request\n");
837 /* Set up V3 context struct */
838 X509V3_set_ctx(&ext_ctx, CAcert != NULL ? CAcert : new_x509,
839 new_x509, NULL, NULL, X509V3_CTX_REPLACE);
840 if (CAcert == NULL) { /* self-issued, possibly self-signed */
841 if (!X509V3_set_issuer_pkey(&ext_ctx, pkey)) /* prepare right AKID */
844 if (!X509_check_private_key(new_x509, pkey))
846 "Warning: Signature key and public key of cert do not match\n");
849 X509V3_set_nconf(&ext_ctx, req_conf);
852 if (extensions != NULL
853 && !X509V3_EXT_add_nconf(req_conf, &ext_ctx, extensions,
855 BIO_printf(bio_err, "Error adding x509 extensions from section %s\n",
859 if (addext_conf != NULL
860 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
862 BIO_printf(bio_err, "Error adding extensions defined via -addext\n");
866 /* If a pre-cert was requested, we need to add a poison extension */
868 if (X509_add1_ext_i2d(new_x509, NID_ct_precert_poison,
870 BIO_printf(bio_err, "Error adding poison extension\n");
875 i = do_X509_sign(new_x509, CAcert != NULL ? CAkey : pkey,
876 digest, sigopts, &ext_ctx);
882 /* Set up V3 context struct */
883 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
884 X509V3_set_nconf(&ext_ctx, req_conf);
888 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
890 BIO_printf(bio_err, "Error adding request extensions from section %s\n",
894 if (addext_conf != NULL
895 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
897 BIO_printf(bio_err, "Error adding extensions defined via -addext\n");
900 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
906 if (subj != NULL && !newreq && !gen_x509) {
908 BIO_printf(out, "Modifying subject of certificate request\n");
909 print_name(out, "Old subject=", X509_REQ_get_subject_name(req));
912 if (!X509_REQ_set_subject_name(req, fsubj)) {
913 BIO_printf(bio_err, "Error modifying subject of certificate request\n");
918 print_name(out, "New subject=", X509_REQ_get_subject_name(req));
923 EVP_PKEY *tpubkey = pkey;
925 if (tpubkey == NULL) {
926 tpubkey = X509_REQ_get0_pubkey(req);
931 i = do_X509_REQ_verify(req, tpubkey, vfyopts);
936 BIO_printf(bio_err, "Certificate request self-signature verify failure\n");
938 BIO_printf(bio_err, "Certificate request self-signature verify OK\n");
941 if (noout && !text && !modulus && !subject && !pubkey) {
946 out = bio_open_default(outfile,
947 keyout != NULL && outfile != NULL &&
948 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
954 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
956 if (tpubkey == NULL) {
957 BIO_printf(bio_err, "Error getting public key\n");
960 PEM_write_bio_PUBKEY(out, tpubkey);
965 ret = X509_print_ex(out, new_x509, get_nameopt(), reqflag);
967 ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
971 BIO_printf(bio_err, "Error printing certificate\n");
973 BIO_printf(bio_err, "Error printing certificate request\n");
979 print_name(out, "subject=", gen_x509
980 ? X509_get_subject_name(new_x509)
981 : X509_REQ_get_subject_name(req));
988 tpubkey = X509_get0_pubkey(new_x509);
990 tpubkey = X509_REQ_get0_pubkey(req);
991 if (tpubkey == NULL) {
992 fprintf(stdout, "Modulus is unavailable\n");
995 fprintf(stdout, "Modulus=");
996 if (EVP_PKEY_is_a(tpubkey, "RSA")) {
999 /* Every RSA key has an 'n' */
1000 EVP_PKEY_get_bn_param(pkey, "n", &n);
1004 fprintf(stdout, "Wrong Algorithm type");
1006 fprintf(stdout, "\n");
1009 if (!noout && !gen_x509) {
1010 if (outformat == FORMAT_ASN1)
1011 i = i2d_X509_REQ_bio(out, req);
1013 i = PEM_write_bio_X509_REQ_NEW(out, req);
1015 i = PEM_write_bio_X509_REQ(out, req);
1017 BIO_printf(bio_err, "Unable to write certificate request\n");
1021 if (!noout && gen_x509 && new_x509 != NULL) {
1022 if (outformat == FORMAT_ASN1)
1023 i = i2d_X509_bio(out, new_x509);
1025 i = PEM_write_bio_X509(out, new_x509);
1027 BIO_printf(bio_err, "Unable to write X509 certificate\n");
1034 ERR_print_errors(bio_err);
1036 NCONF_free(req_conf);
1037 NCONF_free(addext_conf);
1038 BIO_free(addext_bio);
1040 EVP_PKEY_free(pkey);
1041 EVP_PKEY_CTX_free(genctx);
1042 sk_OPENSSL_STRING_free(pkeyopts);
1043 sk_OPENSSL_STRING_free(sigopts);
1044 sk_OPENSSL_STRING_free(vfyopts);
1045 lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
1046 lh_OPENSSL_STRING_free(addexts);
1047 #ifndef OPENSSL_NO_ENGINE
1048 release_engine(gen_eng);
1050 OPENSSL_free(keyalgstr);
1052 X509_NAME_free(fsubj);
1053 X509_free(new_x509);
1055 EVP_PKEY_free(CAkey);
1056 ASN1_INTEGER_free(serial);
1058 if (passin != nofree_passin)
1059 OPENSSL_free(passin);
1060 if (passout != nofree_passout)
1061 OPENSSL_free(passout);
1065 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj,
1066 int multirdn, int attribs, unsigned long chtype)
1070 STACK_OF(CONF_VALUE) *dn_sk = NULL, *attr_sk = NULL;
1071 char *tmp, *dn_sect, *attr_sect;
1073 tmp = NCONF_get_string(req_conf, section, PROMPT);
1076 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1079 dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
1080 if (dn_sect == NULL) {
1083 dn_sk = NCONF_get_section(req_conf, dn_sect);
1084 if (dn_sk == NULL) {
1085 BIO_printf(bio_err, "Unable to get '%s' section\n", dn_sect);
1090 attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
1091 if (attr_sect == NULL) {
1094 attr_sk = NCONF_get_section(req_conf, attr_sect);
1095 if (attr_sk == NULL) {
1096 BIO_printf(bio_err, "Unable to get '%s' section\n", attr_sect);
1101 /* so far there is only version 1 */
1102 if (!X509_REQ_set_version(req, X509_REQ_VERSION_1))
1106 i = X509_REQ_set_subject_name(req, fsubj);
1108 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1110 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1115 if (!X509_REQ_set_pubkey(req, pkey))
1123 static int prompt_info(X509_REQ *req,
1124 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1125 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1126 int attribs, unsigned long chtype)
1136 X509_NAME *subj = X509_REQ_get_subject_name(req);
1140 "You are about to be asked to enter information that will be incorporated\n");
1141 BIO_printf(bio_err, "into your certificate request.\n");
1143 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1145 "There are quite a few fields but you can leave some blank\n");
1147 "For some fields there will be a default value,\n");
1149 "If you enter '.', the field will be left blank.\n");
1150 BIO_printf(bio_err, "-----\n");
1153 if (sk_CONF_VALUE_num(dn_sk)) {
1158 if (sk_CONF_VALUE_num(dn_sk) <= i)
1161 v = sk_CONF_VALUE_value(dn_sk, i);
1164 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1165 !check_end(type, "_default") || !check_end(type, "_value"))
1168 * Skip past any leading X. X: X, etc to allow for multiple
1171 for (p = v->name; *p; p++)
1172 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1184 /* If OBJ not recognised ignore it */
1185 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1187 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1189 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1194 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1196 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1201 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1203 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1208 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1210 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1215 if (!add_DN_object(subj, v->value, def, value, nid,
1216 n_min, n_max, chtype, mval))
1219 if (X509_NAME_entry_count(subj) == 0) {
1220 BIO_printf(bio_err, "Error: No objects specified in config file\n");
1225 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1228 "\nPlease enter the following 'extra' attributes\n");
1230 "to be sent with your certificate request\n");
1237 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1240 v = sk_CONF_VALUE_value(attr_sk, i);
1242 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1245 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1247 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1253 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1255 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1261 if (!join(buf, sizeof(buf), type, "_min", "Name"))
1263 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1268 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1270 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1275 if (!add_attribute_object(req,
1276 v->value, def, value, nid, n_min,
1282 BIO_printf(bio_err, "No template, please set one up.\n");
1290 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1291 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1292 unsigned long chtype)
1294 int i, spec_char, plus_char;
1300 subj = X509_REQ_get_subject_name(req);
1302 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1304 v = sk_CONF_VALUE_value(dn_sk, i);
1308 * Skip past any leading X. X: X, etc to allow for multiple instances
1310 for (p = v->name; *p; p++) {
1311 #ifndef CHARSET_EBCDIC
1312 spec_char = (*p == ':' || *p == ',' || *p == '.');
1314 spec_char = (*p == os_toascii[':'] || *p == os_toascii[',']
1315 || *p == os_toascii['.']);
1324 #ifndef CHARSET_EBCDIC
1325 plus_char = (*type == '+');
1327 plus_char = (*type == os_toascii['+']);
1335 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1336 (unsigned char *)v->value, -1, -1,
1342 if (!X509_NAME_entry_count(subj)) {
1343 BIO_printf(bio_err, "Error: No objects specified in config file\n");
1347 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1348 v = sk_CONF_VALUE_value(attr_sk, i);
1349 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1350 (unsigned char *)v->value, -1))
1357 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1358 char *value, int nid, int n_min, int n_max,
1359 unsigned long chtype, int mval)
1364 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1365 "DN value", "DN default");
1366 if ((ret == 0) || (ret == 1))
1370 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1371 (unsigned char *)buf, -1, -1, mval))
1377 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1378 char *value, int nid, int n_min,
1379 int n_max, unsigned long chtype)
1384 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1385 "Attribute value", "Attribute default");
1386 if ((ret == 0) || (ret == 1))
1390 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1391 (unsigned char *)buf, -1)) {
1392 BIO_printf(bio_err, "Error adding attribute\n");
1399 static int build_data(char *text, const char *def, char *value,
1400 int n_min, int n_max, char *buf, const int buf_size,
1401 const char *desc1, const char *desc2)
1406 BIO_printf(bio_err, "%s [%s]:", text, def);
1407 (void)BIO_flush(bio_err);
1408 if (value != NULL) {
1409 if (!join(buf, buf_size, value, "\n", desc1))
1411 BIO_printf(bio_err, "%s\n", value);
1415 if (!fgets(buf, buf_size, stdin))
1425 if (buf[0] == '\n') {
1426 if ((def == NULL) || (def[0] == '\0'))
1428 if (!join(buf, buf_size, def, "\n", desc2))
1430 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1435 if (buf[i - 1] != '\n') {
1436 BIO_printf(bio_err, "Missing newline at end of input\n");
1440 #ifdef CHARSET_EBCDIC
1441 ebcdic2ascii(buf, buf, i);
1443 if (!req_check_len(i, n_min, n_max)) {
1451 static int req_check_len(int len, int n_min, int n_max)
1453 if (n_min > 0 && len < n_min) {
1455 "String too short, must be at least %d bytes long\n", n_min);
1458 if (n_max >= 0 && len > n_max) {
1460 "String too long, must be at most %d bytes long\n", n_max);
1466 /* Check if the end of a string matches 'end' */
1467 static int check_end(const char *str, const char *end)
1476 tmp = str + slen - elen;
1477 return strcmp(tmp, end);
1481 * Merge the two strings together into the result buffer checking for
1482 * overflow and producing an error message if there is.
1484 static int join(char buf[], size_t buf_size, const char *name,
1485 const char *tail, const char *desc)
1487 const size_t name_len = strlen(name), tail_len = strlen(tail);
1489 if (name_len + tail_len + 1 > buf_size) {
1490 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1493 memcpy(buf, name, name_len);
1494 memcpy(buf + name_len, tail, tail_len + 1);
1498 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1499 char **pkeytype, long *pkeylen,
1500 ENGINE *keygen_engine)
1502 EVP_PKEY_CTX *gctx = NULL;
1503 EVP_PKEY *param = NULL;
1506 const char *keytype = NULL;
1507 size_t keytypelen = 0;
1508 int expect_paramfile = 0;
1509 const char *paramfile = NULL;
1511 /* Treat the first part of gstr, and only that */
1514 * Special case: when no string given, default to RSA and the
1515 * key length given by |*pkeylen|.
1519 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1520 /* Special case: only keylength given from string, so default to RSA */
1522 /* The second part treatment will do the rest */
1524 const char *p = strchr(gstr, ':');
1532 if (strncmp(gstr, "param", len) == 0) {
1533 expect_paramfile = 1;
1536 "Parameter file requested but no path given: %s\n",
1546 gstr = gstr + len + 1;
1551 /* Treat the second part of gstr, if there is one */
1553 /* If the second part starts with a digit, we assume it's a size */
1554 if (!expect_paramfile && gstr[0] >= '0' && gstr[0] <= '9')
1555 keylen = atol(gstr);
1560 if (paramfile != NULL) {
1561 pbio = BIO_new_file(paramfile, "r");
1563 BIO_printf(bio_err, "Cannot open parameter file %s\n", paramfile);
1566 param = PEM_read_bio_Parameters(pbio, NULL);
1568 if (param == NULL) {
1571 (void)BIO_reset(pbio);
1572 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1574 param = X509_get_pubkey(x);
1581 if (param == NULL) {
1582 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1585 if (keytype == NULL) {
1586 keytype = EVP_PKEY_get0_type_name(param);
1587 if (keytype == NULL) {
1588 EVP_PKEY_free(param);
1589 BIO_puts(bio_err, "Unable to determine key type\n");
1596 *pkeytype = OPENSSL_strndup(keytype, keytypelen);
1598 *pkeytype = OPENSSL_strdup(keytype);
1602 if (param != NULL) {
1603 if (!EVP_PKEY_is_a(param, *pkeytype)) {
1604 BIO_printf(bio_err, "Key type does not match parameters\n");
1605 EVP_PKEY_free(param);
1609 if (keygen_engine != NULL)
1610 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1612 gctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(),
1613 param, app_get0_propq());
1614 *pkeylen = EVP_PKEY_get_bits(param);
1615 EVP_PKEY_free(param);
1617 if (keygen_engine != NULL) {
1618 int pkey_id = get_legacy_pkey_id(app_get0_libctx(), keytype,
1621 if (pkey_id != NID_undef)
1622 gctx = EVP_PKEY_CTX_new_id(pkey_id, keygen_engine);
1624 gctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(),
1625 keytype, app_get0_propq());
1630 BIO_puts(bio_err, "Error allocating keygen context\n");
1634 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1635 BIO_puts(bio_err, "Error initializing keygen context\n");
1636 EVP_PKEY_CTX_free(gctx);
1639 if (keylen == -1 && (EVP_PKEY_CTX_is_a(gctx, "RSA")
1640 || EVP_PKEY_CTX_is_a(gctx, "RSA-PSS")))
1644 OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END };
1645 size_t bits = keylen;
1648 OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_BITS, &bits);
1649 if (EVP_PKEY_CTX_set_params(gctx, params) <= 0) {
1650 BIO_puts(bio_err, "Error setting keysize\n");
1651 EVP_PKEY_CTX_free(gctx);
1659 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1662 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1664 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1673 BIO_write(b, &c, 1);