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>
37 #define BITS "default_bits"
38 #define KEYFILE "default_keyfile"
39 #define PROMPT "prompt"
40 #define DISTINGUISHED_NAME "distinguished_name"
41 #define ATTRIBUTES "attributes"
42 #define V3_EXTENSIONS "x509_extensions"
43 #define REQ_EXTENSIONS "req_extensions"
44 #define STRING_MASK "string_mask"
45 #define UTF8_IN "utf8"
47 #define DEFAULT_KEY_LENGTH 2048
48 #define MIN_KEY_LENGTH 512
50 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
51 int attribs, unsigned long chtype);
52 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
54 static int prompt_info(X509_REQ *req,
55 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
56 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
57 int attribs, unsigned long chtype);
58 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
59 STACK_OF(CONF_VALUE) *attr, int attribs,
60 unsigned long chtype);
61 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
62 char *value, int nid, int n_min, int n_max,
63 unsigned long chtype);
64 static int add_DN_object(X509_NAME *n, char *text, const char *def,
65 char *value, int nid, int n_min, int n_max,
66 unsigned long chtype, int mval);
67 static int genpkey_cb(EVP_PKEY_CTX *ctx);
68 static int build_data(char *text, const char *def,
69 char *value, int n_min, int n_max,
70 char *buf, const int buf_size,
71 const char *desc1, const char *desc2
73 static int req_check_len(int len, int n_min, int n_max);
74 static int check_end(const char *str, const char *end);
75 static int join(char buf[], size_t buf_size, const char *name,
76 const char *tail, const char *desc);
77 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
78 int *pkey_type, long *pkeylen,
79 char **palgnam, ENGINE *keygen_engine);
80 static CONF *req_conf = NULL;
81 static CONF *addext_conf = NULL;
84 typedef enum OPTION_choice {
85 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
86 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
87 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
88 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
89 OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
90 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
91 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
92 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
93 OPT_REQEXTS, OPT_PRECERT, OPT_MD, OPT_SM2ID, OPT_SM2HEXID,
94 OPT_R_ENUM, OPT_PROV_ENUM
97 const OPTIONS req_options[] = {
98 OPT_SECTION("General"),
99 {"help", OPT_HELP, '-', "Display this summary"},
100 #ifndef OPENSSL_NO_ENGINE
101 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
102 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
103 "Specify engine to be used for key generation operations"},
105 {"in", OPT_IN, '<', "Input file"},
106 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
107 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
109 OPT_SECTION("Certificate"),
110 {"new", OPT_NEW, '-', "New request"},
111 {"config", OPT_CONFIG, '<', "Request template file"},
112 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
113 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
114 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
115 {"text", OPT_TEXT, '-', "Text form of request"},
116 {"x509", OPT_X509, '-',
117 "Output an x509 structure instead of a cert request"},
118 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
119 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
120 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
121 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
122 "Enable support for multivalued RDNs"},
123 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
124 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
125 {"addext", OPT_ADDEXT, 's',
126 "Additional cert extension key=value pair (may be given more than once)"},
127 {"extensions", OPT_EXTENSIONS, 's',
128 "Cert extension section (override value in config file)"},
129 {"reqexts", OPT_REQEXTS, 's',
130 "Request extension section (override value in config file)"},
131 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
133 OPT_SECTION("Keys and Signing"),
134 {"key", OPT_KEY, 's', "Private key to use"},
135 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
136 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
137 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
138 {"passin", OPT_PASSIN, 's', "Private key password source"},
139 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
140 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
141 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
142 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
143 {"", OPT_MD, '-', "Any supported digest"},
144 #ifndef OPENSSL_NO_SM2
145 {"sm2-id", OPT_SM2ID, 's',
146 "Specify an ID string to verify an SM2 certificate request"},
147 {"sm2-hex-id", OPT_SM2HEXID, 's',
148 "Specify a hex ID string to verify an SM2 certificate request"},
151 OPT_SECTION("Output"),
152 {"out", OPT_OUT, '>', "Output file"},
153 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
154 {"batch", OPT_BATCH, '-',
155 "Do not ask anything during request generation"},
156 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
157 {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
158 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
159 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
160 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
169 * An LHASH of strings, where each string is an extension name.
171 static unsigned long ext_name_hash(const OPENSSL_STRING *a)
173 return OPENSSL_LH_strhash((const char *)a);
176 static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
178 return strcmp((const char *)a, (const char *)b);
181 static void exts_cleanup(OPENSSL_STRING *x)
183 OPENSSL_free((char *)x);
187 * Is the |kv| key already duplicated? This is remarkably tricky to get
188 * right. Return 0 if unique, -1 on runtime error; 1 if found or a syntax
191 static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
197 /* Skip leading whitespace, make a copy. */
198 while (*kv && isspace(*kv))
201 if ((p = strchr(kv, '=')) == NULL)
204 if ((kv = OPENSSL_strdup(kv)) == NULL)
207 /* Skip trailing space before the equal sign. */
208 for (p = kv + off; p > kv; --p)
217 /* Finally have a clean "key"; see if it's there [by attempt to add it]. */
218 p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING*)kv);
222 } else if (lh_OPENSSL_STRING_error(addexts)) {
230 int req_main(int argc, char **argv)
232 ASN1_INTEGER *serial = NULL;
233 BIO *in = NULL, *out = NULL;
234 ENGINE *e = NULL, *gen_eng = NULL;
235 EVP_PKEY *pkey = NULL;
236 EVP_PKEY_CTX *genctx = NULL;
237 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
238 LHASH_OF(OPENSSL_STRING) *addexts = NULL;
240 X509_REQ *req = NULL;
241 const EVP_CIPHER *cipher = NULL;
242 const EVP_MD *md_alg = NULL, *digest = NULL;
243 BIO *addext_bio = NULL;
244 char *extensions = NULL, *infile = NULL;
245 char *outfile = NULL, *keyfile = NULL;
246 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
247 char *passin = NULL, *passout = NULL;
248 char *nofree_passin = NULL, *nofree_passout = NULL;
249 char *req_exts = NULL, *subj = NULL;
250 char *template = default_config_file, *keyout = NULL;
251 const char *keyalg = NULL;
253 int ret = 1, x509 = 0, days = 0, i = 0, newreq = 0, verbose = 0;
254 int pkey_type = -1, private = 0;
255 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
256 int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
257 int nodes = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
259 unsigned long chtype = MBSTRING_ASC, reqflag = 0;
260 unsigned char *sm2_id = NULL;
261 size_t sm2_idlen = 0;
264 #ifndef OPENSSL_NO_DES
265 cipher = EVP_des_ede3_cbc();
268 prog = opt_init(argc, argv, req_options);
269 while ((o = opt_next()) != OPT_EOF) {
274 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
277 opt_help(req_options);
281 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
285 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
289 e = setup_engine(opt_arg(), 0);
291 case OPT_KEYGEN_ENGINE:
292 #ifndef OPENSSL_NO_ENGINE
293 gen_eng = ENGINE_by_id(opt_arg());
294 if (gen_eng == NULL) {
295 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
310 template = opt_arg();
313 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
326 passargin = opt_arg();
329 passargout = opt_arg();
336 if (!opt_provider(o))
344 if (pkeyopts == NULL)
345 pkeyopts = sk_OPENSSL_STRING_new_null();
347 || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
352 sigopts = sk_OPENSSL_STRING_new_null();
353 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
378 chtype = MBSTRING_UTF8;
381 if (!set_nameopt(opt_arg()))
385 if (!set_cert_ex(&reqflag, opt_arg()))
395 days = atoi(opt_arg());
398 if (serial != NULL) {
399 BIO_printf(bio_err, "Serial number supplied twice\n");
402 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
412 case OPT_MULTIVALUE_RDN:
417 if (addexts == NULL) {
418 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
419 addext_bio = BIO_new(BIO_s_mem());
420 if (addexts == NULL || addext_bio == NULL)
423 i = duplicated(addexts, p);
426 if (i < 0 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
430 extensions = opt_arg();
433 req_exts = opt_arg();
436 newreq = precert = 1;
439 if (!opt_md(opt_unknown(), &md_alg))
444 if (sm2_id != NULL) {
446 "Use one of the options 'sm2-hex-id' or 'sm2-id'\n");
449 sm2_id = (unsigned char *)opt_arg();
450 sm2_idlen = strlen((const char *)sm2_id);
453 if (sm2_id != NULL) {
455 "Use one of the options 'sm2-hex-id' or 'sm2-id'\n");
458 /* try to parse the input as hex string first */
460 sm2_id = OPENSSL_hexstr2buf(opt_arg(), (long *)&sm2_idlen);
461 if (sm2_id == NULL) {
462 BIO_printf(bio_err, "Invalid hex string input\n");
468 argc = opt_num_rest();
473 BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
474 if (x509 && infile == NULL)
477 /* TODO: simplify this as pkey is still always NULL here */
478 private = newreq && (pkey == NULL) ? 1 : 0;
480 if (!app_passwd(passargin, passargout, &passin, &passout)) {
481 BIO_printf(bio_err, "Error getting passwords\n");
486 BIO_printf(bio_err, "Using configuration from %s\n", template);
487 if ((req_conf = app_load_config(template)) == NULL)
492 "Using additional configuration from command line\n");
493 if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
496 if (template != default_config_file && !app_load_modules(req_conf))
499 if (req_conf != NULL) {
500 p = NCONF_get_string(req_conf, NULL, "oid_file");
506 oid_bio = BIO_new_file(p, "r");
507 if (oid_bio == NULL) {
509 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
510 ERR_print_errors(bio_err);
513 OBJ_create_objects(oid_bio);
518 if (!add_oid_section(req_conf))
521 if (md_alg == NULL) {
522 p = NCONF_get_string(req_conf, SECTION, "default_md");
526 if (!opt_md(p, &md_alg))
532 if (extensions == NULL) {
533 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
534 if (extensions == NULL)
537 if (extensions != NULL) {
538 /* Check syntax of file */
540 X509V3_set_ctx_test(&ctx);
541 X509V3_set_nconf(&ctx, req_conf);
542 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
544 "Error Loading extension section %s\n", extensions);
548 if (addext_conf != NULL) {
549 /* Check syntax of command line extensions */
551 X509V3_set_ctx_test(&ctx);
552 X509V3_set_nconf(&ctx, addext_conf);
553 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
554 BIO_printf(bio_err, "Error Loading command line extensions\n");
559 if (passin == NULL) {
560 passin = nofree_passin =
561 NCONF_get_string(req_conf, SECTION, "input_password");
566 if (passout == NULL) {
567 passout = nofree_passout =
568 NCONF_get_string(req_conf, SECTION, "output_password");
573 p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
577 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
578 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
582 if (chtype != MBSTRING_UTF8) {
583 p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
586 else if (strcmp(p, "yes") == 0)
587 chtype = MBSTRING_UTF8;
590 if (req_exts == NULL) {
591 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
592 if (req_exts == NULL)
595 if (req_exts != NULL) {
596 /* Check syntax of file */
598 X509V3_set_ctx_test(&ctx);
599 X509V3_set_nconf(&ctx, req_conf);
600 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
602 "Error Loading request extension section %s\n",
608 if (keyfile != NULL) {
609 pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
611 /* load_key() has already printed an appropriate message */
614 app_RAND_load_conf(req_conf, SECTION);
618 if (newreq && (pkey == NULL)) {
619 app_RAND_load_conf(req_conf, SECTION);
621 if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
622 newkey = DEFAULT_KEY_LENGTH;
625 if (keyalg != NULL) {
626 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
627 &keyalgstr, gen_eng);
632 if (newkey < MIN_KEY_LENGTH
633 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
634 BIO_printf(bio_err, "private key length is too short,\n");
635 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
636 MIN_KEY_LENGTH, newkey);
640 if (pkey_type == EVP_PKEY_RSA && newkey > OPENSSL_RSA_MAX_MODULUS_BITS)
642 "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
643 " Your key size is %ld! Larger key size may behave not as expected.\n",
644 OPENSSL_RSA_MAX_MODULUS_BITS, newkey);
646 #ifndef OPENSSL_NO_DSA
647 if (pkey_type == EVP_PKEY_DSA && newkey > OPENSSL_DSA_MAX_MODULUS_BITS)
649 "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
650 " Your key size is %ld! Larger key size may behave not as expected.\n",
651 OPENSSL_DSA_MAX_MODULUS_BITS, newkey);
654 if (genctx == NULL) {
655 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
656 &keyalgstr, gen_eng);
661 if (pkeyopts != NULL) {
663 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
664 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
665 if (pkey_ctrl_string(genctx, genopt) <= 0) {
666 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
667 ERR_print_errors(bio_err);
673 if (pkey_type == EVP_PKEY_EC) {
674 BIO_printf(bio_err, "Generating an EC private key\n");
676 BIO_printf(bio_err, "Generating a %s private key\n", keyalgstr);
679 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
680 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
682 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
683 BIO_puts(bio_err, "Error Generating Key\n");
687 EVP_PKEY_CTX_free(genctx);
690 if (keyout == NULL) {
691 keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
697 BIO_printf(bio_err, "writing new private key to stdout\n");
699 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
700 out = bio_open_owner(keyout, outformat, private);
704 p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
707 p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
711 if ((p != NULL) && (strcmp(p, "no") == 0))
719 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
720 NULL, 0, NULL, passout)) {
721 if ((ERR_GET_REASON(ERR_peek_error()) ==
722 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
731 BIO_printf(bio_err, "-----\n");
735 in = bio_open_default(infile, 'r', informat);
739 if (informat == FORMAT_ASN1)
740 req = d2i_X509_REQ_bio(in, NULL);
742 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
744 BIO_printf(bio_err, "unable to load X509 request\n");
749 if (newreq || x509) {
751 BIO_printf(bio_err, "you need to specify a private key\n");
756 req = X509_REQ_new();
761 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
762 subj = NULL; /* done processing '-subj' option */
764 BIO_printf(bio_err, "problems making Certificate Request\n");
771 if ((x509ss = X509_new()) == NULL)
774 /* Set version to V3 */
775 if ((extensions != NULL || addext_conf != NULL)
776 && !X509_set_version(x509ss, 2))
778 if (serial != NULL) {
779 if (!X509_set_serialNumber(x509ss, serial))
782 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
786 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
789 /* set default days if it's not specified */
792 if (!set_cert_times(x509ss, NULL, NULL, days))
794 if (!X509_set_subject_name
795 (x509ss, X509_REQ_get_subject_name(req)))
797 tmppkey = X509_REQ_get0_pubkey(req);
798 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
801 /* Set up V3 context struct */
803 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
804 X509V3_set_nconf(&ext_ctx, req_conf);
807 if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
808 &ext_ctx, extensions,
810 BIO_printf(bio_err, "Error Loading extension section %s\n",
814 if (addext_conf != NULL
815 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
817 BIO_printf(bio_err, "Error Loading command line extensions\n");
821 /* If a pre-cert was requested, we need to add a poison extension */
823 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
825 BIO_printf(bio_err, "Error adding poison extension\n");
830 i = do_X509_sign(x509ss, pkey, digest, sigopts);
832 ERR_print_errors(bio_err);
838 /* Set up V3 context struct */
840 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
841 X509V3_set_nconf(&ext_ctx, req_conf);
845 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
847 BIO_printf(bio_err, "Error Loading extension section %s\n",
851 if (addext_conf != NULL
852 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
854 BIO_printf(bio_err, "Error Loading command line extensions\n");
857 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
859 ERR_print_errors(bio_err);
866 BIO_printf(bio_err, "Cannot modify certificate subject\n");
872 BIO_printf(bio_err, "Modifying Request's Subject\n");
873 print_name(bio_err, "old subject=",
874 X509_REQ_get_subject_name(req), get_nameopt());
877 if (build_subject(req, subj, chtype, multirdn) == 0) {
878 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
884 print_name(bio_err, "new subject=",
885 X509_REQ_get_subject_name(req), get_nameopt());
889 if (verify && !x509) {
890 EVP_PKEY *tpubkey = pkey;
892 if (tpubkey == NULL) {
893 tpubkey = X509_REQ_get0_pubkey(req);
898 if (sm2_id != NULL) {
899 #ifndef OPENSSL_NO_SM2
900 ASN1_OCTET_STRING *v;
902 v = ASN1_OCTET_STRING_new();
904 BIO_printf(bio_err, "error: SM2 ID allocation failed\n");
908 if (!ASN1_OCTET_STRING_set(v, sm2_id, sm2_idlen)) {
909 BIO_printf(bio_err, "error: setting SM2 ID failed\n");
910 ASN1_OCTET_STRING_free(v);
914 X509_REQ_set0_sm2_id(req, v);
918 i = X509_REQ_verify(req, tpubkey);
923 BIO_printf(bio_err, "verify failure\n");
924 ERR_print_errors(bio_err);
925 } else { /* if (i > 0) */
926 BIO_printf(bio_err, "verify OK\n");
930 if (noout && !text && !modulus && !subject && !pubkey) {
935 out = bio_open_default(outfile,
936 keyout != NULL && outfile != NULL &&
937 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
943 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
945 if (tpubkey == NULL) {
946 BIO_printf(bio_err, "Error getting public key\n");
947 ERR_print_errors(bio_err);
950 PEM_write_bio_PUBKEY(out, tpubkey);
955 ret = X509_print_ex(out, x509ss, get_nameopt(), reqflag);
957 ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
961 BIO_printf(bio_err, "Error printing certificate\n");
963 BIO_printf(bio_err, "Error printing certificate request\n");
965 ERR_print_errors(bio_err);
972 print_name(out, "subject=", X509_get_subject_name(x509ss),
975 print_name(out, "subject=", X509_REQ_get_subject_name(req),
983 tpubkey = X509_get0_pubkey(x509ss);
985 tpubkey = X509_REQ_get0_pubkey(req);
986 if (tpubkey == NULL) {
987 fprintf(stdout, "Modulus=unavailable\n");
990 fprintf(stdout, "Modulus=");
991 #ifndef OPENSSL_NO_RSA
992 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
994 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
998 fprintf(stdout, "Wrong Algorithm type");
999 fprintf(stdout, "\n");
1002 if (!noout && !x509) {
1003 if (outformat == FORMAT_ASN1)
1004 i = i2d_X509_REQ_bio(out, req);
1006 i = PEM_write_bio_X509_REQ_NEW(out, req);
1008 i = PEM_write_bio_X509_REQ(out, req);
1010 BIO_printf(bio_err, "unable to write X509 request\n");
1014 if (!noout && x509 && (x509ss != NULL)) {
1015 if (outformat == FORMAT_ASN1)
1016 i = i2d_X509_bio(out, x509ss);
1018 i = PEM_write_bio_X509(out, x509ss);
1020 BIO_printf(bio_err, "unable to write X509 certificate\n");
1027 OPENSSL_free(sm2_id);
1029 ERR_print_errors(bio_err);
1031 NCONF_free(req_conf);
1032 NCONF_free(addext_conf);
1033 BIO_free(addext_bio);
1036 EVP_PKEY_free(pkey);
1037 EVP_PKEY_CTX_free(genctx);
1038 sk_OPENSSL_STRING_free(pkeyopts);
1039 sk_OPENSSL_STRING_free(sigopts);
1040 lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
1041 lh_OPENSSL_STRING_free(addexts);
1042 #ifndef OPENSSL_NO_ENGINE
1043 ENGINE_free(gen_eng);
1045 OPENSSL_free(keyalgstr);
1048 ASN1_INTEGER_free(serial);
1050 if (passin != nofree_passin)
1051 OPENSSL_free(passin);
1052 if (passout != nofree_passout)
1053 OPENSSL_free(passout);
1057 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1058 int attribs, unsigned long chtype)
1062 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1063 char *tmp, *dn_sect, *attr_sect;
1065 tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
1068 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1071 dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
1072 if (dn_sect == NULL) {
1073 BIO_printf(bio_err, "unable to find '%s' in config\n",
1074 DISTINGUISHED_NAME);
1077 dn_sk = NCONF_get_section(req_conf, dn_sect);
1078 if (dn_sk == NULL) {
1079 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
1083 attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
1084 if (attr_sect == NULL) {
1088 attr_sk = NCONF_get_section(req_conf, attr_sect);
1089 if (attr_sk == NULL) {
1090 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
1095 /* setup version number */
1096 if (!X509_REQ_set_version(req, 0L))
1097 goto err; /* version 1 */
1100 i = build_subject(req, subj, chtype, multirdn);
1102 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1104 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1109 if (!X509_REQ_set_pubkey(req, pkey))
1118 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1119 * where characters may be escaped by \
1121 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
1126 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
1129 if (!X509_REQ_set_subject_name(req, n)) {
1137 static int prompt_info(X509_REQ *req,
1138 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1139 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1140 int attribs, unsigned long chtype)
1151 subj = X509_REQ_get_subject_name(req);
1155 "You are about to be asked to enter information that will be incorporated\n");
1156 BIO_printf(bio_err, "into your certificate request.\n");
1158 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1160 "There are quite a few fields but you can leave some blank\n");
1162 "For some fields there will be a default value,\n");
1164 "If you enter '.', the field will be left blank.\n");
1165 BIO_printf(bio_err, "-----\n");
1168 if (sk_CONF_VALUE_num(dn_sk)) {
1173 if (sk_CONF_VALUE_num(dn_sk) <= i)
1176 v = sk_CONF_VALUE_value(dn_sk, i);
1179 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1180 !check_end(type, "_default") || !check_end(type, "_value"))
1183 * Skip past any leading X. X: X, etc to allow for multiple
1186 for (p = v->name; *p; p++)
1187 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1199 /* If OBJ not recognised ignore it */
1200 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1202 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1204 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1209 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1211 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1216 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1218 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1224 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1226 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1231 if (!add_DN_object(subj, v->value, def, value, nid,
1232 n_min, n_max, chtype, mval))
1235 if (X509_NAME_entry_count(subj) == 0) {
1237 "error, no objects specified in config file\n");
1242 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1245 "\nPlease enter the following 'extra' attributes\n");
1247 "to be sent with your certificate request\n");
1254 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1257 v = sk_CONF_VALUE_value(attr_sk, i);
1259 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1262 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1264 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1270 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1272 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1278 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1280 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1285 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1287 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1292 if (!add_attribute_object(req,
1293 v->value, def, value, nid, n_min,
1299 BIO_printf(bio_err, "No template, please set one up.\n");
1307 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1308 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1309 unsigned long chtype)
1311 int i, spec_char, plus_char;
1317 subj = X509_REQ_get_subject_name(req);
1319 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1321 v = sk_CONF_VALUE_value(dn_sk, i);
1325 * Skip past any leading X. X: X, etc to allow for multiple instances
1327 for (p = v->name; *p; p++) {
1328 #ifndef CHARSET_EBCDIC
1329 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1331 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1332 || (*p == os_toascii['.']));
1341 #ifndef CHARSET_EBCDIC
1342 plus_char = (*type == '+');
1344 plus_char = (*type == os_toascii['+']);
1352 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1353 (unsigned char *)v->value, -1, -1,
1359 if (!X509_NAME_entry_count(subj)) {
1360 BIO_printf(bio_err, "error, no objects specified in config file\n");
1364 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1365 v = sk_CONF_VALUE_value(attr_sk, i);
1366 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1367 (unsigned char *)v->value, -1))
1374 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1375 char *value, int nid, int n_min, int n_max,
1376 unsigned long chtype, int mval)
1381 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1382 "DN value", "DN default");
1383 if ((ret == 0) || (ret == 1))
1387 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1388 (unsigned char *)buf, -1, -1, mval))
1394 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1395 char *value, int nid, int n_min,
1396 int n_max, unsigned long chtype)
1401 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1402 "Attribute value", "Attribute default");
1403 if ((ret == 0) || (ret == 1))
1407 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1408 (unsigned char *)buf, -1)) {
1409 BIO_printf(bio_err, "Error adding attribute\n");
1410 ERR_print_errors(bio_err);
1418 static int build_data(char *text, const char *def,
1419 char *value, int n_min, int n_max,
1420 char *buf, const int buf_size,
1421 const char *desc1, const char *desc2
1427 BIO_printf(bio_err, "%s [%s]:", text, def);
1428 (void)BIO_flush(bio_err);
1429 if (value != NULL) {
1430 if (!join(buf, buf_size, value, "\n", desc1))
1432 BIO_printf(bio_err, "%s\n", value);
1436 if (!fgets(buf, buf_size, stdin))
1446 if (buf[0] == '\n') {
1447 if ((def == NULL) || (def[0] == '\0'))
1449 if (!join(buf, buf_size, def, "\n", desc2))
1451 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1456 if (buf[i - 1] != '\n') {
1457 BIO_printf(bio_err, "weird input :-(\n");
1461 #ifdef CHARSET_EBCDIC
1462 ebcdic2ascii(buf, buf, i);
1464 if (!req_check_len(i, n_min, n_max)) {
1472 static int req_check_len(int len, int n_min, int n_max)
1474 if ((n_min > 0) && (len < n_min)) {
1476 "string is too short, it needs to be at least %d bytes long\n",
1480 if ((n_max >= 0) && (len > n_max)) {
1482 "string is too long, it needs to be no more than %d bytes long\n",
1489 /* Check if the end of a string matches 'end' */
1490 static int check_end(const char *str, const char *end)
1499 tmp = str + slen - elen;
1500 return strcmp(tmp, end);
1504 * Merge the two strings together into the result buffer checking for
1505 * overflow and producing an error message if there is.
1507 static int join(char buf[], size_t buf_size, const char *name,
1508 const char *tail, const char *desc)
1510 const size_t name_len = strlen(name), tail_len = strlen(tail);
1512 if (name_len + tail_len + 1 > buf_size) {
1513 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1516 memcpy(buf, name, name_len);
1517 memcpy(buf + name_len, tail, tail_len + 1);
1521 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1522 int *pkey_type, long *pkeylen,
1523 char **palgnam, ENGINE *keygen_engine)
1525 EVP_PKEY_CTX *gctx = NULL;
1526 EVP_PKEY *param = NULL;
1529 const char *paramfile = NULL;
1532 *pkey_type = EVP_PKEY_RSA;
1534 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1535 *pkey_type = EVP_PKEY_RSA;
1536 keylen = atol(gstr);
1538 } else if (strncmp(gstr, "param:", 6) == 0) {
1539 paramfile = gstr + 6;
1541 const char *p = strchr(gstr, ':');
1544 const EVP_PKEY_ASN1_METHOD *ameth;
1551 * The lookup of a the string will cover all engines so keep a note
1552 * of the implementation.
1555 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1557 if (ameth == NULL) {
1558 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1562 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1563 #ifndef OPENSSL_NO_ENGINE
1564 ENGINE_finish(tmpeng);
1566 if (*pkey_type == EVP_PKEY_RSA) {
1568 keylen = atol(p + 1);
1573 } else if (p != NULL) {
1578 if (paramfile != NULL) {
1579 pbio = BIO_new_file(paramfile, "r");
1581 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1584 param = PEM_read_bio_Parameters(pbio, NULL);
1586 if (param == NULL) {
1589 (void)BIO_reset(pbio);
1590 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1592 param = X509_get_pubkey(x);
1599 if (param == NULL) {
1600 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1603 if (*pkey_type == -1) {
1604 *pkey_type = EVP_PKEY_id(param);
1605 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1606 BIO_printf(bio_err, "Key Type does not match parameters\n");
1607 EVP_PKEY_free(param);
1612 if (palgnam != NULL) {
1613 const EVP_PKEY_ASN1_METHOD *ameth;
1617 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1618 if (ameth == NULL) {
1619 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1622 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1623 *palgnam = OPENSSL_strdup(anam);
1624 #ifndef OPENSSL_NO_ENGINE
1625 ENGINE_finish(tmpeng);
1629 if (param != NULL) {
1630 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1631 *pkeylen = EVP_PKEY_bits(param);
1632 EVP_PKEY_free(param);
1634 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1638 BIO_puts(bio_err, "Error allocating keygen context\n");
1639 ERR_print_errors(bio_err);
1643 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1644 BIO_puts(bio_err, "Error initializing keygen context\n");
1645 ERR_print_errors(bio_err);
1646 EVP_PKEY_CTX_free(gctx);
1649 #ifndef OPENSSL_NO_RSA
1650 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1651 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1652 BIO_puts(bio_err, "Error setting RSA keysize\n");
1653 ERR_print_errors(bio_err);
1654 EVP_PKEY_CTX_free(gctx);
1663 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1666 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1668 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1677 BIO_write(b, &c, 1);
1682 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1683 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1685 EVP_PKEY_CTX *pkctx = NULL;
1686 EVP_PKEY_CTX *pctx = NULL;
1687 int i, def_nid, ret = 0;
1691 if (EVP_PKEY_id(pkey) == EVP_PKEY_SM2) {
1692 pctx = EVP_PKEY_CTX_new(pkey, NULL);
1694 BIO_printf(bio_err, "memory allocation failure.\n");
1697 /* set SM2 ID from sig options before calling the real init routine */
1698 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1699 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1700 if (pkey_ctrl_string(pctx, sigopt) <= 0) {
1701 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1702 ERR_print_errors(bio_err);
1706 EVP_MD_CTX_set_pkey_ctx(ctx, pctx);
1709 * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is mandatory
1710 * for this algorithm.
1712 if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) == 2
1713 && def_nid == NID_undef) {
1714 /* The signing algorithm requires there to be no digest */
1717 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1719 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1720 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1721 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1722 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1723 ERR_print_errors(bio_err);
1731 EVP_PKEY_CTX_free(pctx);
1735 static void do_sign_cleanup(EVP_MD_CTX *ctx, EVP_PKEY *pkey)
1738 * With SM2, do_sign_init() attached an EVP_PKEY_CTX to the EVP_MD_CTX,
1739 * and we have to free it explicitly.
1741 if (EVP_PKEY_id(pkey) == EVP_PKEY_SM2) {
1742 EVP_PKEY_CTX *pctx = EVP_MD_CTX_pkey_ctx(ctx);
1744 EVP_MD_CTX_set_pkey_ctx(ctx, NULL);
1745 EVP_PKEY_CTX_free(pctx);
1749 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1750 STACK_OF(OPENSSL_STRING) *sigopts)
1753 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1755 if (do_sign_init(mctx, pkey, md, sigopts) > 0) {
1756 rv = (X509_sign_ctx(x, mctx) > 0);
1757 do_sign_cleanup(mctx, pkey);
1759 EVP_MD_CTX_free(mctx);
1763 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1764 STACK_OF(OPENSSL_STRING) *sigopts)
1767 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1769 if (do_sign_init(mctx, pkey, md, sigopts) > 0) {
1770 rv = (X509_REQ_sign_ctx(x, mctx) > 0);
1771 do_sign_cleanup(mctx, pkey);
1773 EVP_MD_CTX_free(mctx);
1777 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1778 STACK_OF(OPENSSL_STRING) *sigopts)
1781 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1783 if (do_sign_init(mctx, pkey, md, sigopts) > 0) {
1784 rv = (X509_CRL_sign_ctx(x, mctx) > 0);
1785 do_sign_cleanup(mctx, pkey);
1787 EVP_MD_CTX_free(mctx);