2 * Copyright 1995-2018 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/bio.h>
18 #include <openssl/evp.h>
19 #include <openssl/conf.h>
20 #include <openssl/err.h>
21 #include <openssl/asn1.h>
22 #include <openssl/x509.h>
23 #include <openssl/x509v3.h>
24 #include <openssl/objects.h>
25 #include <openssl/pem.h>
26 #include <openssl/bn.h>
27 #include <openssl/lhash.h>
28 #ifndef OPENSSL_NO_RSA
29 # include <openssl/rsa.h>
31 #ifndef OPENSSL_NO_DSA
32 # include <openssl/dsa.h>
36 #define BITS "default_bits"
37 #define KEYFILE "default_keyfile"
38 #define PROMPT "prompt"
39 #define DISTINGUISHED_NAME "distinguished_name"
40 #define ATTRIBUTES "attributes"
41 #define V3_EXTENSIONS "x509_extensions"
42 #define REQ_EXTENSIONS "req_extensions"
43 #define STRING_MASK "string_mask"
44 #define UTF8_IN "utf8"
46 #define DEFAULT_KEY_LENGTH 2048
47 #define MIN_KEY_LENGTH 512
49 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
50 int attribs, unsigned long chtype);
51 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
53 static int prompt_info(X509_REQ *req,
54 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
55 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
56 int attribs, unsigned long chtype);
57 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
58 STACK_OF(CONF_VALUE) *attr, int attribs,
59 unsigned long chtype);
60 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
61 char *value, int nid, int n_min, int n_max,
62 unsigned long chtype);
63 static int add_DN_object(X509_NAME *n, char *text, const char *def,
64 char *value, int nid, int n_min, int n_max,
65 unsigned long chtype, int mval);
66 static int genpkey_cb(EVP_PKEY_CTX *ctx);
67 static int build_data(char *text, const char *def,
68 char *value, int n_min, int n_max,
69 char *buf, const int buf_size,
70 const char *desc1, const char *desc2
72 static int req_check_len(int len, int n_min, int n_max);
73 static int check_end(const char *str, const char *end);
74 static int join(char buf[], size_t buf_size, const char *name,
75 const char *tail, const char *desc);
76 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
77 int *pkey_type, long *pkeylen,
78 char **palgnam, ENGINE *keygen_engine);
80 static const char *section = "req";
81 static CONF *req_conf = NULL;
82 static CONF *addext_conf = NULL;
85 typedef enum OPTION_choice {
86 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
87 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
88 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
89 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
90 OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
91 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
92 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
93 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
94 OPT_REQEXTS, OPT_PRECERT, OPT_MD, OPT_SM2ID, OPT_SM2HEXID,
96 OPT_R_ENUM, OPT_PROV_ENUM
99 const OPTIONS req_options[] = {
100 OPT_SECTION("General"),
101 {"help", OPT_HELP, '-', "Display this summary"},
102 #ifndef OPENSSL_NO_ENGINE
103 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
104 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
105 "Specify engine to be used for key generation operations"},
107 {"in", OPT_IN, '<', "Input file"},
108 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
109 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
111 OPT_SECTION("Certificate"),
112 {"new", OPT_NEW, '-', "New request"},
113 {"config", OPT_CONFIG, '<', "Request template file"},
114 {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
115 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
116 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
117 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
118 {"text", OPT_TEXT, '-', "Text form of request"},
119 {"x509", OPT_X509, '-',
120 "Output an x509 structure instead of a cert request"},
121 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
122 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
123 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
124 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
125 "Enable support for multivalued RDNs"},
126 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
127 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
128 {"addext", OPT_ADDEXT, 's',
129 "Additional cert extension key=value pair (may be given more than once)"},
130 {"extensions", OPT_EXTENSIONS, 's',
131 "Cert extension section (override value in config file)"},
132 {"reqexts", OPT_REQEXTS, 's',
133 "Request extension section (override value in config file)"},
134 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
136 OPT_SECTION("Keys and Signing"),
137 {"key", OPT_KEY, 's', "Private key to use"},
138 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
139 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
140 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
141 {"passin", OPT_PASSIN, 's', "Private key password source"},
142 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
143 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
144 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
145 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
146 {"", OPT_MD, '-', "Any supported digest"},
147 #ifndef OPENSSL_NO_SM2
148 {"sm2-id", OPT_SM2ID, 's',
149 "Specify an ID string to verify an SM2 certificate request"},
150 {"sm2-hex-id", OPT_SM2HEXID, 's',
151 "Specify a hex ID string to verify an SM2 certificate request"},
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 {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
161 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
162 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
163 {"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
191 * right. Return 0 if unique, -1 on runtime error; 1 if found or a syntax
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;
236 BIO *in = NULL, *out = NULL;
237 ENGINE *e = NULL, *gen_eng = NULL;
238 EVP_PKEY *pkey = NULL;
239 EVP_PKEY_CTX *genctx = NULL;
240 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
241 LHASH_OF(OPENSSL_STRING) *addexts = NULL;
243 X509_REQ *req = NULL;
244 const EVP_CIPHER *cipher = NULL;
245 const EVP_MD *md_alg = NULL, *digest = NULL;
246 BIO *addext_bio = NULL;
247 char *extensions = NULL, *infile = NULL;
248 char *outfile = NULL, *keyfile = NULL;
249 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
250 char *passin = NULL, *passout = NULL;
251 char *nofree_passin = NULL, *nofree_passout = NULL;
252 char *req_exts = NULL, *subj = NULL;
253 char *template = default_config_file, *keyout = NULL;
254 const char *keyalg = NULL;
256 int ret = 1, x509 = 0, days = 0, i = 0, newreq = 0, verbose = 0;
257 int pkey_type = -1, private = 0;
258 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
259 int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
260 int nodes = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
262 unsigned long chtype = MBSTRING_ASC, reqflag = 0;
263 unsigned char *sm2_id = NULL;
264 size_t sm2_idlen = 0;
267 #ifndef OPENSSL_NO_DES
268 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 = ENGINE_by_id(opt_arg());
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()))
384 chtype = MBSTRING_UTF8;
387 if (!set_nameopt(opt_arg()))
391 if (!set_cert_ex(&reqflag, opt_arg()))
401 days = atoi(opt_arg());
404 if (serial != NULL) {
405 BIO_printf(bio_err, "Serial number supplied twice\n");
408 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
418 case OPT_MULTIVALUE_RDN:
423 if (addexts == NULL) {
424 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
425 addext_bio = BIO_new(BIO_s_mem());
426 if (addexts == NULL || addext_bio == NULL)
429 i = duplicated(addexts, p);
432 if (i < 0 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
436 extensions = opt_arg();
439 req_exts = opt_arg();
442 newreq = precert = 1;
445 if (!opt_md(opt_unknown(), &md_alg))
450 if (sm2_id != NULL) {
452 "Use one of the options 'sm2-hex-id' or 'sm2-id'\n");
455 sm2_id = (unsigned char *)opt_arg();
456 sm2_idlen = strlen((const char *)sm2_id);
459 if (sm2_id != NULL) {
461 "Use one of the options 'sm2-hex-id' or 'sm2-id'\n");
464 /* try to parse the input as hex string first */
466 sm2_id = OPENSSL_hexstr2buf(opt_arg(), (long *)&sm2_idlen);
467 if (sm2_id == NULL) {
468 BIO_printf(bio_err, "Invalid hex string input\n");
474 argc = opt_num_rest();
479 BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
480 if (x509 && infile == NULL)
483 /* TODO: simplify this as pkey is still always NULL here */
484 private = newreq && (pkey == NULL) ? 1 : 0;
486 if (!app_passwd(passargin, passargout, &passin, &passout)) {
487 BIO_printf(bio_err, "Error getting passwords\n");
492 BIO_printf(bio_err, "Using configuration from %s\n", template);
493 if ((req_conf = app_load_config(template)) == NULL)
498 "Using additional configuration from command line\n");
499 if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
502 if (template != default_config_file && !app_load_modules(req_conf))
505 if (req_conf != NULL) {
506 p = NCONF_get_string(req_conf, NULL, "oid_file");
512 oid_bio = BIO_new_file(p, "r");
513 if (oid_bio == NULL) {
515 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
516 ERR_print_errors(bio_err);
519 OBJ_create_objects(oid_bio);
524 if (!add_oid_section(req_conf))
527 if (md_alg == NULL) {
528 p = NCONF_get_string(req_conf, section, "default_md");
532 if (!opt_md(p, &md_alg))
538 if (extensions == NULL) {
539 extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS);
540 if (extensions == NULL)
543 if (extensions != NULL) {
544 /* Check syntax of file */
546 X509V3_set_ctx_test(&ctx);
547 X509V3_set_nconf(&ctx, req_conf);
548 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
550 "Error Loading extension section %s\n", extensions);
554 if (addext_conf != NULL) {
555 /* Check syntax of command line extensions */
557 X509V3_set_ctx_test(&ctx);
558 X509V3_set_nconf(&ctx, addext_conf);
559 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
560 BIO_printf(bio_err, "Error Loading command line extensions\n");
565 if (passin == NULL) {
566 passin = nofree_passin =
567 NCONF_get_string(req_conf, section, "input_password");
572 if (passout == NULL) {
573 passout = nofree_passout =
574 NCONF_get_string(req_conf, section, "output_password");
579 p = NCONF_get_string(req_conf, section, STRING_MASK);
583 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
584 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
588 if (chtype != MBSTRING_UTF8) {
589 p = NCONF_get_string(req_conf, section, UTF8_IN);
592 else if (strcmp(p, "yes") == 0)
593 chtype = MBSTRING_UTF8;
596 if (req_exts == NULL) {
597 req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS);
598 if (req_exts == NULL)
601 if (req_exts != NULL) {
602 /* Check syntax of file */
604 X509V3_set_ctx_test(&ctx);
605 X509V3_set_nconf(&ctx, req_conf);
606 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
608 "Error Loading request extension section %s\n",
614 if (keyfile != NULL) {
615 pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
617 /* load_key() has already printed an appropriate message */
620 app_RAND_load_conf(req_conf, section);
624 if (newreq && (pkey == NULL)) {
625 app_RAND_load_conf(req_conf, section);
627 if (!NCONF_get_number(req_conf, section, BITS, &newkey)) {
628 newkey = DEFAULT_KEY_LENGTH;
631 if (keyalg != NULL) {
632 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
633 &keyalgstr, gen_eng);
638 if (newkey < MIN_KEY_LENGTH
639 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
640 BIO_printf(bio_err, "private key length is too short,\n");
641 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
642 MIN_KEY_LENGTH, newkey);
646 if (pkey_type == EVP_PKEY_RSA && newkey > OPENSSL_RSA_MAX_MODULUS_BITS)
648 "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
649 " Your key size is %ld! Larger key size may behave not as expected.\n",
650 OPENSSL_RSA_MAX_MODULUS_BITS, newkey);
652 #ifndef OPENSSL_NO_DSA
653 if (pkey_type == EVP_PKEY_DSA && newkey > OPENSSL_DSA_MAX_MODULUS_BITS)
655 "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
656 " Your key size is %ld! Larger key size may behave not as expected.\n",
657 OPENSSL_DSA_MAX_MODULUS_BITS, newkey);
660 if (genctx == NULL) {
661 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
662 &keyalgstr, gen_eng);
667 if (pkeyopts != NULL) {
669 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
670 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
671 if (pkey_ctrl_string(genctx, genopt) <= 0) {
672 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
673 ERR_print_errors(bio_err);
679 if (pkey_type == EVP_PKEY_EC) {
680 BIO_printf(bio_err, "Generating an EC private key\n");
682 BIO_printf(bio_err, "Generating a %s private key\n", keyalgstr);
685 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
686 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
688 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
689 BIO_puts(bio_err, "Error Generating Key\n");
693 EVP_PKEY_CTX_free(genctx);
696 if (keyout == NULL) {
697 keyout = NCONF_get_string(req_conf, section, KEYFILE);
703 BIO_printf(bio_err, "writing new private key to stdout\n");
705 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
706 out = bio_open_owner(keyout, outformat, private);
710 p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
713 p = NCONF_get_string(req_conf, section, "encrypt_key");
717 if ((p != NULL) && (strcmp(p, "no") == 0))
725 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
726 NULL, 0, NULL, passout)) {
727 if ((ERR_GET_REASON(ERR_peek_error()) ==
728 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
737 BIO_printf(bio_err, "-----\n");
741 in = bio_open_default(infile, 'r', informat);
745 if (informat == FORMAT_ASN1)
746 req = d2i_X509_REQ_bio(in, NULL);
748 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
750 BIO_printf(bio_err, "unable to load X509 request\n");
755 if (newreq || x509) {
757 BIO_printf(bio_err, "you need to specify a private key\n");
762 req = X509_REQ_new();
767 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
768 subj = NULL; /* done processing '-subj' option */
770 BIO_printf(bio_err, "problems making Certificate Request\n");
777 if ((x509ss = X509_new()) == NULL)
780 /* Set version to V3 */
781 if ((extensions != NULL || addext_conf != NULL)
782 && !X509_set_version(x509ss, 2))
784 if (serial != NULL) {
785 if (!X509_set_serialNumber(x509ss, serial))
788 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
792 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
795 /* set default days if it's not specified */
798 if (!set_cert_times(x509ss, NULL, NULL, days))
800 if (!X509_set_subject_name
801 (x509ss, X509_REQ_get_subject_name(req)))
803 tmppkey = X509_REQ_get0_pubkey(req);
804 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
807 /* Set up V3 context struct */
809 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
810 X509V3_set_nconf(&ext_ctx, req_conf);
813 if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
814 &ext_ctx, extensions,
816 BIO_printf(bio_err, "Error Loading extension section %s\n",
820 if (addext_conf != NULL
821 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
823 BIO_printf(bio_err, "Error Loading command line extensions\n");
827 /* If a pre-cert was requested, we need to add a poison extension */
829 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
831 BIO_printf(bio_err, "Error adding poison extension\n");
836 i = do_X509_sign(x509ss, pkey, digest, sigopts);
838 ERR_print_errors(bio_err);
844 /* Set up V3 context struct */
846 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
847 X509V3_set_nconf(&ext_ctx, req_conf);
851 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
853 BIO_printf(bio_err, "Error Loading extension section %s\n",
857 if (addext_conf != NULL
858 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
860 BIO_printf(bio_err, "Error Loading command line extensions\n");
863 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
865 ERR_print_errors(bio_err);
872 BIO_printf(bio_err, "Cannot modify certificate subject\n");
878 BIO_printf(bio_err, "Modifying Request's Subject\n");
879 print_name(bio_err, "old subject=",
880 X509_REQ_get_subject_name(req), get_nameopt());
883 if (build_subject(req, subj, chtype, multirdn) == 0) {
884 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
890 print_name(bio_err, "new subject=",
891 X509_REQ_get_subject_name(req), get_nameopt());
895 if (verify && !x509) {
896 EVP_PKEY *tpubkey = pkey;
898 if (tpubkey == NULL) {
899 tpubkey = X509_REQ_get0_pubkey(req);
904 if (sm2_id != NULL) {
905 #ifndef OPENSSL_NO_SM2
906 ASN1_OCTET_STRING *v;
908 v = ASN1_OCTET_STRING_new();
910 BIO_printf(bio_err, "error: SM2 ID allocation failed\n");
914 if (!ASN1_OCTET_STRING_set(v, sm2_id, sm2_idlen)) {
915 BIO_printf(bio_err, "error: setting SM2 ID failed\n");
916 ASN1_OCTET_STRING_free(v);
920 X509_REQ_set0_sm2_id(req, v);
924 i = X509_REQ_verify(req, tpubkey);
929 BIO_printf(bio_err, "verify failure\n");
930 ERR_print_errors(bio_err);
931 } else { /* if (i > 0) */
932 BIO_printf(bio_err, "verify OK\n");
936 if (noout && !text && !modulus && !subject && !pubkey) {
941 out = bio_open_default(outfile,
942 keyout != NULL && outfile != NULL &&
943 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
949 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
951 if (tpubkey == NULL) {
952 BIO_printf(bio_err, "Error getting public key\n");
953 ERR_print_errors(bio_err);
956 PEM_write_bio_PUBKEY(out, tpubkey);
961 ret = X509_print_ex(out, x509ss, get_nameopt(), reqflag);
963 ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
967 BIO_printf(bio_err, "Error printing certificate\n");
969 BIO_printf(bio_err, "Error printing certificate request\n");
971 ERR_print_errors(bio_err);
978 print_name(out, "subject=", X509_get_subject_name(x509ss),
981 print_name(out, "subject=", X509_REQ_get_subject_name(req),
989 tpubkey = X509_get0_pubkey(x509ss);
991 tpubkey = X509_REQ_get0_pubkey(req);
992 if (tpubkey == NULL) {
993 fprintf(stdout, "Modulus=unavailable\n");
996 fprintf(stdout, "Modulus=");
997 #ifndef OPENSSL_NO_RSA
998 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
1000 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
1004 fprintf(stdout, "Wrong Algorithm type");
1005 fprintf(stdout, "\n");
1008 if (!noout && !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 X509 request\n");
1020 if (!noout && x509 && (x509ss != NULL)) {
1021 if (outformat == FORMAT_ASN1)
1022 i = i2d_X509_bio(out, x509ss);
1024 i = PEM_write_bio_X509(out, x509ss);
1026 BIO_printf(bio_err, "unable to write X509 certificate\n");
1033 OPENSSL_free(sm2_id);
1035 ERR_print_errors(bio_err);
1037 NCONF_free(req_conf);
1038 NCONF_free(addext_conf);
1039 BIO_free(addext_bio);
1042 EVP_PKEY_free(pkey);
1043 EVP_PKEY_CTX_free(genctx);
1044 sk_OPENSSL_STRING_free(pkeyopts);
1045 sk_OPENSSL_STRING_free(sigopts);
1046 lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
1047 lh_OPENSSL_STRING_free(addexts);
1048 #ifndef OPENSSL_NO_ENGINE
1049 ENGINE_free(gen_eng);
1051 OPENSSL_free(keyalgstr);
1054 ASN1_INTEGER_free(serial);
1056 if (passin != nofree_passin)
1057 OPENSSL_free(passin);
1058 if (passout != nofree_passout)
1059 OPENSSL_free(passout);
1063 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1064 int attribs, unsigned long chtype)
1068 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1069 char *tmp, *dn_sect, *attr_sect;
1071 tmp = NCONF_get_string(req_conf, section, PROMPT);
1074 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1077 dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
1078 if (dn_sect == NULL) {
1079 BIO_printf(bio_err, "unable to find '%s' in config\n",
1080 DISTINGUISHED_NAME);
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);
1089 attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
1090 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 /* setup version number */
1102 if (!X509_REQ_set_version(req, 0L))
1103 goto err; /* version 1 */
1106 i = build_subject(req, subj, chtype, multirdn);
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))
1124 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1125 * where characters may be escaped by \
1127 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
1132 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
1135 if (!X509_REQ_set_subject_name(req, n)) {
1143 static int prompt_info(X509_REQ *req,
1144 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1145 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1146 int attribs, unsigned long chtype)
1157 subj = X509_REQ_get_subject_name(req);
1161 "You are about to be asked to enter information that will be incorporated\n");
1162 BIO_printf(bio_err, "into your certificate request.\n");
1164 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1166 "There are quite a few fields but you can leave some blank\n");
1168 "For some fields there will be a default value,\n");
1170 "If you enter '.', the field will be left blank.\n");
1171 BIO_printf(bio_err, "-----\n");
1174 if (sk_CONF_VALUE_num(dn_sk)) {
1179 if (sk_CONF_VALUE_num(dn_sk) <= i)
1182 v = sk_CONF_VALUE_value(dn_sk, i);
1185 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1186 !check_end(type, "_default") || !check_end(type, "_value"))
1189 * Skip past any leading X. X: X, etc to allow for multiple
1192 for (p = v->name; *p; p++)
1193 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1205 /* If OBJ not recognised ignore it */
1206 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1208 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1210 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1215 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1217 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1222 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1224 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1230 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1232 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1237 if (!add_DN_object(subj, v->value, def, value, nid,
1238 n_min, n_max, chtype, mval))
1241 if (X509_NAME_entry_count(subj) == 0) {
1243 "error, no objects specified in config file\n");
1248 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1251 "\nPlease enter the following 'extra' attributes\n");
1253 "to be sent with your certificate request\n");
1260 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1263 v = sk_CONF_VALUE_value(attr_sk, i);
1265 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1268 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1270 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1276 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1278 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1284 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1286 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1291 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1293 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1298 if (!add_attribute_object(req,
1299 v->value, def, value, nid, n_min,
1305 BIO_printf(bio_err, "No template, please set one up.\n");
1313 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1314 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1315 unsigned long chtype)
1317 int i, spec_char, plus_char;
1323 subj = X509_REQ_get_subject_name(req);
1325 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1327 v = sk_CONF_VALUE_value(dn_sk, i);
1331 * Skip past any leading X. X: X, etc to allow for multiple instances
1333 for (p = v->name; *p; p++) {
1334 #ifndef CHARSET_EBCDIC
1335 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1337 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1338 || (*p == os_toascii['.']));
1347 #ifndef CHARSET_EBCDIC
1348 plus_char = (*type == '+');
1350 plus_char = (*type == os_toascii['+']);
1358 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1359 (unsigned char *)v->value, -1, -1,
1365 if (!X509_NAME_entry_count(subj)) {
1366 BIO_printf(bio_err, "error, no objects specified in config file\n");
1370 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1371 v = sk_CONF_VALUE_value(attr_sk, i);
1372 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1373 (unsigned char *)v->value, -1))
1380 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1381 char *value, int nid, int n_min, int n_max,
1382 unsigned long chtype, int mval)
1387 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1388 "DN value", "DN default");
1389 if ((ret == 0) || (ret == 1))
1393 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1394 (unsigned char *)buf, -1, -1, mval))
1400 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1401 char *value, int nid, int n_min,
1402 int n_max, unsigned long chtype)
1407 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1408 "Attribute value", "Attribute default");
1409 if ((ret == 0) || (ret == 1))
1413 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1414 (unsigned char *)buf, -1)) {
1415 BIO_printf(bio_err, "Error adding attribute\n");
1416 ERR_print_errors(bio_err);
1424 static int build_data(char *text, const char *def,
1425 char *value, int n_min, int n_max,
1426 char *buf, const int buf_size,
1427 const char *desc1, const char *desc2
1433 BIO_printf(bio_err, "%s [%s]:", text, def);
1434 (void)BIO_flush(bio_err);
1435 if (value != NULL) {
1436 if (!join(buf, buf_size, value, "\n", desc1))
1438 BIO_printf(bio_err, "%s\n", value);
1442 if (!fgets(buf, buf_size, stdin))
1452 if (buf[0] == '\n') {
1453 if ((def == NULL) || (def[0] == '\0'))
1455 if (!join(buf, buf_size, def, "\n", desc2))
1457 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1462 if (buf[i - 1] != '\n') {
1463 BIO_printf(bio_err, "weird input :-(\n");
1467 #ifdef CHARSET_EBCDIC
1468 ebcdic2ascii(buf, buf, i);
1470 if (!req_check_len(i, n_min, n_max)) {
1478 static int req_check_len(int len, int n_min, int n_max)
1480 if ((n_min > 0) && (len < n_min)) {
1482 "string is too short, it needs to be at least %d bytes long\n",
1486 if ((n_max >= 0) && (len > n_max)) {
1488 "string is too long, it needs to be no more than %d bytes long\n",
1495 /* Check if the end of a string matches 'end' */
1496 static int check_end(const char *str, const char *end)
1505 tmp = str + slen - elen;
1506 return strcmp(tmp, end);
1510 * Merge the two strings together into the result buffer checking for
1511 * overflow and producing an error message if there is.
1513 static int join(char buf[], size_t buf_size, const char *name,
1514 const char *tail, const char *desc)
1516 const size_t name_len = strlen(name), tail_len = strlen(tail);
1518 if (name_len + tail_len + 1 > buf_size) {
1519 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1522 memcpy(buf, name, name_len);
1523 memcpy(buf + name_len, tail, tail_len + 1);
1527 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1528 int *pkey_type, long *pkeylen,
1529 char **palgnam, ENGINE *keygen_engine)
1531 EVP_PKEY_CTX *gctx = NULL;
1532 EVP_PKEY *param = NULL;
1535 const char *paramfile = NULL;
1538 *pkey_type = EVP_PKEY_RSA;
1540 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1541 *pkey_type = EVP_PKEY_RSA;
1542 keylen = atol(gstr);
1544 } else if (strncmp(gstr, "param:", 6) == 0) {
1545 paramfile = gstr + 6;
1547 const char *p = strchr(gstr, ':');
1550 const EVP_PKEY_ASN1_METHOD *ameth;
1557 * The lookup of a the string will cover all engines so keep a note
1558 * of the implementation.
1561 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1563 if (ameth == NULL) {
1564 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1568 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1569 #ifndef OPENSSL_NO_ENGINE
1570 ENGINE_finish(tmpeng);
1572 if (*pkey_type == EVP_PKEY_RSA) {
1574 keylen = atol(p + 1);
1579 } else if (p != NULL) {
1584 if (paramfile != NULL) {
1585 pbio = BIO_new_file(paramfile, "r");
1587 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1590 param = PEM_read_bio_Parameters(pbio, NULL);
1592 if (param == NULL) {
1595 (void)BIO_reset(pbio);
1596 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1598 param = X509_get_pubkey(x);
1605 if (param == NULL) {
1606 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1609 if (*pkey_type == -1) {
1610 *pkey_type = EVP_PKEY_id(param);
1611 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1612 BIO_printf(bio_err, "Key Type does not match parameters\n");
1613 EVP_PKEY_free(param);
1618 if (palgnam != NULL) {
1619 const EVP_PKEY_ASN1_METHOD *ameth;
1623 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1624 if (ameth == NULL) {
1625 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1628 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1629 *palgnam = OPENSSL_strdup(anam);
1630 #ifndef OPENSSL_NO_ENGINE
1631 ENGINE_finish(tmpeng);
1635 if (param != NULL) {
1636 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1637 *pkeylen = EVP_PKEY_bits(param);
1638 EVP_PKEY_free(param);
1640 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1644 BIO_puts(bio_err, "Error allocating keygen context\n");
1645 ERR_print_errors(bio_err);
1649 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1650 BIO_puts(bio_err, "Error initializing keygen context\n");
1651 ERR_print_errors(bio_err);
1652 EVP_PKEY_CTX_free(gctx);
1655 #ifndef OPENSSL_NO_RSA
1656 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1657 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1658 BIO_puts(bio_err, "Error setting RSA keysize\n");
1659 ERR_print_errors(bio_err);
1660 EVP_PKEY_CTX_free(gctx);
1669 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1672 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1674 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1683 BIO_write(b, &c, 1);
1688 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
1695 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1696 char *opt = sk_OPENSSL_STRING_value(opts, i);
1697 if (x509_req_ctrl_string(x, opt) <= 0) {
1698 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1699 ERR_print_errors(bio_err);
1707 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1708 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1710 EVP_PKEY_CTX *pkctx = NULL;
1711 EVP_PKEY_CTX *pctx = NULL;
1712 int i, def_nid, ret = 0;
1716 if (EVP_PKEY_id(pkey) == EVP_PKEY_SM2) {
1717 pctx = EVP_PKEY_CTX_new(pkey, NULL);
1719 BIO_printf(bio_err, "memory allocation failure.\n");
1722 /* set SM2 ID from sig options before calling the real init routine */
1723 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1724 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1725 if (pkey_ctrl_string(pctx, sigopt) <= 0) {
1726 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1727 ERR_print_errors(bio_err);
1731 EVP_MD_CTX_set_pkey_ctx(ctx, pctx);
1734 * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is mandatory
1735 * for this algorithm.
1737 if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) == 2
1738 && def_nid == NID_undef) {
1739 /* The signing algorithm requires there to be no digest */
1742 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1744 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1745 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1746 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1747 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1748 ERR_print_errors(bio_err);
1756 EVP_PKEY_CTX_free(pctx);
1760 static void do_sign_cleanup(EVP_MD_CTX *ctx, EVP_PKEY *pkey)
1763 * With SM2, do_sign_init() attached an EVP_PKEY_CTX to the EVP_MD_CTX,
1764 * and we have to free it explicitly.
1766 if (EVP_PKEY_id(pkey) == EVP_PKEY_SM2) {
1767 EVP_PKEY_CTX *pctx = EVP_MD_CTX_pkey_ctx(ctx);
1769 EVP_MD_CTX_set_pkey_ctx(ctx, NULL);
1770 EVP_PKEY_CTX_free(pctx);
1774 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1775 STACK_OF(OPENSSL_STRING) *sigopts)
1778 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1780 if (do_sign_init(mctx, pkey, md, sigopts) > 0) {
1781 rv = (X509_sign_ctx(x, mctx) > 0);
1782 do_sign_cleanup(mctx, pkey);
1784 EVP_MD_CTX_free(mctx);
1788 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1789 STACK_OF(OPENSSL_STRING) *sigopts)
1792 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1794 if (do_sign_init(mctx, pkey, md, sigopts) > 0) {
1795 rv = (X509_REQ_sign_ctx(x, mctx) > 0);
1796 do_sign_cleanup(mctx, pkey);
1798 EVP_MD_CTX_free(mctx);
1802 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
1803 STACK_OF(OPENSSL_STRING) *vfyopts)
1807 if (do_x509_req_init(x, vfyopts) > 0)
1808 rv = (X509_REQ_verify(x, pkey) > 0);
1812 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1813 STACK_OF(OPENSSL_STRING) *sigopts)
1816 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1818 if (do_sign_init(mctx, pkey, md, sigopts) > 0) {
1819 rv = (X509_CRL_sign_ctx(x, mctx) > 0);
1820 do_sign_cleanup(mctx, pkey);
1822 EVP_MD_CTX_free(mctx);