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
10 /* We need to use some engine deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
20 #include <openssl/bio.h>
21 #include <openssl/evp.h>
22 #include <openssl/conf.h>
23 #include <openssl/err.h>
24 #include <openssl/asn1.h>
25 #include <openssl/x509.h>
26 #include <openssl/x509v3.h>
27 #include <openssl/objects.h>
28 #include <openssl/pem.h>
29 #include <openssl/bn.h>
30 #include <openssl/lhash.h>
31 #ifndef OPENSSL_NO_RSA
32 # include <openssl/rsa.h>
34 #ifndef OPENSSL_NO_DSA
35 # include <openssl/dsa.h>
38 DEFINE_STACK_OF(CONF_VALUE)
39 DEFINE_STACK_OF_STRING()
41 #define BITS "default_bits"
42 #define KEYFILE "default_keyfile"
43 #define PROMPT "prompt"
44 #define DISTINGUISHED_NAME "distinguished_name"
45 #define ATTRIBUTES "attributes"
46 #define V3_EXTENSIONS "x509_extensions"
47 #define REQ_EXTENSIONS "req_extensions"
48 #define STRING_MASK "string_mask"
49 #define UTF8_IN "utf8"
51 #define DEFAULT_KEY_LENGTH 2048
52 #define MIN_KEY_LENGTH 512
54 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
55 int attribs, unsigned long chtype);
56 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
58 static int prompt_info(X509_REQ *req,
59 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
60 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
61 int attribs, unsigned long chtype);
62 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
63 STACK_OF(CONF_VALUE) *attr, int attribs,
64 unsigned long chtype);
65 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
66 char *value, int nid, int n_min, int n_max,
67 unsigned long chtype);
68 static int add_DN_object(X509_NAME *n, char *text, const char *def,
69 char *value, int nid, int n_min, int n_max,
70 unsigned long chtype, int mval);
71 static int genpkey_cb(EVP_PKEY_CTX *ctx);
72 static int build_data(char *text, const char *def,
73 char *value, int n_min, int n_max,
74 char *buf, const int buf_size,
75 const char *desc1, const char *desc2
77 static int req_check_len(int len, int n_min, int n_max);
78 static int check_end(const char *str, const char *end);
79 static int join(char buf[], size_t buf_size, const char *name,
80 const char *tail, const char *desc);
81 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
82 int *pkey_type, long *pkeylen,
83 char **palgnam, ENGINE *keygen_engine);
85 static const char *section = "req";
86 static CONF *req_conf = NULL;
87 static CONF *addext_conf = NULL;
90 typedef enum OPTION_choice {
91 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
92 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
93 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
94 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
95 OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
96 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
97 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
98 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
99 OPT_REQEXTS, OPT_PRECERT, OPT_MD,
101 OPT_R_ENUM, OPT_PROV_ENUM
104 const OPTIONS req_options[] = {
105 OPT_SECTION("General"),
106 {"help", OPT_HELP, '-', "Display this summary"},
107 #ifndef OPENSSL_NO_ENGINE
108 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
109 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
110 "Specify engine to be used for key generation operations"},
112 {"in", OPT_IN, '<', "Input file"},
113 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
114 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
116 OPT_SECTION("Certificate"),
117 {"new", OPT_NEW, '-', "New request"},
118 {"config", OPT_CONFIG, '<', "Request template file"},
119 {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
120 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
121 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
122 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
123 {"text", OPT_TEXT, '-', "Text form of request"},
124 {"x509", OPT_X509, '-',
125 "Output an x509 structure instead of a cert request"},
126 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
127 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
128 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
129 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
130 "Enable support for multivalued RDNs"},
131 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
132 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
133 {"addext", OPT_ADDEXT, 's',
134 "Additional cert extension key=value pair (may be given more than once)"},
135 {"extensions", OPT_EXTENSIONS, 's',
136 "Cert extension section (override value in config file)"},
137 {"reqexts", OPT_REQEXTS, 's',
138 "Request extension section (override value in config file)"},
139 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
141 OPT_SECTION("Keys and Signing"),
142 {"key", OPT_KEY, 's', "Private key to use"},
143 {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"},
144 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
145 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
146 {"passin", OPT_PASSIN, 's', "Private key password source"},
147 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
148 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
149 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
150 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
151 {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
152 {"", OPT_MD, '-', "Any supported digest"},
154 OPT_SECTION("Output"),
155 {"out", OPT_OUT, '>', "Output file"},
156 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
157 {"batch", OPT_BATCH, '-',
158 "Do not ask anything during request generation"},
159 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
160 {"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;
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, *vfyopts = 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;
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();
316 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
329 passargin = opt_arg();
332 passargout = opt_arg();
339 if (!opt_provider(o))
347 if (pkeyopts == NULL)
348 pkeyopts = sk_OPENSSL_STRING_new_null();
350 || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
355 sigopts = sk_OPENSSL_STRING_new_null();
356 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
361 vfyopts = sk_OPENSSL_STRING_new_null();
362 if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
387 chtype = MBSTRING_UTF8;
390 if (!set_nameopt(opt_arg()))
394 if (!set_cert_ex(&reqflag, opt_arg()))
404 days = atoi(opt_arg());
407 if (serial != NULL) {
408 BIO_printf(bio_err, "Serial number supplied twice\n");
411 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
421 case OPT_MULTIVALUE_RDN:
426 if (addexts == NULL) {
427 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
428 addext_bio = BIO_new(BIO_s_mem());
429 if (addexts == NULL || addext_bio == NULL)
432 i = duplicated(addexts, p);
435 if (i < 0 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
439 extensions = opt_arg();
442 req_exts = opt_arg();
445 newreq = precert = 1;
448 if (!opt_md(opt_unknown(), &md_alg))
454 argc = opt_num_rest();
459 BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
460 if (x509 && infile == NULL)
463 /* TODO: simplify this as pkey is still always NULL here */
464 private = newreq && (pkey == NULL) ? 1 : 0;
466 if (!app_passwd(passargin, passargout, &passin, &passout)) {
467 BIO_printf(bio_err, "Error getting passwords\n");
472 BIO_printf(bio_err, "Using configuration from %s\n", template);
473 if ((req_conf = app_load_config(template)) == NULL)
475 if (addext_bio != NULL) {
478 "Using additional configuration from command line\n");
479 if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
482 if (template != default_config_file && !app_load_modules(req_conf))
485 if (req_conf != NULL) {
486 p = NCONF_get_string(req_conf, NULL, "oid_file");
492 oid_bio = BIO_new_file(p, "r");
493 if (oid_bio == NULL) {
495 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
496 ERR_print_errors(bio_err);
499 OBJ_create_objects(oid_bio);
504 if (!add_oid_section(req_conf))
507 if (md_alg == NULL) {
508 p = NCONF_get_string(req_conf, section, "default_md");
512 if (!opt_md(p, &md_alg))
518 if (extensions == NULL) {
519 extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS);
520 if (extensions == NULL)
523 if (extensions != NULL) {
524 /* Check syntax of file */
526 X509V3_set_ctx_test(&ctx);
527 X509V3_set_nconf(&ctx, req_conf);
528 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
530 "Error Loading extension section %s\n", extensions);
534 if (addext_conf != NULL) {
535 /* Check syntax of command line extensions */
537 X509V3_set_ctx_test(&ctx);
538 X509V3_set_nconf(&ctx, addext_conf);
539 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
540 BIO_printf(bio_err, "Error Loading command line extensions\n");
545 if (passin == NULL) {
546 passin = nofree_passin =
547 NCONF_get_string(req_conf, section, "input_password");
552 if (passout == NULL) {
553 passout = nofree_passout =
554 NCONF_get_string(req_conf, section, "output_password");
559 p = NCONF_get_string(req_conf, section, STRING_MASK);
563 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
564 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
568 if (chtype != MBSTRING_UTF8) {
569 p = NCONF_get_string(req_conf, section, UTF8_IN);
572 else if (strcmp(p, "yes") == 0)
573 chtype = MBSTRING_UTF8;
576 if (req_exts == NULL) {
577 req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS);
578 if (req_exts == NULL)
581 if (req_exts != NULL) {
582 /* Check syntax of file */
584 X509V3_set_ctx_test(&ctx);
585 X509V3_set_nconf(&ctx, req_conf);
586 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
588 "Error Loading request extension section %s\n",
594 if (keyfile != NULL) {
595 pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
598 app_RAND_load_conf(req_conf, section);
601 if (newreq && (pkey == NULL)) {
602 app_RAND_load_conf(req_conf, section);
604 if (!NCONF_get_number(req_conf, section, BITS, &newkey)) {
605 newkey = DEFAULT_KEY_LENGTH;
608 if (keyalg != NULL) {
609 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
610 &keyalgstr, gen_eng);
615 if (newkey < MIN_KEY_LENGTH
616 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
617 BIO_printf(bio_err, "private key length is too short,\n");
618 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
619 MIN_KEY_LENGTH, newkey);
623 if (pkey_type == EVP_PKEY_RSA && newkey > OPENSSL_RSA_MAX_MODULUS_BITS)
625 "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
626 " Your key size is %ld! Larger key size may behave not as expected.\n",
627 OPENSSL_RSA_MAX_MODULUS_BITS, newkey);
629 #ifndef OPENSSL_NO_DSA
630 if (pkey_type == EVP_PKEY_DSA && newkey > OPENSSL_DSA_MAX_MODULUS_BITS)
632 "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
633 " Your key size is %ld! Larger key size may behave not as expected.\n",
634 OPENSSL_DSA_MAX_MODULUS_BITS, newkey);
637 if (genctx == NULL) {
638 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
639 &keyalgstr, gen_eng);
644 if (pkeyopts != NULL) {
646 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
647 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
648 if (pkey_ctrl_string(genctx, genopt) <= 0) {
649 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
650 ERR_print_errors(bio_err);
656 if (pkey_type == EVP_PKEY_EC) {
657 BIO_printf(bio_err, "Generating an EC private key\n");
659 BIO_printf(bio_err, "Generating a %s private key\n", keyalgstr);
662 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
663 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
665 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
666 BIO_puts(bio_err, "Error Generating Key\n");
670 EVP_PKEY_CTX_free(genctx);
673 if (keyout == NULL) {
674 keyout = NCONF_get_string(req_conf, section, KEYFILE);
680 BIO_printf(bio_err, "writing new private key to stdout\n");
682 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
683 out = bio_open_owner(keyout, outformat, private);
687 p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
690 p = NCONF_get_string(req_conf, section, "encrypt_key");
694 if ((p != NULL) && (strcmp(p, "no") == 0))
702 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
703 NULL, 0, NULL, passout)) {
704 if ((ERR_GET_REASON(ERR_peek_error()) ==
705 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
714 BIO_printf(bio_err, "-----\n");
718 req = load_csr(infile, informat, "X509 request");
723 if (newreq || x509) {
725 BIO_printf(bio_err, "you need to specify a private key\n");
730 req = X509_REQ_new();
735 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
736 subj = NULL; /* done processing '-subj' option */
738 BIO_printf(bio_err, "problems making Certificate Request\n");
745 if ((x509ss = X509_new_with_libctx(app_get0_libctx(),
746 app_get0_propq())) == NULL)
749 /* Set version to V3 */
750 if ((extensions != NULL || addext_conf != NULL)
751 && !X509_set_version(x509ss, 2))
753 if (serial != NULL) {
754 if (!X509_set_serialNumber(x509ss, serial))
757 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
761 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
764 /* set default days if it's not specified */
767 if (!set_cert_times(x509ss, NULL, NULL, days))
769 if (!X509_set_subject_name
770 (x509ss, X509_REQ_get_subject_name(req)))
772 tmppkey = X509_REQ_get0_pubkey(req);
773 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
776 /* Set up V3 context struct */
778 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
779 X509V3_set_nconf(&ext_ctx, req_conf);
782 if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
783 &ext_ctx, extensions,
785 BIO_printf(bio_err, "Error Loading extension section %s\n",
789 if (addext_conf != NULL
790 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
792 BIO_printf(bio_err, "Error Loading command line extensions\n");
796 /* If a pre-cert was requested, we need to add a poison extension */
798 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
800 BIO_printf(bio_err, "Error adding poison extension\n");
805 i = do_X509_sign(x509ss, pkey, digest, sigopts);
807 ERR_print_errors(bio_err);
813 /* Set up V3 context struct */
815 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
816 X509V3_set_nconf(&ext_ctx, req_conf);
820 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
822 BIO_printf(bio_err, "Error Loading extension section %s\n",
826 if (addext_conf != NULL
827 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
829 BIO_printf(bio_err, "Error Loading command line extensions\n");
832 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
834 ERR_print_errors(bio_err);
841 BIO_printf(bio_err, "Cannot modify certificate subject\n");
847 BIO_printf(bio_err, "Modifying Request's Subject\n");
848 print_name(bio_err, "old subject=",
849 X509_REQ_get_subject_name(req), get_nameopt());
852 if (build_subject(req, subj, chtype, multirdn) == 0) {
853 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
859 print_name(bio_err, "new subject=",
860 X509_REQ_get_subject_name(req), get_nameopt());
864 if (verify && !x509) {
865 EVP_PKEY *tpubkey = pkey;
867 if (tpubkey == NULL) {
868 tpubkey = X509_REQ_get0_pubkey(req);
873 i = do_X509_REQ_verify(req, tpubkey, vfyopts);
878 BIO_printf(bio_err, "verify failure\n");
879 ERR_print_errors(bio_err);
880 } else { /* if (i > 0) */
881 BIO_printf(bio_err, "verify OK\n");
885 if (noout && !text && !modulus && !subject && !pubkey) {
890 out = bio_open_default(outfile,
891 keyout != NULL && outfile != NULL &&
892 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
898 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
900 if (tpubkey == NULL) {
901 BIO_printf(bio_err, "Error getting public key\n");
902 ERR_print_errors(bio_err);
905 PEM_write_bio_PUBKEY(out, tpubkey);
910 ret = X509_print_ex(out, x509ss, get_nameopt(), reqflag);
912 ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
916 BIO_printf(bio_err, "Error printing certificate\n");
918 BIO_printf(bio_err, "Error printing certificate request\n");
920 ERR_print_errors(bio_err);
927 print_name(out, "subject=", X509_get_subject_name(x509ss),
930 print_name(out, "subject=", X509_REQ_get_subject_name(req),
938 tpubkey = X509_get0_pubkey(x509ss);
940 tpubkey = X509_REQ_get0_pubkey(req);
941 if (tpubkey == NULL) {
942 fprintf(stdout, "Modulus=unavailable\n");
945 fprintf(stdout, "Modulus=");
946 #ifndef OPENSSL_NO_RSA
947 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
949 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
953 fprintf(stdout, "Wrong Algorithm type");
954 fprintf(stdout, "\n");
957 if (!noout && !x509) {
958 if (outformat == FORMAT_ASN1)
959 i = i2d_X509_REQ_bio(out, req);
961 i = PEM_write_bio_X509_REQ_NEW(out, req);
963 i = PEM_write_bio_X509_REQ(out, req);
965 BIO_printf(bio_err, "unable to write X509 request\n");
969 if (!noout && x509 && (x509ss != NULL)) {
970 if (outformat == FORMAT_ASN1)
971 i = i2d_X509_bio(out, x509ss);
973 i = PEM_write_bio_X509(out, x509ss);
975 BIO_printf(bio_err, "unable to write X509 certificate\n");
982 ERR_print_errors(bio_err);
984 NCONF_free(req_conf);
985 NCONF_free(addext_conf);
986 BIO_free(addext_bio);
989 EVP_PKEY_CTX_free(genctx);
990 sk_OPENSSL_STRING_free(pkeyopts);
991 sk_OPENSSL_STRING_free(sigopts);
992 sk_OPENSSL_STRING_free(vfyopts);
993 lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
994 lh_OPENSSL_STRING_free(addexts);
995 #ifndef OPENSSL_NO_ENGINE
996 ENGINE_free(gen_eng);
998 OPENSSL_free(keyalgstr);
1001 ASN1_INTEGER_free(serial);
1003 if (passin != nofree_passin)
1004 OPENSSL_free(passin);
1005 if (passout != nofree_passout)
1006 OPENSSL_free(passout);
1010 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1011 int attribs, unsigned long chtype)
1015 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1016 char *tmp, *dn_sect, *attr_sect;
1018 tmp = NCONF_get_string(req_conf, section, PROMPT);
1021 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1024 dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
1025 if (dn_sect == NULL) {
1026 BIO_printf(bio_err, "unable to find '%s' in config\n",
1027 DISTINGUISHED_NAME);
1030 dn_sk = NCONF_get_section(req_conf, dn_sect);
1031 if (dn_sk == NULL) {
1032 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
1036 attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
1037 if (attr_sect == NULL) {
1041 attr_sk = NCONF_get_section(req_conf, attr_sect);
1042 if (attr_sk == NULL) {
1043 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
1048 /* setup version number */
1049 if (!X509_REQ_set_version(req, 0L))
1050 goto err; /* version 1 */
1053 i = build_subject(req, subj, chtype, multirdn);
1055 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1057 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1062 if (!X509_REQ_set_pubkey(req, pkey))
1071 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1072 * where characters may be escaped by \
1074 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
1079 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
1082 if (!X509_REQ_set_subject_name(req, n)) {
1090 static int prompt_info(X509_REQ *req,
1091 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1092 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1093 int attribs, unsigned long chtype)
1103 X509_NAME *subj = X509_REQ_get_subject_name(req);
1107 "You are about to be asked to enter information that will be incorporated\n");
1108 BIO_printf(bio_err, "into your certificate request.\n");
1110 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1112 "There are quite a few fields but you can leave some blank\n");
1114 "For some fields there will be a default value,\n");
1116 "If you enter '.', the field will be left blank.\n");
1117 BIO_printf(bio_err, "-----\n");
1120 if (sk_CONF_VALUE_num(dn_sk)) {
1125 if (sk_CONF_VALUE_num(dn_sk) <= i)
1128 v = sk_CONF_VALUE_value(dn_sk, i);
1131 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1132 !check_end(type, "_default") || !check_end(type, "_value"))
1135 * Skip past any leading X. X: X, etc to allow for multiple
1138 for (p = v->name; *p; p++)
1139 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1151 /* If OBJ not recognised ignore it */
1152 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1154 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1156 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1161 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1163 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1168 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1170 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1176 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1178 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1183 if (!add_DN_object(subj, v->value, def, value, nid,
1184 n_min, n_max, chtype, mval))
1187 if (X509_NAME_entry_count(subj) == 0) {
1188 BIO_printf(bio_err, "error, no objects specified in config file\n");
1193 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1196 "\nPlease enter the following 'extra' attributes\n");
1198 "to be sent with your certificate request\n");
1205 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1208 v = sk_CONF_VALUE_value(attr_sk, i);
1210 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1213 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1215 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1221 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1223 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1229 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1231 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1236 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1238 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1243 if (!add_attribute_object(req,
1244 v->value, def, value, nid, n_min,
1250 BIO_printf(bio_err, "No template, please set one up.\n");
1258 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1259 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1260 unsigned long chtype)
1262 int i, spec_char, plus_char;
1268 subj = X509_REQ_get_subject_name(req);
1270 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1272 v = sk_CONF_VALUE_value(dn_sk, i);
1276 * Skip past any leading X. X: X, etc to allow for multiple instances
1278 for (p = v->name; *p; p++) {
1279 #ifndef CHARSET_EBCDIC
1280 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1282 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1283 || (*p == os_toascii['.']));
1292 #ifndef CHARSET_EBCDIC
1293 plus_char = (*type == '+');
1295 plus_char = (*type == os_toascii['+']);
1303 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1304 (unsigned char *)v->value, -1, -1,
1310 if (!X509_NAME_entry_count(subj)) {
1311 BIO_printf(bio_err, "error, no objects specified in config file\n");
1315 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1316 v = sk_CONF_VALUE_value(attr_sk, i);
1317 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1318 (unsigned char *)v->value, -1))
1325 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1326 char *value, int nid, int n_min, int n_max,
1327 unsigned long chtype, int mval)
1332 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1333 "DN value", "DN default");
1334 if ((ret == 0) || (ret == 1))
1338 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1339 (unsigned char *)buf, -1, -1, mval))
1345 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1346 char *value, int nid, int n_min,
1347 int n_max, unsigned long chtype)
1352 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1353 "Attribute value", "Attribute default");
1354 if ((ret == 0) || (ret == 1))
1358 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1359 (unsigned char *)buf, -1)) {
1360 BIO_printf(bio_err, "Error adding attribute\n");
1361 ERR_print_errors(bio_err);
1369 static int build_data(char *text, const char *def,
1370 char *value, int n_min, int n_max,
1371 char *buf, const int buf_size,
1372 const char *desc1, const char *desc2
1378 BIO_printf(bio_err, "%s [%s]:", text, def);
1379 (void)BIO_flush(bio_err);
1380 if (value != NULL) {
1381 if (!join(buf, buf_size, value, "\n", desc1))
1383 BIO_printf(bio_err, "%s\n", value);
1387 if (!fgets(buf, buf_size, stdin))
1397 if (buf[0] == '\n') {
1398 if ((def == NULL) || (def[0] == '\0'))
1400 if (!join(buf, buf_size, def, "\n", desc2))
1402 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1407 if (buf[i - 1] != '\n') {
1408 BIO_printf(bio_err, "weird input :-(\n");
1412 #ifdef CHARSET_EBCDIC
1413 ebcdic2ascii(buf, buf, i);
1415 if (!req_check_len(i, n_min, n_max)) {
1423 static int req_check_len(int len, int n_min, int n_max)
1425 if ((n_min > 0) && (len < n_min)) {
1427 "string is too short, it needs to be at least %d bytes long\n",
1431 if ((n_max >= 0) && (len > n_max)) {
1433 "string is too long, it needs to be no more than %d bytes long\n",
1440 /* Check if the end of a string matches 'end' */
1441 static int check_end(const char *str, const char *end)
1450 tmp = str + slen - elen;
1451 return strcmp(tmp, end);
1455 * Merge the two strings together into the result buffer checking for
1456 * overflow and producing an error message if there is.
1458 static int join(char buf[], size_t buf_size, const char *name,
1459 const char *tail, const char *desc)
1461 const size_t name_len = strlen(name), tail_len = strlen(tail);
1463 if (name_len + tail_len + 1 > buf_size) {
1464 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1467 memcpy(buf, name, name_len);
1468 memcpy(buf + name_len, tail, tail_len + 1);
1472 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1473 int *pkey_type, long *pkeylen,
1474 char **palgnam, ENGINE *keygen_engine)
1476 EVP_PKEY_CTX *gctx = NULL;
1477 EVP_PKEY *param = NULL;
1480 const char *paramfile = NULL;
1483 *pkey_type = EVP_PKEY_RSA;
1485 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1486 *pkey_type = EVP_PKEY_RSA;
1487 keylen = atol(gstr);
1489 } else if (strncmp(gstr, "param:", 6) == 0) {
1490 paramfile = gstr + 6;
1492 const char *p = strchr(gstr, ':');
1495 const EVP_PKEY_ASN1_METHOD *ameth;
1502 * The lookup of a the string will cover all engines so keep a note
1503 * of the implementation.
1506 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1508 if (ameth == NULL) {
1509 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1513 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1514 #ifndef OPENSSL_NO_ENGINE
1515 ENGINE_finish(tmpeng);
1517 if (*pkey_type == EVP_PKEY_RSA) {
1519 keylen = atol(p + 1);
1524 } else if (p != NULL) {
1529 if (paramfile != NULL) {
1530 pbio = BIO_new_file(paramfile, "r");
1532 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1535 param = PEM_read_bio_Parameters(pbio, NULL);
1537 if (param == NULL) {
1540 (void)BIO_reset(pbio);
1541 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1543 param = X509_get_pubkey(x);
1550 if (param == NULL) {
1551 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1554 if (*pkey_type == -1) {
1555 *pkey_type = EVP_PKEY_id(param);
1556 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1557 BIO_printf(bio_err, "Key Type does not match parameters\n");
1558 EVP_PKEY_free(param);
1563 if (palgnam != NULL) {
1564 const EVP_PKEY_ASN1_METHOD *ameth;
1568 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1569 if (ameth == NULL) {
1570 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1573 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1574 *palgnam = OPENSSL_strdup(anam);
1575 #ifndef OPENSSL_NO_ENGINE
1576 ENGINE_finish(tmpeng);
1580 if (param != NULL) {
1581 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1582 *pkeylen = EVP_PKEY_bits(param);
1583 EVP_PKEY_free(param);
1585 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1589 BIO_puts(bio_err, "Error allocating keygen context\n");
1590 ERR_print_errors(bio_err);
1594 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1595 BIO_puts(bio_err, "Error initializing keygen context\n");
1596 ERR_print_errors(bio_err);
1597 EVP_PKEY_CTX_free(gctx);
1600 #ifndef OPENSSL_NO_RSA
1601 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1602 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1603 BIO_puts(bio_err, "Error setting RSA keysize\n");
1604 ERR_print_errors(bio_err);
1605 EVP_PKEY_CTX_free(gctx);
1614 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1617 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1619 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1628 BIO_write(b, &c, 1);
1633 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
1640 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1641 char *opt = sk_OPENSSL_STRING_value(opts, i);
1642 if (pkey_ctrl_string(pkctx, opt) <= 0) {
1643 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1644 ERR_print_errors(bio_err);
1652 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
1659 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1660 char *opt = sk_OPENSSL_STRING_value(opts, i);
1661 if (x509_ctrl_string(x, opt) <= 0) {
1662 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1663 ERR_print_errors(bio_err);
1671 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
1678 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1679 char *opt = sk_OPENSSL_STRING_value(opts, i);
1680 if (x509_req_ctrl_string(x, opt) <= 0) {
1681 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1682 ERR_print_errors(bio_err);
1690 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1691 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1693 EVP_PKEY_CTX *pkctx = NULL;
1699 * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is mandatory
1700 * for this algorithm.
1702 if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) == 2
1703 && def_nid == NID_undef) {
1704 /* The signing algorithm requires there to be no digest */
1707 return EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey)
1708 && do_pkey_ctx_init(pkctx, sigopts);
1711 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1712 STACK_OF(OPENSSL_STRING) *sigopts)
1715 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1717 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1718 rv = (X509_sign_ctx(x, mctx) > 0);
1719 EVP_MD_CTX_free(mctx);
1723 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1724 STACK_OF(OPENSSL_STRING) *sigopts)
1727 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1729 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1730 rv = (X509_REQ_sign_ctx(x, mctx) > 0);
1731 EVP_MD_CTX_free(mctx);
1735 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
1739 if (do_x509_init(x, vfyopts) > 0)
1740 rv = (X509_verify(x, pkey) > 0);
1744 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
1745 STACK_OF(OPENSSL_STRING) *vfyopts)
1749 if (do_x509_req_init(x, vfyopts) > 0)
1750 rv = (X509_REQ_verify(x, pkey) > 0);
1754 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1755 STACK_OF(OPENSSL_STRING) *sigopts)
1758 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1760 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1761 rv = (X509_CRL_sign_ctx(x, mctx) > 0);
1762 EVP_MD_CTX_free(mctx);