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_EXTENSIONS
, OPT_REQEXTS
, OPT_ADDEXT
,
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 (default stdin)"},
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 X.509 certificate structure instead of a cert request"},
120 {"CA", OPT_CA
, '<', "Issuer cert to use for signing a cert, implies -x509"},
121 {"CAkey", OPT_CAKEY
, 's',
122 "Issuer private key to use with -CA; 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 {"extensions", OPT_EXTENSIONS
, 's',
134 "Cert or request extension section (override value in config file)"},
135 {"reqexts", OPT_REQEXTS
, 's', "An alias for -extensions"},
136 {"addext", OPT_ADDEXT
, 's',
137 "Additional cert extension key=value pair (may be given more than once)"},
138 {"precert", OPT_PRECERT
, '-', "Add a poison extension to generated cert (implies -new)"},
140 OPT_SECTION("Keys and Signing"),
141 {"key", OPT_KEY
, 's', "Key for signing, and to include unless -in given"},
142 {"keyform", OPT_KEYFORM
, 'f', "Key file format (ENGINE, other values ignored)"},
143 {"pubkey", OPT_PUBKEY
, '-', "Output public key"},
144 {"keyout", OPT_KEYOUT
, '>', "File to write private key to"},
145 {"passin", OPT_PASSIN
, 's', "Private key and certificate password source"},
146 {"passout", OPT_PASSOUT
, 's', "Output file pass phrase source"},
147 {"newkey", OPT_NEWKEY
, 's',
148 "Generate new key with [<alg>:]<nbits> or <alg>[:<file>] or param:<file>"},
149 {"pkeyopt", OPT_PKEYOPT
, 's', "Public key options as opt:value"},
150 {"sigopt", OPT_SIGOPT
, 's', "Signature parameter in n:v form"},
151 {"vfyopt", OPT_VFYOPT
, 's', "Verification parameter in n:v form"},
152 {"", OPT_MD
, '-', "Any supported digest"},
154 OPT_SECTION("Output"),
155 {"out", OPT_OUT
, '>', "Output file"},
156 {"outform", OPT_OUTFORM
, 'F', "Output format - DER or PEM"},
157 {"batch", OPT_BATCH
, '-',
158 "Do not ask anything during request generation"},
159 {"verbose", OPT_VERBOSE
, '-', "Verbose output"},
160 {"noenc", OPT_NOENC
, '-', "Don't encrypt private keys"},
161 {"nodes", OPT_NODES
, '-', "Don't encrypt private keys; deprecated"},
162 {"noout", OPT_NOOUT
, '-', "Do not output REQ"},
163 {"newhdr", OPT_NEWHDR
, '-', "Output \"NEW\" in the header lines"},
164 {"modulus", OPT_MODULUS
, '-', "RSA modulus"},
172 * An LHASH of strings, where each string is an extension name.
174 static unsigned long ext_name_hash(const OPENSSL_STRING
*a
)
176 return OPENSSL_LH_strhash((const char *)a
);
179 static int ext_name_cmp(const OPENSSL_STRING
*a
, const OPENSSL_STRING
*b
)
181 return strcmp((const char *)a
, (const char *)b
);
184 static void exts_cleanup(OPENSSL_STRING
*x
)
186 OPENSSL_free((char *)x
);
190 * Is the |kv| key already duplicated? This is remarkably tricky to get right.
191 * Return 0 if unique, -1 on runtime error; 1 if found or a syntax error.
193 static int duplicated(LHASH_OF(OPENSSL_STRING
) *addexts
, char *kv
)
199 /* Skip leading whitespace, make a copy. */
200 while (*kv
&& isspace(*kv
))
203 if ((p
= strchr(kv
, '=')) == NULL
)
206 if ((kv
= OPENSSL_strdup(kv
)) == NULL
)
209 /* Skip trailing space before the equal sign. */
210 for (p
= kv
+ off
; p
> kv
; --p
)
219 /* Finally have a clean "key"; see if it's there [by attempt to add it]. */
220 p
= (char *)lh_OPENSSL_STRING_insert(addexts
, (OPENSSL_STRING
*)kv
);
224 } else if (lh_OPENSSL_STRING_error(addexts
)) {
232 int req_main(int argc
, char **argv
)
234 ASN1_INTEGER
*serial
= NULL
;
236 ENGINE
*e
= NULL
, *gen_eng
= NULL
;
237 EVP_PKEY
*pkey
= NULL
, *CAkey
= NULL
;
238 EVP_PKEY_CTX
*genctx
= NULL
;
239 STACK_OF(OPENSSL_STRING
) *pkeyopts
= NULL
, *sigopts
= NULL
, *vfyopts
= NULL
;
240 LHASH_OF(OPENSSL_STRING
) *addexts
= NULL
;
241 X509
*new_x509
= NULL
, *CAcert
= NULL
;
242 X509_REQ
*req
= NULL
;
243 EVP_CIPHER
*cipher
= NULL
;
245 int ext_copy
= EXT_COPY_UNSET
;
246 BIO
*addext_bio
= NULL
;
247 char *extsect
= NULL
;
248 const char *infile
= NULL
, *CAfile
= NULL
, *CAkeyfile
= NULL
;
249 char *outfile
= NULL
, *keyfile
= NULL
, *digest
= NULL
;
250 char *keyalgstr
= NULL
, *p
, *prog
, *passargin
= NULL
, *passargout
= NULL
;
251 char *passin
= NULL
, *passout
= NULL
;
252 char *nofree_passin
= NULL
, *nofree_passout
= NULL
;
254 X509_NAME
*fsubj
= NULL
;
255 char *template = default_config_file
, *keyout
= NULL
;
256 const char *keyalg
= NULL
;
258 int days
= UNSET_DAYS
;
259 int ret
= 1, gen_x509
= 0, i
= 0, newreq
= 0, verbose
= 0;
260 int informat
= FORMAT_UNDEF
, outformat
= FORMAT_PEM
, keyform
= FORMAT_UNDEF
;
261 int modulus
= 0, multirdn
= 1, verify
= 0, noout
= 0, text
= 0;
262 int noenc
= 0, newhdr
= 0, subject
= 0, pubkey
= 0, precert
= 0;
263 long newkey_len
= -1;
264 unsigned long chtype
= MBSTRING_ASC
, reqflag
= 0;
266 #ifndef OPENSSL_NO_DES
267 cipher
= (EVP_CIPHER
*)EVP_des_ede3_cbc();
270 prog
= opt_init(argc
, argv
, req_options
);
271 while ((o
= opt_next()) != OPT_EOF
) {
276 BIO_printf(bio_err
, "%s: Use -help for summary.\n", prog
);
279 opt_help(req_options
);
283 if (!opt_format(opt_arg(), OPT_FMT_PEMDER
, &informat
))
287 if (!opt_format(opt_arg(), OPT_FMT_PEMDER
, &outformat
))
291 e
= setup_engine(opt_arg(), 0);
293 case OPT_KEYGEN_ENGINE
:
294 #ifndef OPENSSL_NO_ENGINE
295 gen_eng
= setup_engine(opt_arg(), 0);
296 if (gen_eng
== NULL
) {
297 BIO_printf(bio_err
, "Can't find keygen engine %s\n", *argv
);
312 template = opt_arg();
318 if (!opt_format(opt_arg(), OPT_FMT_ANY
, &keyform
))
331 passargin
= opt_arg();
334 passargout
= opt_arg();
341 if (!opt_provider(o
))
349 if (pkeyopts
== NULL
)
350 pkeyopts
= sk_OPENSSL_STRING_new_null();
352 || !sk_OPENSSL_STRING_push(pkeyopts
, opt_arg()))
357 sigopts
= sk_OPENSSL_STRING_new_null();
358 if (!sigopts
|| !sk_OPENSSL_STRING_push(sigopts
, opt_arg()))
363 vfyopts
= sk_OPENSSL_STRING_new_null();
364 if (!vfyopts
|| !sk_OPENSSL_STRING_push(vfyopts
, opt_arg()))
390 chtype
= MBSTRING_UTF8
;
393 if (!set_nameopt(opt_arg()))
397 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",
452 if (addexts
== NULL
) {
453 addexts
= lh_OPENSSL_STRING_new(ext_name_hash
, ext_name_cmp
);
454 addext_bio
= BIO_new(BIO_s_mem());
455 if (addexts
== NULL
|| addext_bio
== NULL
)
458 i
= duplicated(addexts
, p
);
460 BIO_printf(bio_err
, "Duplicate extension name: %s\n", p
);
463 if (i
< 0 || BIO_printf(addext_bio
, "%s\n", p
) < 0)
467 newreq
= precert
= 1;
470 digest
= opt_unknown();
475 /* No extra arguments. */
476 argc
= opt_num_rest();
480 if (!app_RAND_load())
484 if (days
!= UNSET_DAYS
)
485 BIO_printf(bio_err
, "Ignoring -days without -x509; not generating a certificate\n");
486 if (ext_copy
== EXT_COPY_NONE
)
487 BIO_printf(bio_err
, "Ignoring -copy_extensions 'none' when -x509 is not given\n");
489 if (infile
== NULL
) {
494 "Warning: Will read cert request from stdin since no -in option is given\n");
497 if (!app_passwd(passargin
, passargout
, &passin
, &passout
)) {
498 BIO_printf(bio_err
, "Error getting passwords\n");
502 if ((req_conf
= app_load_config_verbose(template, verbose
)) == NULL
)
504 if (addext_bio
!= NULL
) {
507 "Using additional configuration from -addext options\n");
508 if ((addext_conf
= app_load_config_bio(addext_bio
, NULL
)) == NULL
)
511 if (template != default_config_file
&& !app_load_modules(req_conf
))
514 if (req_conf
!= NULL
) {
515 p
= NCONF_get_string(req_conf
, NULL
, "oid_file");
519 BIO
*oid_bio
= BIO_new_file(p
, "r");
521 if (oid_bio
== NULL
) {
524 "Problems opening '%s' for extra OIDs\n", p
);
526 OBJ_create_objects(oid_bio
);
531 if (!add_oid_section(req_conf
))
534 /* Check that any specified digest is fetchable */
535 if (digest
!= NULL
) {
536 if (!opt_md(digest
, &md
)) {
542 /* No digest specified, default to configuration */
543 p
= NCONF_get_string(req_conf
, section
, "default_md");
550 if (extsect
== NULL
) {
551 extsect
= NCONF_get_string(req_conf
, section
,
552 gen_x509
? V3_EXTENSIONS
: REQ_EXTENSIONS
);
556 if (extsect
!= NULL
) {
557 /* Check syntax of extension section in config file */
560 X509V3_set_ctx_test(&ctx
);
561 X509V3_set_nconf(&ctx
, req_conf
);
562 if (!X509V3_EXT_add_nconf(req_conf
, &ctx
, extsect
, NULL
)) {
564 "Error checking %s extension section %s\n",
565 gen_x509
? "x509" : "request", extsect
);
569 if (addext_conf
!= NULL
) {
570 /* Check syntax of command line extensions */
573 X509V3_set_ctx_test(&ctx
);
574 X509V3_set_nconf(&ctx
, addext_conf
);
575 if (!X509V3_EXT_add_nconf(addext_conf
, &ctx
, "default", NULL
)) {
576 BIO_printf(bio_err
, "Error checking extensions defined using -addext\n");
581 if (passin
== NULL
) {
582 passin
= nofree_passin
=
583 NCONF_get_string(req_conf
, section
, "input_password");
588 if (passout
== NULL
) {
589 passout
= nofree_passout
=
590 NCONF_get_string(req_conf
, section
, "output_password");
595 p
= NCONF_get_string(req_conf
, section
, STRING_MASK
);
599 if (p
!= NULL
&& !ASN1_STRING_set_default_mask_asc(p
)) {
600 BIO_printf(bio_err
, "Invalid global string mask setting %s\n", p
);
604 if (chtype
!= MBSTRING_UTF8
) {
605 p
= NCONF_get_string(req_conf
, section
, UTF8_IN
);
608 else if (strcmp(p
, "yes") == 0)
609 chtype
= MBSTRING_UTF8
;
612 if (keyfile
!= NULL
) {
613 pkey
= load_key(keyfile
, keyform
, 0, passin
, e
, "private key");
616 app_RAND_load_conf(req_conf
, section
);
618 if (keyalg
!= NULL
&& pkey
!= NULL
) {
620 "Warning: Not generating key via given -newkey option since -key is given\n");
621 /* Better throw an error in this case */
623 if (newreq
&& pkey
== NULL
) {
624 app_RAND_load_conf(req_conf
, section
);
626 if (!NCONF_get_number(req_conf
, section
, BITS
, &newkey_len
))
627 newkey_len
= DEFAULT_KEY_LENGTH
;
629 genctx
= set_keygen_ctx(keyalg
, &keyalgstr
, &newkey_len
, gen_eng
);
633 if (newkey_len
< MIN_KEY_LENGTH
634 && (EVP_PKEY_CTX_is_a(genctx
, "RSA")
635 || EVP_PKEY_CTX_is_a(genctx
, "RSA-PSS")
636 || EVP_PKEY_CTX_is_a(genctx
, "DSA"))) {
637 BIO_printf(bio_err
, "Private key length too short, needs to be at least %d bits, not %ld.\n",
638 MIN_KEY_LENGTH
, newkey_len
);
642 if (newkey_len
> OPENSSL_RSA_MAX_MODULUS_BITS
643 && (EVP_PKEY_CTX_is_a(genctx
, "RSA")
644 || EVP_PKEY_CTX_is_a(genctx
, "RSA-PSS")))
646 "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
647 " Your key size is %ld! Larger key size may behave not as expected.\n",
648 OPENSSL_RSA_MAX_MODULUS_BITS
, newkey_len
);
650 #ifndef OPENSSL_NO_DSA
651 if (EVP_PKEY_CTX_is_a(genctx
, "DSA")
652 && newkey_len
> OPENSSL_DSA_MAX_MODULUS_BITS
)
654 "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
655 " Your key size is %ld! Larger key size may behave not as expected.\n",
656 OPENSSL_DSA_MAX_MODULUS_BITS
, newkey_len
);
659 if (pkeyopts
!= NULL
) {
661 for (i
= 0; i
< sk_OPENSSL_STRING_num(pkeyopts
); i
++) {
662 genopt
= sk_OPENSSL_STRING_value(pkeyopts
, i
);
663 if (pkey_ctrl_string(genctx
, genopt
) <= 0) {
664 BIO_printf(bio_err
, "Key parameter error \"%s\"\n", genopt
);
670 EVP_PKEY_CTX_set_cb(genctx
, genpkey_cb
);
671 EVP_PKEY_CTX_set_app_data(genctx
, bio_err
);
673 pkey
= app_keygen(genctx
, keyalgstr
, newkey_len
, verbose
);
675 EVP_PKEY_CTX_free(genctx
);
678 if (keyout
== NULL
&& keyfile
== NULL
) {
679 keyout
= NCONF_get_string(req_conf
, section
, KEYFILE
);
684 if (pkey
!= NULL
&& (keyfile
== NULL
|| keyout
!= NULL
)) {
686 BIO_printf(bio_err
, "Writing private key to ");
688 BIO_printf(bio_err
, "stdout\n");
690 BIO_printf(bio_err
, "'%s'\n", keyout
);
692 out
= bio_open_owner(keyout
, outformat
, newreq
);
696 p
= NCONF_get_string(req_conf
, section
, "encrypt_rsa_key");
699 p
= NCONF_get_string(req_conf
, section
, "encrypt_key");
703 if ((p
!= NULL
) && (strcmp(p
, "no") == 0))
710 if (!PEM_write_bio_PrivateKey(out
, pkey
, cipher
,
711 NULL
, 0, NULL
, passout
)) {
712 if ((ERR_GET_REASON(ERR_peek_error()) ==
713 PEM_R_PROBLEMS_GETTING_PASSWORD
) && (i
< 3)) {
722 BIO_printf(bio_err
, "-----\n");
726 * subj is expected to be in the format /type0=value0/type1=value1/type2=...
727 * where characters may be escaped by \
730 && (fsubj
= parse_name(subj
, chtype
, multirdn
, "subject")) == NULL
)
736 "Warning: Not placing -key in cert or request since request is used\n");
737 req
= load_csr(infile
/* if NULL, reads from stdin */,
738 informat
, "X509 request");
741 } else if (infile
!= NULL
) {
743 "Warning: Ignoring -in option since -new or -newkey or -precert is given\n");
744 /* Better throw an error in this case, as done in the x509 app */
747 if (CAkeyfile
== NULL
)
749 if (CAkeyfile
!= NULL
) {
750 if (CAfile
== NULL
) {
752 "Warning: Ignoring -CAkey option since no -CA option is given\n");
754 if ((CAkey
= load_key(CAkeyfile
, FORMAT_UNDEF
,
757 ? "issuer private key from -CAkey arg"
758 : "issuer private key from -CA arg")) == NULL
)
762 if (CAfile
!= NULL
) {
763 if ((CAcert
= load_cert_pass(CAfile
, FORMAT_UNDEF
, 1, passin
,
764 "issuer cert from -CA arg")) == NULL
)
766 if (!X509_check_private_key(CAcert
, CAkey
)) {
768 "Issuer CA certificate and key do not match\n");
772 if (newreq
|| gen_x509
) {
773 if (pkey
== NULL
/* can happen only if !newreq */) {
774 BIO_printf(bio_err
, "Must provide a signature key using -key\n");
779 req
= X509_REQ_new_ex(app_get0_libctx(), app_get0_propq());
784 if (!make_REQ(req
, pkey
, fsubj
, multirdn
, !gen_x509
, chtype
)) {
785 BIO_printf(bio_err
, "Error making certificate request\n");
788 /* Note that -x509 can take over -key and -subj option values. */
791 EVP_PKEY
*pub_key
= X509_REQ_get0_pubkey(req
);
792 EVP_PKEY
*issuer_key
= CAcert
!= NULL
? CAkey
: pkey
;
794 X509_NAME
*issuer
= CAcert
!= NULL
? X509_get_subject_name(CAcert
) :
795 X509_REQ_get_subject_name(req
);
796 X509_NAME
*n_subj
= fsubj
!= NULL
? fsubj
:
797 X509_REQ_get_subject_name(req
);
799 if (CAcert
!= NULL
&& keyfile
!= NULL
)
801 "Warning: Not using -key or -newkey for signing since -CA option is given\n");
803 if ((new_x509
= X509_new_ex(app_get0_libctx(),
804 app_get0_propq())) == NULL
)
807 if (serial
!= NULL
) {
808 if (!X509_set_serialNumber(new_x509
, serial
))
811 if (!rand_serial(NULL
, X509_get_serialNumber(new_x509
)))
815 if (!X509_set_issuer_name(new_x509
, issuer
))
817 if (days
== UNSET_DAYS
) {
820 if (!set_cert_times(new_x509
, NULL
, NULL
, days
))
822 if (!X509_set_subject_name(new_x509
, n_subj
))
824 if (!pub_key
|| !X509_set_pubkey(new_x509
, pub_key
))
826 if (ext_copy
== EXT_COPY_UNSET
) {
828 BIO_printf(bio_err
, "Warning: No -copy_extensions given; ignoring any extensions in the request\n");
829 } else if (!copy_extensions(new_x509
, req
, ext_copy
)) {
830 BIO_printf(bio_err
, "Error copying extensions from request\n");
834 /* Set up V3 context struct */
835 X509V3_set_ctx(&ext_ctx
, CAcert
!= NULL
? CAcert
: new_x509
,
836 new_x509
, NULL
, NULL
, X509V3_CTX_REPLACE
);
837 /* prepare fallback for AKID, but only if issuer cert == new_x509 */
838 if (CAcert
== NULL
) {
839 if (!X509V3_set_issuer_pkey(&ext_ctx
, issuer_key
))
842 if (!X509_check_private_key(new_x509
, issuer_key
))
844 "Warning: Signature key and public key of cert do not match\n");
847 X509V3_set_nconf(&ext_ctx
, req_conf
);
851 && !X509V3_EXT_add_nconf(req_conf
, &ext_ctx
, extsect
, new_x509
)) {
852 BIO_printf(bio_err
, "Error adding x509 extensions from section %s\n",
856 if (addext_conf
!= NULL
857 && !X509V3_EXT_add_nconf(addext_conf
, &ext_ctx
, "default",
859 BIO_printf(bio_err
, "Error adding x509 extensions defined via -addext\n");
863 /* If a pre-cert was requested, we need to add a poison extension */
865 if (X509_add1_ext_i2d(new_x509
, NID_ct_precert_poison
,
867 BIO_printf(bio_err
, "Error adding poison extension\n");
872 i
= do_X509_sign(new_x509
, issuer_key
, digest
, sigopts
, &ext_ctx
);
880 "Warning: Ignoring -precert flag since no cert is produced\n");
882 /* Set up V3 context struct */
883 X509V3_set_ctx(&ext_ctx
, NULL
, NULL
, req
, NULL
, X509V3_CTX_REPLACE
);
884 X509V3_set_nconf(&ext_ctx
, req_conf
);
888 && !X509V3_EXT_REQ_add_nconf(req_conf
, &ext_ctx
, extsect
, req
)) {
889 BIO_printf(bio_err
, "Error adding request extensions from section %s\n",
893 if (addext_conf
!= NULL
894 && !X509V3_EXT_REQ_add_nconf(addext_conf
, &ext_ctx
, "default",
896 BIO_printf(bio_err
, "Error adding request extensions defined via -addext\n");
899 i
= do_X509_REQ_sign(req
, pkey
, digest
, sigopts
);
905 if (subj
!= NULL
&& !newreq
&& !gen_x509
) {
907 BIO_printf(out
, "Modifying subject of certificate request\n");
908 print_name(out
, "Old subject=", X509_REQ_get_subject_name(req
));
911 if (!X509_REQ_set_subject_name(req
, fsubj
)) {
912 BIO_printf(bio_err
, "Error modifying subject of certificate request\n");
917 print_name(out
, "New subject=", X509_REQ_get_subject_name(req
));
922 EVP_PKEY
*tpubkey
= pkey
;
924 if (tpubkey
== NULL
) {
925 tpubkey
= X509_REQ_get0_pubkey(req
);
930 i
= do_X509_REQ_verify(req
, tpubkey
, vfyopts
);
935 BIO_printf(bio_err
, "Certificate request self-signature verify failure\n");
937 BIO_printf(bio_err
, "Certificate request self-signature verify OK\n");
940 if (noout
&& !text
&& !modulus
&& !subject
&& !pubkey
) {
945 out
= bio_open_default(outfile
,
946 keyout
!= NULL
&& outfile
!= NULL
&&
947 strcmp(keyout
, outfile
) == 0 ? 'a' : 'w',
953 EVP_PKEY
*tpubkey
= X509_REQ_get0_pubkey(req
);
955 if (tpubkey
== NULL
) {
956 BIO_printf(bio_err
, "Error getting public key\n");
959 PEM_write_bio_PUBKEY(out
, tpubkey
);
964 ret
= X509_print_ex(out
, new_x509
, get_nameopt(), reqflag
);
966 ret
= X509_REQ_print_ex(out
, req
, get_nameopt(), reqflag
);
970 BIO_printf(bio_err
, "Error printing certificate\n");
972 BIO_printf(bio_err
, "Error printing certificate request\n");
978 print_name(out
, "subject=", gen_x509
979 ? X509_get_subject_name(new_x509
)
980 : X509_REQ_get_subject_name(req
));
987 tpubkey
= X509_get0_pubkey(new_x509
);
989 tpubkey
= X509_REQ_get0_pubkey(req
);
990 if (tpubkey
== NULL
) {
991 fprintf(stdout
, "Modulus is unavailable\n");
994 fprintf(stdout
, "Modulus=");
995 if (EVP_PKEY_is_a(tpubkey
, "RSA")) {
998 if (!EVP_PKEY_get_bn_param(tpubkey
, "n", &n
))
1003 fprintf(stdout
, "Wrong Algorithm type");
1005 fprintf(stdout
, "\n");
1008 if (!noout
&& !gen_x509
) {
1009 if (outformat
== FORMAT_ASN1
)
1010 i
= i2d_X509_REQ_bio(out
, req
);
1012 i
= PEM_write_bio_X509_REQ_NEW(out
, req
);
1014 i
= PEM_write_bio_X509_REQ(out
, req
);
1016 BIO_printf(bio_err
, "Unable to write certificate request\n");
1020 if (!noout
&& gen_x509
&& new_x509
!= NULL
) {
1021 if (outformat
== FORMAT_ASN1
)
1022 i
= i2d_X509_bio(out
, new_x509
);
1024 i
= PEM_write_bio_X509(out
, new_x509
);
1026 BIO_printf(bio_err
, "Unable to write X509 certificate\n");
1033 ERR_print_errors(bio_err
);
1035 NCONF_free(req_conf
);
1036 NCONF_free(addext_conf
);
1037 BIO_free(addext_bio
);
1039 EVP_PKEY_free(pkey
);
1040 EVP_PKEY_CTX_free(genctx
);
1041 sk_OPENSSL_STRING_free(pkeyopts
);
1042 sk_OPENSSL_STRING_free(sigopts
);
1043 sk_OPENSSL_STRING_free(vfyopts
);
1044 lh_OPENSSL_STRING_doall(addexts
, exts_cleanup
);
1045 lh_OPENSSL_STRING_free(addexts
);
1046 #ifndef OPENSSL_NO_ENGINE
1047 release_engine(gen_eng
);
1049 OPENSSL_free(keyalgstr
);
1051 X509_NAME_free(fsubj
);
1052 X509_free(new_x509
);
1054 EVP_PKEY_free(CAkey
);
1055 ASN1_INTEGER_free(serial
);
1057 if (passin
!= nofree_passin
)
1058 OPENSSL_free(passin
);
1059 if (passout
!= nofree_passout
)
1060 OPENSSL_free(passout
);
1064 static int make_REQ(X509_REQ
*req
, EVP_PKEY
*pkey
, X509_NAME
*fsubj
,
1065 int multirdn
, int attribs
, unsigned long chtype
)
1069 STACK_OF(CONF_VALUE
) *dn_sk
= NULL
, *attr_sk
= NULL
;
1070 char *tmp
, *dn_sect
, *attr_sect
;
1072 tmp
= NCONF_get_string(req_conf
, section
, PROMPT
);
1075 if ((tmp
!= NULL
) && strcmp(tmp
, "no") == 0)
1078 dn_sect
= NCONF_get_string(req_conf
, section
, DISTINGUISHED_NAME
);
1079 if (dn_sect
== NULL
) {
1082 dn_sk
= NCONF_get_section(req_conf
, dn_sect
);
1083 if (dn_sk
== NULL
) {
1084 BIO_printf(bio_err
, "Unable to get '%s' section\n", dn_sect
);
1089 attr_sect
= NCONF_get_string(req_conf
, section
, ATTRIBUTES
);
1090 if (attr_sect
== NULL
) {
1093 attr_sk
= NCONF_get_section(req_conf
, attr_sect
);
1094 if (attr_sk
== NULL
) {
1095 BIO_printf(bio_err
, "Unable to get '%s' section\n", attr_sect
);
1100 /* so far there is only version 1 */
1101 if (!X509_REQ_set_version(req
, X509_REQ_VERSION_1
))
1105 i
= X509_REQ_set_subject_name(req
, fsubj
);
1107 i
= auto_info(req
, dn_sk
, attr_sk
, attribs
, chtype
);
1109 i
= prompt_info(req
, dn_sk
, dn_sect
, attr_sk
, attr_sect
, attribs
,
1114 if (!X509_REQ_set_pubkey(req
, pkey
))
1122 static int prompt_info(X509_REQ
*req
,
1123 STACK_OF(CONF_VALUE
) *dn_sk
, const char *dn_sect
,
1124 STACK_OF(CONF_VALUE
) *attr_sk
, const char *attr_sect
,
1125 int attribs
, unsigned long chtype
)
1135 X509_NAME
*subj
= X509_REQ_get_subject_name(req
);
1139 "You are about to be asked to enter information that will be incorporated\n");
1140 BIO_printf(bio_err
, "into your certificate request.\n");
1142 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1144 "There are quite a few fields but you can leave some blank\n");
1146 "For some fields there will be a default value,\n");
1148 "If you enter '.', the field will be left blank.\n");
1149 BIO_printf(bio_err
, "-----\n");
1152 if (sk_CONF_VALUE_num(dn_sk
)) {
1157 if (sk_CONF_VALUE_num(dn_sk
) <= i
)
1160 v
= sk_CONF_VALUE_value(dn_sk
, i
);
1163 if (!check_end(type
, "_min") || !check_end(type
, "_max") ||
1164 !check_end(type
, "_default") || !check_end(type
, "_value"))
1167 * Skip past any leading X. X: X, etc to allow for multiple
1170 for (p
= v
->name
; *p
; p
++)
1171 if ((*p
== ':') || (*p
== ',') || (*p
== '.')) {
1183 /* If OBJ not recognised ignore it */
1184 if ((nid
= OBJ_txt2nid(type
)) == NID_undef
)
1186 if (!join(buf
, sizeof(buf
), v
->name
, "_default", "Name"))
1188 if ((def
= NCONF_get_string(req_conf
, dn_sect
, buf
)) == NULL
) {
1193 if (!join(buf
, sizeof(buf
), v
->name
, "_value", "Name"))
1195 if ((value
= NCONF_get_string(req_conf
, dn_sect
, buf
)) == NULL
) {
1200 if (!join(buf
, sizeof(buf
), v
->name
, "_min", "Name"))
1202 if (!NCONF_get_number(req_conf
, dn_sect
, buf
, &n_min
)) {
1207 if (!join(buf
, sizeof(buf
), v
->name
, "_max", "Name"))
1209 if (!NCONF_get_number(req_conf
, dn_sect
, buf
, &n_max
)) {
1214 if (!add_DN_object(subj
, v
->value
, def
, value
, nid
,
1215 n_min
, n_max
, chtype
, mval
))
1218 if (X509_NAME_entry_count(subj
) == 0) {
1219 BIO_printf(bio_err
, "Error: No objects specified in config file\n");
1224 if ((attr_sk
!= NULL
) && (sk_CONF_VALUE_num(attr_sk
) > 0)
1227 "\nPlease enter the following 'extra' attributes\n");
1229 "to be sent with your certificate request\n");
1236 if ((attr_sk
== NULL
) || (sk_CONF_VALUE_num(attr_sk
) <= i
))
1239 v
= sk_CONF_VALUE_value(attr_sk
, i
);
1241 if ((nid
= OBJ_txt2nid(type
)) == NID_undef
)
1244 if (!join(buf
, sizeof(buf
), type
, "_default", "Name"))
1246 if ((def
= NCONF_get_string(req_conf
, attr_sect
, buf
))
1252 if (!join(buf
, sizeof(buf
), type
, "_value", "Name"))
1254 if ((value
= NCONF_get_string(req_conf
, attr_sect
, buf
))
1260 if (!join(buf
, sizeof(buf
), type
, "_min", "Name"))
1262 if (!NCONF_get_number(req_conf
, attr_sect
, buf
, &n_min
)) {
1267 if (!join(buf
, sizeof(buf
), type
, "_max", "Name"))
1269 if (!NCONF_get_number(req_conf
, attr_sect
, buf
, &n_max
)) {
1274 if (!add_attribute_object(req
,
1275 v
->value
, def
, value
, nid
, n_min
,
1281 BIO_printf(bio_err
, "No template, please set one up.\n");
1289 static int auto_info(X509_REQ
*req
, STACK_OF(CONF_VALUE
) *dn_sk
,
1290 STACK_OF(CONF_VALUE
) *attr_sk
, int attribs
,
1291 unsigned long chtype
)
1293 int i
, spec_char
, plus_char
;
1299 subj
= X509_REQ_get_subject_name(req
);
1301 for (i
= 0; i
< sk_CONF_VALUE_num(dn_sk
); i
++) {
1303 v
= sk_CONF_VALUE_value(dn_sk
, i
);
1307 * Skip past any leading X. X: X, etc to allow for multiple instances
1309 for (p
= v
->name
; *p
; p
++) {
1310 #ifndef CHARSET_EBCDIC
1311 spec_char
= (*p
== ':' || *p
== ',' || *p
== '.');
1313 spec_char
= (*p
== os_toascii
[':'] || *p
== os_toascii
[',']
1314 || *p
== os_toascii
['.']);
1323 #ifndef CHARSET_EBCDIC
1324 plus_char
= (*type
== '+');
1326 plus_char
= (*type
== os_toascii
['+']);
1334 if (!X509_NAME_add_entry_by_txt(subj
, type
, chtype
,
1335 (unsigned char *)v
->value
, -1, -1,
1341 if (!X509_NAME_entry_count(subj
)) {
1342 BIO_printf(bio_err
, "Error: No objects specified in config file\n");
1346 for (i
= 0; i
< sk_CONF_VALUE_num(attr_sk
); i
++) {
1347 v
= sk_CONF_VALUE_value(attr_sk
, i
);
1348 if (!X509_REQ_add1_attr_by_txt(req
, v
->name
, chtype
,
1349 (unsigned char *)v
->value
, -1))
1356 static int add_DN_object(X509_NAME
*n
, char *text
, const char *def
,
1357 char *value
, int nid
, int n_min
, int n_max
,
1358 unsigned long chtype
, int mval
)
1363 ret
= build_data(text
, def
, value
, n_min
, n_max
, buf
, sizeof(buf
),
1364 "DN value", "DN default");
1365 if ((ret
== 0) || (ret
== 1))
1369 if (!X509_NAME_add_entry_by_NID(n
, nid
, chtype
,
1370 (unsigned char *)buf
, -1, -1, mval
))
1376 static int add_attribute_object(X509_REQ
*req
, char *text
, const char *def
,
1377 char *value
, int nid
, int n_min
,
1378 int n_max
, unsigned long chtype
)
1383 ret
= build_data(text
, def
, value
, n_min
, n_max
, buf
, sizeof(buf
),
1384 "Attribute value", "Attribute default");
1385 if ((ret
== 0) || (ret
== 1))
1389 if (!X509_REQ_add1_attr_by_NID(req
, nid
, chtype
,
1390 (unsigned char *)buf
, -1)) {
1391 BIO_printf(bio_err
, "Error adding attribute\n");
1398 static int build_data(char *text
, const char *def
, char *value
,
1399 int n_min
, int n_max
, char *buf
, const int buf_size
,
1400 const char *desc1
, const char *desc2
)
1405 BIO_printf(bio_err
, "%s [%s]:", text
, def
);
1406 (void)BIO_flush(bio_err
);
1407 if (value
!= NULL
) {
1408 if (!join(buf
, buf_size
, value
, "\n", desc1
))
1410 BIO_printf(bio_err
, "%s\n", value
);
1414 if (!fgets(buf
, buf_size
, stdin
))
1424 if (buf
[0] == '\n') {
1425 if ((def
== NULL
) || (def
[0] == '\0'))
1427 if (!join(buf
, buf_size
, def
, "\n", desc2
))
1429 } else if ((buf
[0] == '.') && (buf
[1] == '\n')) {
1434 if (buf
[i
- 1] != '\n') {
1435 BIO_printf(bio_err
, "Missing newline at end of input\n");
1439 #ifdef CHARSET_EBCDIC
1440 ebcdic2ascii(buf
, buf
, i
);
1442 if (!req_check_len(i
, n_min
, n_max
)) {
1450 static int req_check_len(int len
, int n_min
, int n_max
)
1452 if (n_min
> 0 && len
< n_min
) {
1454 "String too short, must be at least %d bytes long\n", n_min
);
1457 if (n_max
>= 0 && len
> n_max
) {
1459 "String too long, must be at most %d bytes long\n", n_max
);
1465 /* Check if the end of a string matches 'end' */
1466 static int check_end(const char *str
, const char *end
)
1475 tmp
= str
+ slen
- elen
;
1476 return strcmp(tmp
, end
);
1480 * Merge the two strings together into the result buffer checking for
1481 * overflow and producing an error message if there is.
1483 static int join(char buf
[], size_t buf_size
, const char *name
,
1484 const char *tail
, const char *desc
)
1486 const size_t name_len
= strlen(name
), tail_len
= strlen(tail
);
1488 if (name_len
+ tail_len
+ 1 > buf_size
) {
1489 BIO_printf(bio_err
, "%s '%s' too long\n", desc
, name
);
1492 memcpy(buf
, name
, name_len
);
1493 memcpy(buf
+ name_len
, tail
, tail_len
+ 1);
1497 static EVP_PKEY_CTX
*set_keygen_ctx(const char *gstr
,
1498 char **pkeytype
, long *pkeylen
,
1499 ENGINE
*keygen_engine
)
1501 EVP_PKEY_CTX
*gctx
= NULL
;
1502 EVP_PKEY
*param
= NULL
;
1505 const char *keytype
= NULL
;
1506 size_t keytypelen
= 0;
1507 int expect_paramfile
= 0;
1508 const char *paramfile
= NULL
;
1510 /* Treat the first part of gstr, and only that */
1513 * Special case: when no string given, default to RSA and the
1514 * key length given by |*pkeylen|.
1518 } else if (gstr
[0] >= '0' && gstr
[0] <= '9') {
1519 /* Special case: only keylength given from string, so default to RSA */
1521 /* The second part treatment will do the rest */
1523 const char *p
= strchr(gstr
, ':');
1531 if (strncmp(gstr
, "param", len
) == 0) {
1532 expect_paramfile
= 1;
1535 "Parameter file requested but no path given: %s\n",
1545 gstr
= gstr
+ len
+ 1;
1550 /* Treat the second part of gstr, if there is one */
1552 /* If the second part starts with a digit, we assume it's a size */
1553 if (!expect_paramfile
&& gstr
[0] >= '0' && gstr
[0] <= '9')
1554 keylen
= atol(gstr
);
1559 if (paramfile
!= NULL
) {
1560 pbio
= BIO_new_file(paramfile
, "r");
1562 BIO_printf(bio_err
, "Cannot open parameter file %s\n", paramfile
);
1565 param
= PEM_read_bio_Parameters(pbio
, NULL
);
1567 if (param
== NULL
) {
1570 (void)BIO_reset(pbio
);
1571 x
= PEM_read_bio_X509(pbio
, NULL
, NULL
, NULL
);
1573 param
= X509_get_pubkey(x
);
1580 if (param
== NULL
) {
1581 BIO_printf(bio_err
, "Error reading parameter file %s\n", paramfile
);
1584 if (keytype
== NULL
) {
1585 keytype
= EVP_PKEY_get0_type_name(param
);
1586 if (keytype
== NULL
) {
1587 EVP_PKEY_free(param
);
1588 BIO_puts(bio_err
, "Unable to determine key type\n");
1595 *pkeytype
= OPENSSL_strndup(keytype
, keytypelen
);
1597 *pkeytype
= OPENSSL_strdup(keytype
);
1601 if (param
!= NULL
) {
1602 if (!EVP_PKEY_is_a(param
, *pkeytype
)) {
1603 BIO_printf(bio_err
, "Key type does not match parameters\n");
1604 EVP_PKEY_free(param
);
1608 if (keygen_engine
!= NULL
)
1609 gctx
= EVP_PKEY_CTX_new(param
, keygen_engine
);
1611 gctx
= EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(),
1612 param
, app_get0_propq());
1613 *pkeylen
= EVP_PKEY_get_bits(param
);
1614 EVP_PKEY_free(param
);
1616 if (keygen_engine
!= NULL
) {
1617 int pkey_id
= get_legacy_pkey_id(app_get0_libctx(), *pkeytype
,
1620 if (pkey_id
!= NID_undef
)
1621 gctx
= EVP_PKEY_CTX_new_id(pkey_id
, keygen_engine
);
1623 gctx
= EVP_PKEY_CTX_new_from_name(app_get0_libctx(),
1624 *pkeytype
, app_get0_propq());
1629 BIO_puts(bio_err
, "Error allocating keygen context\n");
1633 if (EVP_PKEY_keygen_init(gctx
) <= 0) {
1634 BIO_puts(bio_err
, "Error initializing keygen context\n");
1635 EVP_PKEY_CTX_free(gctx
);
1638 if (keylen
== -1 && (EVP_PKEY_CTX_is_a(gctx
, "RSA")
1639 || EVP_PKEY_CTX_is_a(gctx
, "RSA-PSS")))
1643 OSSL_PARAM params
[] = { OSSL_PARAM_END
, OSSL_PARAM_END
};
1644 size_t bits
= keylen
;
1647 OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_BITS
, &bits
);
1648 if (EVP_PKEY_CTX_set_params(gctx
, params
) <= 0) {
1649 BIO_puts(bio_err
, "Error setting keysize\n");
1650 EVP_PKEY_CTX_free(gctx
);
1658 static int genpkey_cb(EVP_PKEY_CTX
*ctx
)
1661 BIO
*b
= EVP_PKEY_CTX_get_app_data(ctx
);
1663 p
= EVP_PKEY_CTX_get_keygen_info(ctx
, 0);
1672 BIO_write(b
, &c
, 1);