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 BITS "default_bits"
36 #define KEYFILE "default_keyfile"
37 #define PROMPT "prompt"
38 #define DISTINGUISHED_NAME "distinguished_name"
39 #define ATTRIBUTES "attributes"
40 #define V3_EXTENSIONS "x509_extensions"
41 #define REQ_EXTENSIONS "req_extensions"
42 #define STRING_MASK "string_mask"
43 #define UTF8_IN "utf8"
45 #define DEFAULT_KEY_LENGTH 2048
46 #define MIN_KEY_LENGTH 512
48 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
49 int attribs, unsigned long chtype);
50 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
52 static int prompt_info(X509_REQ *req,
53 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
54 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
55 int attribs, unsigned long chtype);
56 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
57 STACK_OF(CONF_VALUE) *attr, int attribs,
58 unsigned long chtype);
59 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
60 char *value, int nid, int n_min, int n_max,
61 unsigned long chtype);
62 static int add_DN_object(X509_NAME *n, char *text, const char *def,
63 char *value, int nid, int n_min, int n_max,
64 unsigned long chtype, int mval);
65 static int genpkey_cb(EVP_PKEY_CTX *ctx);
66 static int build_data(char *text, const char *def,
67 char *value, int n_min, int n_max,
68 char *buf, const int buf_size,
69 const char *desc1, const char *desc2
71 static int req_check_len(int len, int n_min, int n_max);
72 static int check_end(const char *str, const char *end);
73 static int join(char buf[], size_t buf_size, const char *name,
74 const char *tail, const char *desc);
75 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
76 int *pkey_type, long *pkeylen,
77 char **palgnam, ENGINE *keygen_engine);
79 static const char *section = "req";
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_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
90 OPT_VERIFY, OPT_NOENC, 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,
95 OPT_R_ENUM, OPT_PROV_ENUM
98 const OPTIONS req_options[] = {
99 OPT_SECTION("General"),
100 {"help", OPT_HELP, '-', "Display this summary"},
101 #ifndef OPENSSL_NO_ENGINE
102 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
103 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
104 "Specify engine to be used for key generation operations"},
106 {"in", OPT_IN, '<', "Input file"},
107 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
108 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
110 OPT_SECTION("Certificate"),
111 {"new", OPT_NEW, '-', "New request"},
112 {"config", OPT_CONFIG, '<', "Request template file"},
113 {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
114 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
115 {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"},
116 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
117 {"text", OPT_TEXT, '-', "Text form of request"},
118 {"x509", OPT_X509, '-',
119 "Output an x509 structure instead of a cert request"},
120 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
121 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
122 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
123 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
124 "Deprecated; multi-valued RDNs support is always on."},
125 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
126 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
127 {"addext", OPT_ADDEXT, 's',
128 "Additional cert extension key=value pair (may be given more than once)"},
129 {"extensions", OPT_EXTENSIONS, 's',
130 "Cert extension section (override value in config file)"},
131 {"reqexts", OPT_REQEXTS, 's',
132 "Request extension section (override value in config file)"},
133 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
135 OPT_SECTION("Keys and Signing"),
136 {"key", OPT_KEY, 's', "Private key to use"},
137 {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"},
138 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
139 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
140 {"passin", OPT_PASSIN, 's', "Private key password source"},
141 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
142 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
143 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
144 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
145 {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
146 {"", OPT_MD, '-', "Any supported digest"},
148 OPT_SECTION("Output"),
149 {"out", OPT_OUT, '>', "Output file"},
150 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
151 {"batch", OPT_BATCH, '-',
152 "Do not ask anything during request generation"},
153 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
154 {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"},
155 {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"},
156 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
157 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
158 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
167 * An LHASH of strings, where each string is an extension name.
169 static unsigned long ext_name_hash(const OPENSSL_STRING *a)
171 return OPENSSL_LH_strhash((const char *)a);
174 static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
176 return strcmp((const char *)a, (const char *)b);
179 static void exts_cleanup(OPENSSL_STRING *x)
181 OPENSSL_free((char *)x);
185 * Is the |kv| key already duplicated? This is remarkably tricky to get
186 * right. Return 0 if unique, -1 on runtime error; 1 if found or a syntax
189 static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
195 /* Skip leading whitespace, make a copy. */
196 while (*kv && isspace(*kv))
199 if ((p = strchr(kv, '=')) == NULL)
202 if ((kv = OPENSSL_strdup(kv)) == NULL)
205 /* Skip trailing space before the equal sign. */
206 for (p = kv + off; p > kv; --p)
215 /* Finally have a clean "key"; see if it's there [by attempt to add it]. */
216 p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING*)kv);
220 } else if (lh_OPENSSL_STRING_error(addexts)) {
228 int req_main(int argc, char **argv)
230 ASN1_INTEGER *serial = NULL;
232 ENGINE *e = NULL, *gen_eng = NULL;
233 EVP_PKEY *pkey = NULL;
234 EVP_PKEY_CTX *genctx = NULL;
235 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL, *vfyopts = NULL;
236 LHASH_OF(OPENSSL_STRING) *addexts = NULL;
238 X509_REQ *req = NULL;
239 const EVP_CIPHER *cipher = NULL;
240 const EVP_MD *md_alg = NULL, *digest = NULL;
241 BIO *addext_bio = NULL;
242 char *extensions = NULL, *infile = NULL;
243 char *outfile = NULL, *keyfile = NULL;
244 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
245 char *passin = NULL, *passout = NULL;
246 char *nofree_passin = NULL, *nofree_passout = NULL;
247 char *req_exts = NULL, *subj = NULL;
248 char *template = default_config_file, *keyout = NULL;
249 const char *keyalg = NULL;
251 int ret = 1, x509 = 0, days = 0, i = 0, newreq = 0, verbose = 0;
252 int pkey_type = -1, private = 0;
253 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
254 int modulus = 0, multirdn = 1, verify = 0, noout = 0, text = 0;
255 int noenc = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
257 unsigned long chtype = MBSTRING_ASC, reqflag = 0;
259 #ifndef OPENSSL_NO_DES
260 cipher = EVP_des_ede3_cbc();
263 prog = opt_init(argc, argv, req_options);
264 while ((o = opt_next()) != OPT_EOF) {
269 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
272 opt_help(req_options);
276 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
280 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
284 e = setup_engine(opt_arg(), 0);
286 case OPT_KEYGEN_ENGINE:
287 #ifndef OPENSSL_NO_ENGINE
288 gen_eng = setup_engine(opt_arg(), 0);
289 if (gen_eng == NULL) {
290 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
305 template = opt_arg();
311 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
324 passargin = opt_arg();
327 passargout = opt_arg();
334 if (!opt_provider(o))
342 if (pkeyopts == NULL)
343 pkeyopts = sk_OPENSSL_STRING_new_null();
345 || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
350 sigopts = sk_OPENSSL_STRING_new_null();
351 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
356 vfyopts = sk_OPENSSL_STRING_new_null();
357 if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
383 chtype = MBSTRING_UTF8;
386 if (!set_nameopt(opt_arg()))
390 if (!set_cert_ex(&reqflag, opt_arg()))
400 days = atoi(opt_arg());
403 if (serial != NULL) {
404 BIO_printf(bio_err, "Serial number supplied twice\n");
407 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
417 case OPT_MULTIVALUE_RDN:
422 if (addexts == NULL) {
423 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
424 addext_bio = BIO_new(BIO_s_mem());
425 if (addexts == NULL || addext_bio == NULL)
428 i = duplicated(addexts, p);
431 if (i < 0 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
435 extensions = opt_arg();
438 req_exts = opt_arg();
441 newreq = precert = 1;
444 if (!opt_md(opt_unknown(), &md_alg))
450 argc = opt_num_rest();
455 BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
456 if (x509 && infile == NULL)
459 /* TODO: simplify this as pkey is still always NULL here */
460 private = newreq && (pkey == NULL) ? 1 : 0;
462 if (!app_passwd(passargin, passargout, &passin, &passout)) {
463 BIO_printf(bio_err, "Error getting passwords\n");
468 BIO_printf(bio_err, "Using configuration from %s\n", template);
469 if ((req_conf = app_load_config(template)) == NULL)
471 if (addext_bio != NULL) {
474 "Using additional configuration from command line\n");
475 if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
478 if (template != default_config_file && !app_load_modules(req_conf))
481 if (req_conf != NULL) {
482 p = NCONF_get_string(req_conf, NULL, "oid_file");
488 oid_bio = BIO_new_file(p, "r");
489 if (oid_bio == NULL) {
491 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
492 ERR_print_errors(bio_err);
495 OBJ_create_objects(oid_bio);
500 if (!add_oid_section(req_conf))
503 if (md_alg == NULL) {
504 p = NCONF_get_string(req_conf, section, "default_md");
508 if (!opt_md(p, &md_alg))
514 if (extensions == NULL) {
515 extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS);
516 if (extensions == NULL)
519 if (extensions != NULL) {
520 /* Check syntax of file */
522 X509V3_set_ctx_test(&ctx);
523 X509V3_set_nconf(&ctx, req_conf);
524 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
526 "Error Loading extension section %s\n", extensions);
530 if (addext_conf != NULL) {
531 /* Check syntax of command line extensions */
533 X509V3_set_ctx_test(&ctx);
534 X509V3_set_nconf(&ctx, addext_conf);
535 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
536 BIO_printf(bio_err, "Error Loading command line extensions\n");
541 if (passin == NULL) {
542 passin = nofree_passin =
543 NCONF_get_string(req_conf, section, "input_password");
548 if (passout == NULL) {
549 passout = nofree_passout =
550 NCONF_get_string(req_conf, section, "output_password");
555 p = NCONF_get_string(req_conf, section, STRING_MASK);
559 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
560 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
564 if (chtype != MBSTRING_UTF8) {
565 p = NCONF_get_string(req_conf, section, UTF8_IN);
568 else if (strcmp(p, "yes") == 0)
569 chtype = MBSTRING_UTF8;
572 if (req_exts == NULL) {
573 req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS);
574 if (req_exts == NULL)
577 if (req_exts != NULL) {
578 /* Check syntax of file */
580 X509V3_set_ctx_test(&ctx);
581 X509V3_set_nconf(&ctx, req_conf);
582 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
584 "Error Loading request extension section %s\n",
590 if (keyfile != NULL) {
591 pkey = load_key(keyfile, keyform, 0, passin, e, "private key");
594 app_RAND_load_conf(req_conf, section);
597 if (newreq && (pkey == NULL)) {
598 app_RAND_load_conf(req_conf, section);
600 if (!NCONF_get_number(req_conf, section, BITS, &newkey)) {
601 newkey = DEFAULT_KEY_LENGTH;
604 if (keyalg != NULL) {
605 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
606 &keyalgstr, gen_eng);
611 if (newkey < MIN_KEY_LENGTH
612 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
613 BIO_printf(bio_err, "private key length is too short,\n");
614 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
615 MIN_KEY_LENGTH, newkey);
619 if (pkey_type == EVP_PKEY_RSA && newkey > OPENSSL_RSA_MAX_MODULUS_BITS)
621 "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
622 " Your key size is %ld! Larger key size may behave not as expected.\n",
623 OPENSSL_RSA_MAX_MODULUS_BITS, newkey);
625 #ifndef OPENSSL_NO_DSA
626 if (pkey_type == EVP_PKEY_DSA && newkey > OPENSSL_DSA_MAX_MODULUS_BITS)
628 "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
629 " Your key size is %ld! Larger key size may behave not as expected.\n",
630 OPENSSL_DSA_MAX_MODULUS_BITS, newkey);
633 if (genctx == NULL) {
634 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
635 &keyalgstr, gen_eng);
640 if (pkeyopts != NULL) {
642 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
643 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
644 if (pkey_ctrl_string(genctx, genopt) <= 0) {
645 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
646 ERR_print_errors(bio_err);
652 if (pkey_type == EVP_PKEY_EC) {
653 BIO_printf(bio_err, "Generating an EC private key\n");
655 BIO_printf(bio_err, "Generating a %s private key\n", keyalgstr);
658 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
659 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
661 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
662 BIO_puts(bio_err, "Error Generating Key\n");
666 EVP_PKEY_CTX_free(genctx);
669 if (keyout == NULL) {
670 keyout = NCONF_get_string(req_conf, section, KEYFILE);
676 BIO_printf(bio_err, "writing new private key to stdout\n");
678 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
679 out = bio_open_owner(keyout, outformat, private);
683 p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
686 p = NCONF_get_string(req_conf, section, "encrypt_key");
690 if ((p != NULL) && (strcmp(p, "no") == 0))
698 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
699 NULL, 0, NULL, passout)) {
700 if ((ERR_GET_REASON(ERR_peek_error()) ==
701 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
710 BIO_printf(bio_err, "-----\n");
714 req = load_csr(infile, informat, "X509 request");
719 if (newreq || x509) {
721 BIO_printf(bio_err, "you need to specify a private key\n");
726 req = X509_REQ_new();
731 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
732 subj = NULL; /* done processing '-subj' option */
734 BIO_printf(bio_err, "problems making Certificate Request\n");
741 if ((x509ss = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL)
744 /* Set version to V3 */
745 if ((extensions != NULL || addext_conf != NULL)
746 && !X509_set_version(x509ss, 2))
748 if (serial != NULL) {
749 if (!X509_set_serialNumber(x509ss, serial))
752 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
756 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
759 /* set default days if it's not specified */
762 if (!set_cert_times(x509ss, NULL, NULL, days))
764 if (!X509_set_subject_name
765 (x509ss, X509_REQ_get_subject_name(req)))
767 tmppkey = X509_REQ_get0_pubkey(req);
768 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
771 /* Set up V3 context struct */
773 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
774 X509V3_set_nconf(&ext_ctx, req_conf);
777 if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
778 &ext_ctx, extensions,
780 BIO_printf(bio_err, "Error Loading extension section %s\n",
784 if (addext_conf != NULL
785 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
787 BIO_printf(bio_err, "Error Loading command line extensions\n");
791 /* If a pre-cert was requested, we need to add a poison extension */
793 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
795 BIO_printf(bio_err, "Error adding poison extension\n");
800 i = do_X509_sign(x509ss, pkey, digest, sigopts);
802 ERR_print_errors(bio_err);
808 /* Set up V3 context struct */
810 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
811 X509V3_set_nconf(&ext_ctx, req_conf);
815 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
817 BIO_printf(bio_err, "Error Loading extension section %s\n",
821 if (addext_conf != NULL
822 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
824 BIO_printf(bio_err, "Error Loading command line extensions\n");
827 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
829 ERR_print_errors(bio_err);
836 BIO_printf(bio_err, "Cannot modify certificate subject\n");
842 BIO_printf(bio_err, "Modifying Request's Subject\n");
843 print_name(bio_err, "old subject=",
844 X509_REQ_get_subject_name(req), get_nameopt());
847 if (build_subject(req, subj, chtype, multirdn) == 0) {
848 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
854 print_name(bio_err, "new subject=",
855 X509_REQ_get_subject_name(req), get_nameopt());
859 if (verify && !x509) {
860 EVP_PKEY *tpubkey = pkey;
862 if (tpubkey == NULL) {
863 tpubkey = X509_REQ_get0_pubkey(req);
868 i = do_X509_REQ_verify(req, tpubkey, vfyopts);
873 BIO_printf(bio_err, "verify failure\n");
874 ERR_print_errors(bio_err);
875 } else { /* if (i > 0) */
876 BIO_printf(bio_err, "verify OK\n");
880 if (noout && !text && !modulus && !subject && !pubkey) {
885 out = bio_open_default(outfile,
886 keyout != NULL && outfile != NULL &&
887 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
893 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
895 if (tpubkey == NULL) {
896 BIO_printf(bio_err, "Error getting public key\n");
897 ERR_print_errors(bio_err);
900 PEM_write_bio_PUBKEY(out, tpubkey);
905 ret = X509_print_ex(out, x509ss, get_nameopt(), reqflag);
907 ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
911 BIO_printf(bio_err, "Error printing certificate\n");
913 BIO_printf(bio_err, "Error printing certificate request\n");
915 ERR_print_errors(bio_err);
922 print_name(out, "subject=", X509_get_subject_name(x509ss),
925 print_name(out, "subject=", X509_REQ_get_subject_name(req),
933 tpubkey = X509_get0_pubkey(x509ss);
935 tpubkey = X509_REQ_get0_pubkey(req);
936 if (tpubkey == NULL) {
937 fprintf(stdout, "Modulus=unavailable\n");
940 fprintf(stdout, "Modulus=");
941 #ifndef OPENSSL_NO_RSA
942 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
944 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
948 fprintf(stdout, "Wrong Algorithm type");
949 fprintf(stdout, "\n");
952 if (!noout && !x509) {
953 if (outformat == FORMAT_ASN1)
954 i = i2d_X509_REQ_bio(out, req);
956 i = PEM_write_bio_X509_REQ_NEW(out, req);
958 i = PEM_write_bio_X509_REQ(out, req);
960 BIO_printf(bio_err, "unable to write X509 request\n");
964 if (!noout && x509 && (x509ss != NULL)) {
965 if (outformat == FORMAT_ASN1)
966 i = i2d_X509_bio(out, x509ss);
968 i = PEM_write_bio_X509(out, x509ss);
970 BIO_printf(bio_err, "unable to write X509 certificate\n");
977 ERR_print_errors(bio_err);
979 NCONF_free(req_conf);
980 NCONF_free(addext_conf);
981 BIO_free(addext_bio);
984 EVP_PKEY_CTX_free(genctx);
985 sk_OPENSSL_STRING_free(pkeyopts);
986 sk_OPENSSL_STRING_free(sigopts);
987 sk_OPENSSL_STRING_free(vfyopts);
988 lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
989 lh_OPENSSL_STRING_free(addexts);
990 #ifndef OPENSSL_NO_ENGINE
991 release_engine(gen_eng);
993 OPENSSL_free(keyalgstr);
996 ASN1_INTEGER_free(serial);
998 if (passin != nofree_passin)
999 OPENSSL_free(passin);
1000 if (passout != nofree_passout)
1001 OPENSSL_free(passout);
1005 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1006 int attribs, unsigned long chtype)
1010 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1011 char *tmp, *dn_sect, *attr_sect;
1013 tmp = NCONF_get_string(req_conf, section, PROMPT);
1016 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1019 dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
1020 if (dn_sect == NULL) {
1021 BIO_printf(bio_err, "unable to find '%s' in config\n",
1022 DISTINGUISHED_NAME);
1025 dn_sk = NCONF_get_section(req_conf, dn_sect);
1026 if (dn_sk == NULL) {
1027 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
1031 attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
1032 if (attr_sect == NULL) {
1036 attr_sk = NCONF_get_section(req_conf, attr_sect);
1037 if (attr_sk == NULL) {
1038 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
1043 /* setup version number */
1044 if (!X509_REQ_set_version(req, 0L))
1045 goto err; /* version 1 */
1048 i = build_subject(req, subj, chtype, multirdn);
1050 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1052 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1057 if (!X509_REQ_set_pubkey(req, pkey))
1066 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1067 * where characters may be escaped by \
1069 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
1074 if ((n = parse_name(subject, chtype, multirdn, "subject")) == NULL)
1077 if (!X509_REQ_set_subject_name(req, n)) {
1085 static int prompt_info(X509_REQ *req,
1086 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1087 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1088 int attribs, unsigned long chtype)
1098 X509_NAME *subj = X509_REQ_get_subject_name(req);
1102 "You are about to be asked to enter information that will be incorporated\n");
1103 BIO_printf(bio_err, "into your certificate request.\n");
1105 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1107 "There are quite a few fields but you can leave some blank\n");
1109 "For some fields there will be a default value,\n");
1111 "If you enter '.', the field will be left blank.\n");
1112 BIO_printf(bio_err, "-----\n");
1115 if (sk_CONF_VALUE_num(dn_sk)) {
1120 if (sk_CONF_VALUE_num(dn_sk) <= i)
1123 v = sk_CONF_VALUE_value(dn_sk, i);
1126 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1127 !check_end(type, "_default") || !check_end(type, "_value"))
1130 * Skip past any leading X. X: X, etc to allow for multiple
1133 for (p = v->name; *p; p++)
1134 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1146 /* If OBJ not recognised ignore it */
1147 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1149 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1151 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1156 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1158 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1163 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1165 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1171 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1173 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1178 if (!add_DN_object(subj, v->value, def, value, nid,
1179 n_min, n_max, chtype, mval))
1182 if (X509_NAME_entry_count(subj) == 0) {
1183 BIO_printf(bio_err, "error, no objects specified in config file\n");
1188 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1191 "\nPlease enter the following 'extra' attributes\n");
1193 "to be sent with your certificate request\n");
1200 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1203 v = sk_CONF_VALUE_value(attr_sk, i);
1205 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1208 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1210 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1216 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1218 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1224 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1226 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1231 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1233 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1238 if (!add_attribute_object(req,
1239 v->value, def, value, nid, n_min,
1245 BIO_printf(bio_err, "No template, please set one up.\n");
1253 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1254 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1255 unsigned long chtype)
1257 int i, spec_char, plus_char;
1263 subj = X509_REQ_get_subject_name(req);
1265 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1267 v = sk_CONF_VALUE_value(dn_sk, i);
1271 * Skip past any leading X. X: X, etc to allow for multiple instances
1273 for (p = v->name; *p; p++) {
1274 #ifndef CHARSET_EBCDIC
1275 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1277 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1278 || (*p == os_toascii['.']));
1287 #ifndef CHARSET_EBCDIC
1288 plus_char = (*type == '+');
1290 plus_char = (*type == os_toascii['+']);
1298 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1299 (unsigned char *)v->value, -1, -1,
1305 if (!X509_NAME_entry_count(subj)) {
1306 BIO_printf(bio_err, "error, no objects specified in config file\n");
1310 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1311 v = sk_CONF_VALUE_value(attr_sk, i);
1312 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1313 (unsigned char *)v->value, -1))
1320 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1321 char *value, int nid, int n_min, int n_max,
1322 unsigned long chtype, int mval)
1327 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1328 "DN value", "DN default");
1329 if ((ret == 0) || (ret == 1))
1333 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1334 (unsigned char *)buf, -1, -1, mval))
1340 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1341 char *value, int nid, int n_min,
1342 int n_max, unsigned long chtype)
1347 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1348 "Attribute value", "Attribute default");
1349 if ((ret == 0) || (ret == 1))
1353 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1354 (unsigned char *)buf, -1)) {
1355 BIO_printf(bio_err, "Error adding attribute\n");
1356 ERR_print_errors(bio_err);
1364 static int build_data(char *text, const char *def,
1365 char *value, int n_min, int n_max,
1366 char *buf, const int buf_size,
1367 const char *desc1, const char *desc2
1373 BIO_printf(bio_err, "%s [%s]:", text, def);
1374 (void)BIO_flush(bio_err);
1375 if (value != NULL) {
1376 if (!join(buf, buf_size, value, "\n", desc1))
1378 BIO_printf(bio_err, "%s\n", value);
1382 if (!fgets(buf, buf_size, stdin))
1392 if (buf[0] == '\n') {
1393 if ((def == NULL) || (def[0] == '\0'))
1395 if (!join(buf, buf_size, def, "\n", desc2))
1397 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1402 if (buf[i - 1] != '\n') {
1403 BIO_printf(bio_err, "weird input :-(\n");
1407 #ifdef CHARSET_EBCDIC
1408 ebcdic2ascii(buf, buf, i);
1410 if (!req_check_len(i, n_min, n_max)) {
1418 static int req_check_len(int len, int n_min, int n_max)
1420 if ((n_min > 0) && (len < n_min)) {
1422 "string is too short, it needs to be at least %d bytes long\n",
1426 if ((n_max >= 0) && (len > n_max)) {
1428 "string is too long, it needs to be no more than %d bytes long\n",
1435 /* Check if the end of a string matches 'end' */
1436 static int check_end(const char *str, const char *end)
1445 tmp = str + slen - elen;
1446 return strcmp(tmp, end);
1450 * Merge the two strings together into the result buffer checking for
1451 * overflow and producing an error message if there is.
1453 static int join(char buf[], size_t buf_size, const char *name,
1454 const char *tail, const char *desc)
1456 const size_t name_len = strlen(name), tail_len = strlen(tail);
1458 if (name_len + tail_len + 1 > buf_size) {
1459 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1462 memcpy(buf, name, name_len);
1463 memcpy(buf + name_len, tail, tail_len + 1);
1467 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1468 int *pkey_type, long *pkeylen,
1469 char **palgnam, ENGINE *keygen_engine)
1471 EVP_PKEY_CTX *gctx = NULL;
1472 EVP_PKEY *param = NULL;
1475 const char *paramfile = NULL;
1478 *pkey_type = EVP_PKEY_RSA;
1480 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1481 *pkey_type = EVP_PKEY_RSA;
1482 keylen = atol(gstr);
1484 } else if (strncmp(gstr, "param:", 6) == 0) {
1485 paramfile = gstr + 6;
1487 const char *p = strchr(gstr, ':');
1490 const EVP_PKEY_ASN1_METHOD *ameth;
1497 * The lookup of a the string will cover all engines so keep a note
1498 * of the implementation.
1501 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1503 if (ameth == NULL) {
1504 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1508 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1509 #ifndef OPENSSL_NO_ENGINE
1510 finish_engine(tmpeng);
1512 if (*pkey_type == EVP_PKEY_RSA) {
1514 keylen = atol(p + 1);
1519 } else if (p != NULL) {
1524 if (paramfile != NULL) {
1525 pbio = BIO_new_file(paramfile, "r");
1527 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1530 param = PEM_read_bio_Parameters(pbio, NULL);
1532 if (param == NULL) {
1535 (void)BIO_reset(pbio);
1536 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1538 param = X509_get_pubkey(x);
1545 if (param == NULL) {
1546 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1549 if (*pkey_type == -1) {
1550 *pkey_type = EVP_PKEY_id(param);
1551 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1552 BIO_printf(bio_err, "Key Type does not match parameters\n");
1553 EVP_PKEY_free(param);
1558 if (palgnam != NULL) {
1559 const EVP_PKEY_ASN1_METHOD *ameth;
1563 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1564 if (ameth == NULL) {
1565 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1568 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1569 *palgnam = OPENSSL_strdup(anam);
1570 #ifndef OPENSSL_NO_ENGINE
1571 finish_engine(tmpeng);
1575 if (param != NULL) {
1576 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1577 *pkeylen = EVP_PKEY_bits(param);
1578 EVP_PKEY_free(param);
1580 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1584 BIO_puts(bio_err, "Error allocating keygen context\n");
1585 ERR_print_errors(bio_err);
1589 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1590 BIO_puts(bio_err, "Error initializing keygen context\n");
1591 ERR_print_errors(bio_err);
1592 EVP_PKEY_CTX_free(gctx);
1595 #ifndef OPENSSL_NO_RSA
1596 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1597 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1598 BIO_puts(bio_err, "Error setting RSA keysize\n");
1599 ERR_print_errors(bio_err);
1600 EVP_PKEY_CTX_free(gctx);
1609 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1612 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1614 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1623 BIO_write(b, &c, 1);
1628 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
1635 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1636 char *opt = sk_OPENSSL_STRING_value(opts, i);
1637 if (pkey_ctrl_string(pkctx, opt) <= 0) {
1638 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1639 ERR_print_errors(bio_err);
1647 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
1654 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1655 char *opt = sk_OPENSSL_STRING_value(opts, i);
1656 if (x509_ctrl_string(x, opt) <= 0) {
1657 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1658 ERR_print_errors(bio_err);
1666 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
1673 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1674 char *opt = sk_OPENSSL_STRING_value(opts, i);
1675 if (x509_req_ctrl_string(x, opt) <= 0) {
1676 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1677 ERR_print_errors(bio_err);
1685 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1686 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1688 EVP_PKEY_CTX *pkctx = NULL;
1694 * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is mandatory
1695 * for this algorithm.
1697 if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) == 2
1698 && def_nid == NID_undef) {
1699 /* The signing algorithm requires there to be no digest */
1702 return EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey)
1703 && do_pkey_ctx_init(pkctx, sigopts);
1706 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1707 STACK_OF(OPENSSL_STRING) *sigopts)
1710 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1712 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1713 rv = (X509_sign_ctx(x, mctx) > 0);
1714 EVP_MD_CTX_free(mctx);
1718 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1719 STACK_OF(OPENSSL_STRING) *sigopts)
1722 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1724 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1725 rv = (X509_REQ_sign_ctx(x, mctx) > 0);
1726 EVP_MD_CTX_free(mctx);
1730 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
1734 if (do_x509_init(x, vfyopts) > 0)
1735 rv = (X509_verify(x, pkey) > 0);
1739 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
1740 STACK_OF(OPENSSL_STRING) *vfyopts)
1744 if (do_x509_req_init(x, vfyopts) > 0)
1745 rv = (X509_REQ_verify(x, pkey) > 0);
1749 int do_X509_CRL_sign(X509_CRL *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_CRL_sign_ctx(x, mctx) > 0);
1757 EVP_MD_CTX_free(mctx);