2 * Copyright 1995-2020 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>
35 DEFINE_STACK_OF(CONF_VALUE)
36 DEFINE_STACK_OF_STRING()
38 #define BITS "default_bits"
39 #define KEYFILE "default_keyfile"
40 #define PROMPT "prompt"
41 #define DISTINGUISHED_NAME "distinguished_name"
42 #define ATTRIBUTES "attributes"
43 #define V3_EXTENSIONS "x509_extensions"
44 #define REQ_EXTENSIONS "req_extensions"
45 #define STRING_MASK "string_mask"
46 #define UTF8_IN "utf8"
48 #define DEFAULT_KEY_LENGTH 2048
49 #define MIN_KEY_LENGTH 512
51 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
52 int attribs, unsigned long chtype);
53 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
55 static int prompt_info(X509_REQ *req,
56 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
57 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
58 int attribs, unsigned long chtype);
59 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
60 STACK_OF(CONF_VALUE) *attr, int attribs,
61 unsigned long chtype);
62 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
63 char *value, int nid, int n_min, int n_max,
64 unsigned long chtype);
65 static int add_DN_object(X509_NAME *n, char *text, const char *def,
66 char *value, int nid, int n_min, int n_max,
67 unsigned long chtype, int mval);
68 static int genpkey_cb(EVP_PKEY_CTX *ctx);
69 static int build_data(char *text, const char *def,
70 char *value, int n_min, int n_max,
71 char *buf, const int buf_size,
72 const char *desc1, const char *desc2
74 static int req_check_len(int len, int n_min, int n_max);
75 static int check_end(const char *str, const char *end);
76 static int join(char buf[], size_t buf_size, const char *name,
77 const char *tail, const char *desc);
78 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
79 int *pkey_type, long *pkeylen,
80 char **palgnam, ENGINE *keygen_engine);
82 static const char *section = "req";
83 static CONF *req_conf = NULL;
84 static CONF *addext_conf = NULL;
87 typedef enum OPTION_choice {
88 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
89 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
90 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
91 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
92 OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
93 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
94 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
95 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
96 OPT_REQEXTS, OPT_PRECERT, OPT_MD,
98 OPT_R_ENUM, OPT_PROV_ENUM
101 const OPTIONS req_options[] = {
102 OPT_SECTION("General"),
103 {"help", OPT_HELP, '-', "Display this summary"},
104 #ifndef OPENSSL_NO_ENGINE
105 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
106 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
107 "Specify engine to be used for key generation operations"},
109 {"in", OPT_IN, '<', "Input file"},
110 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
111 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
113 OPT_SECTION("Certificate"),
114 {"new", OPT_NEW, '-', "New request"},
115 {"config", OPT_CONFIG, '<', "Request template file"},
116 {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
117 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
118 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
119 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
120 {"text", OPT_TEXT, '-', "Text form of request"},
121 {"x509", OPT_X509, '-',
122 "Output an x509 structure instead of a cert request"},
123 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
124 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
125 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
126 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
127 "Enable support for multivalued RDNs"},
128 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
129 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
130 {"addext", OPT_ADDEXT, 's',
131 "Additional cert extension key=value pair (may be given more than once)"},
132 {"extensions", OPT_EXTENSIONS, 's',
133 "Cert extension section (override value in config file)"},
134 {"reqexts", OPT_REQEXTS, 's',
135 "Request extension section (override value in config file)"},
136 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
138 OPT_SECTION("Keys and Signing"),
139 {"key", OPT_KEY, 's', "Private key to use"},
140 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
141 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
142 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
143 {"passin", OPT_PASSIN, 's', "Private key password source"},
144 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
145 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
146 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
147 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
148 {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
149 {"", OPT_MD, '-', "Any supported digest"},
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;
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, *vfyopts = 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;
261 #ifndef OPENSSL_NO_DES
262 cipher = EVP_des_ede3_cbc();
265 prog = opt_init(argc, argv, req_options);
266 while ((o = opt_next()) != OPT_EOF) {
271 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
274 opt_help(req_options);
278 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
282 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
286 e = setup_engine(opt_arg(), 0);
288 case OPT_KEYGEN_ENGINE:
289 #ifndef OPENSSL_NO_ENGINE
290 gen_eng = ENGINE_by_id(opt_arg());
291 if (gen_eng == NULL) {
292 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
307 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()))
358 vfyopts = sk_OPENSSL_STRING_new_null();
359 if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, 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))
451 argc = opt_num_rest();
456 BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
457 if (x509 && infile == NULL)
460 /* TODO: simplify this as pkey is still always NULL here */
461 private = newreq && (pkey == NULL) ? 1 : 0;
463 if (!app_passwd(passargin, passargout, &passin, &passout)) {
464 BIO_printf(bio_err, "Error getting passwords\n");
469 BIO_printf(bio_err, "Using configuration from %s\n", template);
470 if ((req_conf = app_load_config(template)) == NULL)
472 if (addext_bio != NULL) {
475 "Using additional configuration from command line\n");
476 if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
479 if (template != default_config_file && !app_load_modules(req_conf))
482 if (req_conf != NULL) {
483 p = NCONF_get_string(req_conf, NULL, "oid_file");
489 oid_bio = BIO_new_file(p, "r");
490 if (oid_bio == NULL) {
492 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
493 ERR_print_errors(bio_err);
496 OBJ_create_objects(oid_bio);
501 if (!add_oid_section(req_conf))
504 if (md_alg == NULL) {
505 p = NCONF_get_string(req_conf, section, "default_md");
509 if (!opt_md(p, &md_alg))
515 if (extensions == NULL) {
516 extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS);
517 if (extensions == NULL)
520 if (extensions != NULL) {
521 /* Check syntax of file */
523 X509V3_set_ctx_test(&ctx);
524 X509V3_set_nconf(&ctx, req_conf);
525 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
527 "Error Loading extension section %s\n", extensions);
531 if (addext_conf != NULL) {
532 /* Check syntax of command line extensions */
534 X509V3_set_ctx_test(&ctx);
535 X509V3_set_nconf(&ctx, addext_conf);
536 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
537 BIO_printf(bio_err, "Error Loading command line extensions\n");
542 if (passin == NULL) {
543 passin = nofree_passin =
544 NCONF_get_string(req_conf, section, "input_password");
549 if (passout == NULL) {
550 passout = nofree_passout =
551 NCONF_get_string(req_conf, section, "output_password");
556 p = NCONF_get_string(req_conf, section, STRING_MASK);
560 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
561 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
565 if (chtype != MBSTRING_UTF8) {
566 p = NCONF_get_string(req_conf, section, UTF8_IN);
569 else if (strcmp(p, "yes") == 0)
570 chtype = MBSTRING_UTF8;
573 if (req_exts == NULL) {
574 req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS);
575 if (req_exts == NULL)
578 if (req_exts != NULL) {
579 /* Check syntax of file */
581 X509V3_set_ctx_test(&ctx);
582 X509V3_set_nconf(&ctx, req_conf);
583 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
585 "Error Loading request extension section %s\n",
591 if (keyfile != NULL) {
592 pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
595 app_RAND_load_conf(req_conf, section);
598 if (newreq && (pkey == NULL)) {
599 app_RAND_load_conf(req_conf, section);
601 if (!NCONF_get_number(req_conf, section, BITS, &newkey)) {
602 newkey = DEFAULT_KEY_LENGTH;
605 if (keyalg != NULL) {
606 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
607 &keyalgstr, gen_eng);
612 if (newkey < MIN_KEY_LENGTH
613 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
614 BIO_printf(bio_err, "private key length is too short,\n");
615 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
616 MIN_KEY_LENGTH, newkey);
620 if (pkey_type == EVP_PKEY_RSA && newkey > OPENSSL_RSA_MAX_MODULUS_BITS)
622 "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
623 " Your key size is %ld! Larger key size may behave not as expected.\n",
624 OPENSSL_RSA_MAX_MODULUS_BITS, newkey);
626 #ifndef OPENSSL_NO_DSA
627 if (pkey_type == EVP_PKEY_DSA && newkey > OPENSSL_DSA_MAX_MODULUS_BITS)
629 "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
630 " Your key size is %ld! Larger key size may behave not as expected.\n",
631 OPENSSL_DSA_MAX_MODULUS_BITS, newkey);
634 if (genctx == NULL) {
635 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
636 &keyalgstr, gen_eng);
641 if (pkeyopts != NULL) {
643 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
644 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
645 if (pkey_ctrl_string(genctx, genopt) <= 0) {
646 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
647 ERR_print_errors(bio_err);
653 if (pkey_type == EVP_PKEY_EC) {
654 BIO_printf(bio_err, "Generating an EC private key\n");
656 BIO_printf(bio_err, "Generating a %s private key\n", keyalgstr);
659 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
660 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
662 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
663 BIO_puts(bio_err, "Error Generating Key\n");
667 EVP_PKEY_CTX_free(genctx);
670 if (keyout == NULL) {
671 keyout = NCONF_get_string(req_conf, section, KEYFILE);
677 BIO_printf(bio_err, "writing new private key to stdout\n");
679 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
680 out = bio_open_owner(keyout, outformat, private);
684 p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
687 p = NCONF_get_string(req_conf, section, "encrypt_key");
691 if ((p != NULL) && (strcmp(p, "no") == 0))
699 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
700 NULL, 0, NULL, passout)) {
701 if ((ERR_GET_REASON(ERR_peek_error()) ==
702 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
711 BIO_printf(bio_err, "-----\n");
715 req = load_csr(infile, informat, "X509 request");
720 if (newreq || x509) {
722 BIO_printf(bio_err, "you need to specify a private key\n");
727 req = X509_REQ_new();
732 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
733 subj = NULL; /* done processing '-subj' option */
735 BIO_printf(bio_err, "problems making Certificate Request\n");
742 if ((x509ss = X509_new()) == NULL)
745 /* Set version to V3 */
746 if ((extensions != NULL || addext_conf != NULL)
747 && !X509_set_version(x509ss, 2))
749 if (serial != NULL) {
750 if (!X509_set_serialNumber(x509ss, serial))
753 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
757 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
760 /* set default days if it's not specified */
763 if (!set_cert_times(x509ss, NULL, NULL, days))
765 if (!X509_set_subject_name
766 (x509ss, X509_REQ_get_subject_name(req)))
768 tmppkey = X509_REQ_get0_pubkey(req);
769 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
772 /* Set up V3 context struct */
774 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
775 X509V3_set_nconf(&ext_ctx, req_conf);
778 if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
779 &ext_ctx, extensions,
781 BIO_printf(bio_err, "Error Loading extension section %s\n",
785 if (addext_conf != NULL
786 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
788 BIO_printf(bio_err, "Error Loading command line extensions\n");
792 /* If a pre-cert was requested, we need to add a poison extension */
794 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
796 BIO_printf(bio_err, "Error adding poison extension\n");
801 i = do_X509_sign(x509ss, pkey, digest, sigopts);
803 ERR_print_errors(bio_err);
809 /* Set up V3 context struct */
811 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
812 X509V3_set_nconf(&ext_ctx, req_conf);
816 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
818 BIO_printf(bio_err, "Error Loading extension section %s\n",
822 if (addext_conf != NULL
823 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
825 BIO_printf(bio_err, "Error Loading command line extensions\n");
828 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
830 ERR_print_errors(bio_err);
837 BIO_printf(bio_err, "Cannot modify certificate subject\n");
843 BIO_printf(bio_err, "Modifying Request's Subject\n");
844 print_name(bio_err, "old subject=",
845 X509_REQ_get_subject_name(req), get_nameopt());
848 if (build_subject(req, subj, chtype, multirdn) == 0) {
849 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
855 print_name(bio_err, "new subject=",
856 X509_REQ_get_subject_name(req), get_nameopt());
860 if (verify && !x509) {
861 EVP_PKEY *tpubkey = pkey;
863 if (tpubkey == NULL) {
864 tpubkey = X509_REQ_get0_pubkey(req);
869 i = do_X509_REQ_verify(req, tpubkey, vfyopts);
874 BIO_printf(bio_err, "verify failure\n");
875 ERR_print_errors(bio_err);
876 } else { /* if (i > 0) */
877 BIO_printf(bio_err, "verify OK\n");
881 if (noout && !text && !modulus && !subject && !pubkey) {
886 out = bio_open_default(outfile,
887 keyout != NULL && outfile != NULL &&
888 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
894 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
896 if (tpubkey == NULL) {
897 BIO_printf(bio_err, "Error getting public key\n");
898 ERR_print_errors(bio_err);
901 PEM_write_bio_PUBKEY(out, tpubkey);
906 ret = X509_print_ex(out, x509ss, get_nameopt(), reqflag);
908 ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
912 BIO_printf(bio_err, "Error printing certificate\n");
914 BIO_printf(bio_err, "Error printing certificate request\n");
916 ERR_print_errors(bio_err);
923 print_name(out, "subject=", X509_get_subject_name(x509ss),
926 print_name(out, "subject=", X509_REQ_get_subject_name(req),
934 tpubkey = X509_get0_pubkey(x509ss);
936 tpubkey = X509_REQ_get0_pubkey(req);
937 if (tpubkey == NULL) {
938 fprintf(stdout, "Modulus=unavailable\n");
941 fprintf(stdout, "Modulus=");
942 #ifndef OPENSSL_NO_RSA
943 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
945 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
949 fprintf(stdout, "Wrong Algorithm type");
950 fprintf(stdout, "\n");
953 if (!noout && !x509) {
954 if (outformat == FORMAT_ASN1)
955 i = i2d_X509_REQ_bio(out, req);
957 i = PEM_write_bio_X509_REQ_NEW(out, req);
959 i = PEM_write_bio_X509_REQ(out, req);
961 BIO_printf(bio_err, "unable to write X509 request\n");
965 if (!noout && x509 && (x509ss != NULL)) {
966 if (outformat == FORMAT_ASN1)
967 i = i2d_X509_bio(out, x509ss);
969 i = PEM_write_bio_X509(out, x509ss);
971 BIO_printf(bio_err, "unable to write X509 certificate\n");
978 ERR_print_errors(bio_err);
980 NCONF_free(req_conf);
981 NCONF_free(addext_conf);
982 BIO_free(addext_bio);
985 EVP_PKEY_CTX_free(genctx);
986 sk_OPENSSL_STRING_free(pkeyopts);
987 sk_OPENSSL_STRING_free(sigopts);
988 sk_OPENSSL_STRING_free(vfyopts);
989 lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
990 lh_OPENSSL_STRING_free(addexts);
991 #ifndef OPENSSL_NO_ENGINE
992 ENGINE_free(gen_eng);
994 OPENSSL_free(keyalgstr);
997 ASN1_INTEGER_free(serial);
999 if (passin != nofree_passin)
1000 OPENSSL_free(passin);
1001 if (passout != nofree_passout)
1002 OPENSSL_free(passout);
1006 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1007 int attribs, unsigned long chtype)
1011 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1012 char *tmp, *dn_sect, *attr_sect;
1014 tmp = NCONF_get_string(req_conf, section, PROMPT);
1017 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1020 dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
1021 if (dn_sect == NULL) {
1022 BIO_printf(bio_err, "unable to find '%s' in config\n",
1023 DISTINGUISHED_NAME);
1026 dn_sk = NCONF_get_section(req_conf, dn_sect);
1027 if (dn_sk == NULL) {
1028 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
1032 attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
1033 if (attr_sect == NULL) {
1037 attr_sk = NCONF_get_section(req_conf, attr_sect);
1038 if (attr_sk == NULL) {
1039 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
1044 /* setup version number */
1045 if (!X509_REQ_set_version(req, 0L))
1046 goto err; /* version 1 */
1049 i = build_subject(req, subj, chtype, multirdn);
1051 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1053 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1058 if (!X509_REQ_set_pubkey(req, pkey))
1067 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1068 * where characters may be escaped by \
1070 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
1075 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
1078 if (!X509_REQ_set_subject_name(req, n)) {
1086 static int prompt_info(X509_REQ *req,
1087 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1088 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1089 int attribs, unsigned long chtype)
1099 X509_NAME *subj = X509_REQ_get_subject_name(req);
1103 "You are about to be asked to enter information that will be incorporated\n");
1104 BIO_printf(bio_err, "into your certificate request.\n");
1106 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1108 "There are quite a few fields but you can leave some blank\n");
1110 "For some fields there will be a default value,\n");
1112 "If you enter '.', the field will be left blank.\n");
1113 BIO_printf(bio_err, "-----\n");
1116 if (sk_CONF_VALUE_num(dn_sk)) {
1121 if (sk_CONF_VALUE_num(dn_sk) <= i)
1124 v = sk_CONF_VALUE_value(dn_sk, i);
1127 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1128 !check_end(type, "_default") || !check_end(type, "_value"))
1131 * Skip past any leading X. X: X, etc to allow for multiple
1134 for (p = v->name; *p; p++)
1135 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1147 /* If OBJ not recognised ignore it */
1148 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1150 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1152 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1157 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1159 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1164 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1166 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1172 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1174 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1179 if (!add_DN_object(subj, v->value, def, value, nid,
1180 n_min, n_max, chtype, mval))
1183 if (X509_NAME_entry_count(subj) == 0) {
1184 BIO_printf(bio_err, "error, no objects specified in config file\n");
1189 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1192 "\nPlease enter the following 'extra' attributes\n");
1194 "to be sent with your certificate request\n");
1201 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1204 v = sk_CONF_VALUE_value(attr_sk, i);
1206 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1209 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1211 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1217 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1219 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1225 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1227 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1232 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1234 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1239 if (!add_attribute_object(req,
1240 v->value, def, value, nid, n_min,
1246 BIO_printf(bio_err, "No template, please set one up.\n");
1254 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1255 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1256 unsigned long chtype)
1258 int i, spec_char, plus_char;
1264 subj = X509_REQ_get_subject_name(req);
1266 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1268 v = sk_CONF_VALUE_value(dn_sk, i);
1272 * Skip past any leading X. X: X, etc to allow for multiple instances
1274 for (p = v->name; *p; p++) {
1275 #ifndef CHARSET_EBCDIC
1276 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1278 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1279 || (*p == os_toascii['.']));
1288 #ifndef CHARSET_EBCDIC
1289 plus_char = (*type == '+');
1291 plus_char = (*type == os_toascii['+']);
1299 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1300 (unsigned char *)v->value, -1, -1,
1306 if (!X509_NAME_entry_count(subj)) {
1307 BIO_printf(bio_err, "error, no objects specified in config file\n");
1311 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1312 v = sk_CONF_VALUE_value(attr_sk, i);
1313 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1314 (unsigned char *)v->value, -1))
1321 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1322 char *value, int nid, int n_min, int n_max,
1323 unsigned long chtype, int mval)
1328 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1329 "DN value", "DN default");
1330 if ((ret == 0) || (ret == 1))
1334 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1335 (unsigned char *)buf, -1, -1, mval))
1341 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1342 char *value, int nid, int n_min,
1343 int n_max, unsigned long chtype)
1348 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1349 "Attribute value", "Attribute default");
1350 if ((ret == 0) || (ret == 1))
1354 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1355 (unsigned char *)buf, -1)) {
1356 BIO_printf(bio_err, "Error adding attribute\n");
1357 ERR_print_errors(bio_err);
1365 static int build_data(char *text, const char *def,
1366 char *value, int n_min, int n_max,
1367 char *buf, const int buf_size,
1368 const char *desc1, const char *desc2
1374 BIO_printf(bio_err, "%s [%s]:", text, def);
1375 (void)BIO_flush(bio_err);
1376 if (value != NULL) {
1377 if (!join(buf, buf_size, value, "\n", desc1))
1379 BIO_printf(bio_err, "%s\n", value);
1383 if (!fgets(buf, buf_size, stdin))
1393 if (buf[0] == '\n') {
1394 if ((def == NULL) || (def[0] == '\0'))
1396 if (!join(buf, buf_size, def, "\n", desc2))
1398 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1403 if (buf[i - 1] != '\n') {
1404 BIO_printf(bio_err, "weird input :-(\n");
1408 #ifdef CHARSET_EBCDIC
1409 ebcdic2ascii(buf, buf, i);
1411 if (!req_check_len(i, n_min, n_max)) {
1419 static int req_check_len(int len, int n_min, int n_max)
1421 if ((n_min > 0) && (len < n_min)) {
1423 "string is too short, it needs to be at least %d bytes long\n",
1427 if ((n_max >= 0) && (len > n_max)) {
1429 "string is too long, it needs to be no more than %d bytes long\n",
1436 /* Check if the end of a string matches 'end' */
1437 static int check_end(const char *str, const char *end)
1446 tmp = str + slen - elen;
1447 return strcmp(tmp, end);
1451 * Merge the two strings together into the result buffer checking for
1452 * overflow and producing an error message if there is.
1454 static int join(char buf[], size_t buf_size, const char *name,
1455 const char *tail, const char *desc)
1457 const size_t name_len = strlen(name), tail_len = strlen(tail);
1459 if (name_len + tail_len + 1 > buf_size) {
1460 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1463 memcpy(buf, name, name_len);
1464 memcpy(buf + name_len, tail, tail_len + 1);
1468 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1469 int *pkey_type, long *pkeylen,
1470 char **palgnam, ENGINE *keygen_engine)
1472 EVP_PKEY_CTX *gctx = NULL;
1473 EVP_PKEY *param = NULL;
1476 const char *paramfile = NULL;
1479 *pkey_type = EVP_PKEY_RSA;
1481 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1482 *pkey_type = EVP_PKEY_RSA;
1483 keylen = atol(gstr);
1485 } else if (strncmp(gstr, "param:", 6) == 0) {
1486 paramfile = gstr + 6;
1488 const char *p = strchr(gstr, ':');
1491 const EVP_PKEY_ASN1_METHOD *ameth;
1498 * The lookup of a the string will cover all engines so keep a note
1499 * of the implementation.
1502 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1504 if (ameth == NULL) {
1505 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1509 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1510 #ifndef OPENSSL_NO_ENGINE
1511 ENGINE_finish(tmpeng);
1513 if (*pkey_type == EVP_PKEY_RSA) {
1515 keylen = atol(p + 1);
1520 } else if (p != NULL) {
1525 if (paramfile != NULL) {
1526 pbio = BIO_new_file(paramfile, "r");
1528 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1531 param = PEM_read_bio_Parameters(pbio, NULL);
1533 if (param == NULL) {
1536 (void)BIO_reset(pbio);
1537 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1539 param = X509_get_pubkey(x);
1546 if (param == NULL) {
1547 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1550 if (*pkey_type == -1) {
1551 *pkey_type = EVP_PKEY_id(param);
1552 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1553 BIO_printf(bio_err, "Key Type does not match parameters\n");
1554 EVP_PKEY_free(param);
1559 if (palgnam != NULL) {
1560 const EVP_PKEY_ASN1_METHOD *ameth;
1564 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1565 if (ameth == NULL) {
1566 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1569 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1570 *palgnam = OPENSSL_strdup(anam);
1571 #ifndef OPENSSL_NO_ENGINE
1572 ENGINE_finish(tmpeng);
1576 if (param != NULL) {
1577 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1578 *pkeylen = EVP_PKEY_bits(param);
1579 EVP_PKEY_free(param);
1581 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1585 BIO_puts(bio_err, "Error allocating keygen context\n");
1586 ERR_print_errors(bio_err);
1590 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1591 BIO_puts(bio_err, "Error initializing keygen context\n");
1592 ERR_print_errors(bio_err);
1593 EVP_PKEY_CTX_free(gctx);
1596 #ifndef OPENSSL_NO_RSA
1597 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1598 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1599 BIO_puts(bio_err, "Error setting RSA keysize\n");
1600 ERR_print_errors(bio_err);
1601 EVP_PKEY_CTX_free(gctx);
1610 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1613 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1615 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1624 BIO_write(b, &c, 1);
1629 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
1636 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1637 char *opt = sk_OPENSSL_STRING_value(opts, i);
1638 if (pkey_ctrl_string(pkctx, opt) <= 0) {
1639 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1640 ERR_print_errors(bio_err);
1648 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
1655 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1656 char *opt = sk_OPENSSL_STRING_value(opts, i);
1657 if (x509_ctrl_string(x, opt) <= 0) {
1658 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1659 ERR_print_errors(bio_err);
1667 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
1674 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1675 char *opt = sk_OPENSSL_STRING_value(opts, i);
1676 if (x509_req_ctrl_string(x, opt) <= 0) {
1677 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1678 ERR_print_errors(bio_err);
1686 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1687 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1689 EVP_PKEY_CTX *pkctx = NULL;
1695 * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is mandatory
1696 * for this algorithm.
1698 if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) == 2
1699 && def_nid == NID_undef) {
1700 /* The signing algorithm requires there to be no digest */
1703 return EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey)
1704 && do_pkey_ctx_init(pkctx, sigopts);
1707 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1708 STACK_OF(OPENSSL_STRING) *sigopts)
1711 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1713 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1714 rv = (X509_sign_ctx(x, mctx) > 0);
1715 EVP_MD_CTX_free(mctx);
1719 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1720 STACK_OF(OPENSSL_STRING) *sigopts)
1723 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1725 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1726 rv = (X509_REQ_sign_ctx(x, mctx) > 0);
1727 EVP_MD_CTX_free(mctx);
1731 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
1735 if (do_x509_init(x, vfyopts) > 0)
1736 rv = (X509_verify(x, pkey) > 0);
1740 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
1741 STACK_OF(OPENSSL_STRING) *vfyopts)
1745 if (do_x509_req_init(x, vfyopts) > 0)
1746 rv = (X509_REQ_verify(x, pkey) > 0);
1750 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1751 STACK_OF(OPENSSL_STRING) *sigopts)
1754 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1756 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1757 rv = (X509_CRL_sign_ctx(x, mctx) > 0);
1758 EVP_MD_CTX_free(mctx);