2 * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
17 #include <openssl/bio.h>
18 #include <openssl/evp.h>
19 #include <openssl/conf.h>
20 #include <openssl/err.h>
21 #include <openssl/asn1.h>
22 #include <openssl/x509.h>
23 #include <openssl/x509v3.h>
24 #include <openssl/objects.h>
25 #include <openssl/pem.h>
26 #include <openssl/bn.h>
27 #include <openssl/lhash.h>
28 #ifndef OPENSSL_NO_RSA
29 # include <openssl/rsa.h>
31 #ifndef OPENSSL_NO_DSA
32 # include <openssl/dsa.h>
36 #define BITS "default_bits"
37 #define KEYFILE "default_keyfile"
38 #define PROMPT "prompt"
39 #define DISTINGUISHED_NAME "distinguished_name"
40 #define ATTRIBUTES "attributes"
41 #define V3_EXTENSIONS "x509_extensions"
42 #define REQ_EXTENSIONS "req_extensions"
43 #define STRING_MASK "string_mask"
44 #define UTF8_IN "utf8"
46 #define DEFAULT_KEY_LENGTH 2048
47 #define MIN_KEY_LENGTH 512
49 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
50 int attribs, unsigned long chtype);
51 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
53 static int prompt_info(X509_REQ *req,
54 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
55 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
56 int attribs, unsigned long chtype);
57 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
58 STACK_OF(CONF_VALUE) *attr, int attribs,
59 unsigned long chtype);
60 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
61 char *value, int nid, int n_min, int n_max,
62 unsigned long chtype);
63 static int add_DN_object(X509_NAME *n, char *text, const char *def,
64 char *value, int nid, int n_min, int n_max,
65 unsigned long chtype, int mval);
66 static int genpkey_cb(EVP_PKEY_CTX *ctx);
67 static int build_data(char *text, const char *def,
68 char *value, int n_min, int n_max,
69 char *buf, const int buf_size,
70 const char *desc1, const char *desc2
72 static int req_check_len(int len, int n_min, int n_max);
73 static int check_end(const char *str, const char *end);
74 static int join(char buf[], size_t buf_size, const char *name,
75 const char *tail, const char *desc);
76 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
77 int *pkey_type, long *pkeylen,
78 char **palgnam, ENGINE *keygen_engine);
80 static const char *section = "req";
81 static CONF *req_conf = NULL;
82 static CONF *addext_conf = NULL;
85 typedef enum OPTION_choice {
86 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
87 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
88 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
89 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
90 OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
91 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
92 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
93 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
94 OPT_REQEXTS, OPT_PRECERT, OPT_MD,
96 OPT_R_ENUM, OPT_PROV_ENUM
99 const OPTIONS req_options[] = {
100 OPT_SECTION("General"),
101 {"help", OPT_HELP, '-', "Display this summary"},
102 #ifndef OPENSSL_NO_ENGINE
103 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
104 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
105 "Specify engine to be used for key generation operations"},
107 {"in", OPT_IN, '<', "Input file"},
108 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
109 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
111 OPT_SECTION("Certificate"),
112 {"new", OPT_NEW, '-', "New request"},
113 {"config", OPT_CONFIG, '<', "Request template file"},
114 {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"},
115 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
116 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
117 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
118 {"text", OPT_TEXT, '-', "Text form of request"},
119 {"x509", OPT_X509, '-',
120 "Output an x509 structure instead of a cert request"},
121 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
122 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
123 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
124 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
125 "Enable support for multivalued RDNs"},
126 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
127 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
128 {"addext", OPT_ADDEXT, 's',
129 "Additional cert extension key=value pair (may be given more than once)"},
130 {"extensions", OPT_EXTENSIONS, 's',
131 "Cert extension section (override value in config file)"},
132 {"reqexts", OPT_REQEXTS, 's',
133 "Request extension section (override value in config file)"},
134 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
136 OPT_SECTION("Keys and Signing"),
137 {"key", OPT_KEY, 's', "Private key to use"},
138 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
139 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
140 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
141 {"passin", OPT_PASSIN, 's', "Private key password source"},
142 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
143 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
144 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
145 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
146 {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"},
147 {"", OPT_MD, '-', "Any supported digest"},
149 OPT_SECTION("Output"),
150 {"out", OPT_OUT, '>', "Output file"},
151 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
152 {"batch", OPT_BATCH, '-',
153 "Do not ask anything during request generation"},
154 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
155 {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
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;
231 BIO *in = NULL, *out = 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 = 0, verify = 0, noout = 0, text = 0;
255 int nodes = 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 = ENGINE_by_id(opt_arg());
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()))
382 chtype = MBSTRING_UTF8;
385 if (!set_nameopt(opt_arg()))
389 if (!set_cert_ex(&reqflag, opt_arg()))
399 days = atoi(opt_arg());
402 if (serial != NULL) {
403 BIO_printf(bio_err, "Serial number supplied twice\n");
406 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
416 case OPT_MULTIVALUE_RDN:
421 if (addexts == NULL) {
422 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
423 addext_bio = BIO_new(BIO_s_mem());
424 if (addexts == NULL || addext_bio == NULL)
427 i = duplicated(addexts, p);
430 if (i < 0 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
434 extensions = opt_arg();
437 req_exts = opt_arg();
440 newreq = precert = 1;
443 if (!opt_md(opt_unknown(), &md_alg))
449 argc = opt_num_rest();
454 BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
455 if (x509 && infile == NULL)
458 /* TODO: simplify this as pkey is still always NULL here */
459 private = newreq && (pkey == NULL) ? 1 : 0;
461 if (!app_passwd(passargin, passargout, &passin, &passout)) {
462 BIO_printf(bio_err, "Error getting passwords\n");
467 BIO_printf(bio_err, "Using configuration from %s\n", template);
468 if ((req_conf = app_load_config(template)) == NULL)
473 "Using additional configuration from command line\n");
474 if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
477 if (template != default_config_file && !app_load_modules(req_conf))
480 if (req_conf != NULL) {
481 p = NCONF_get_string(req_conf, NULL, "oid_file");
487 oid_bio = BIO_new_file(p, "r");
488 if (oid_bio == NULL) {
490 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
491 ERR_print_errors(bio_err);
494 OBJ_create_objects(oid_bio);
499 if (!add_oid_section(req_conf))
502 if (md_alg == NULL) {
503 p = NCONF_get_string(req_conf, section, "default_md");
507 if (!opt_md(p, &md_alg))
513 if (extensions == NULL) {
514 extensions = NCONF_get_string(req_conf, section, V3_EXTENSIONS);
515 if (extensions == NULL)
518 if (extensions != NULL) {
519 /* Check syntax of file */
521 X509V3_set_ctx_test(&ctx);
522 X509V3_set_nconf(&ctx, req_conf);
523 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
525 "Error Loading extension section %s\n", extensions);
529 if (addext_conf != NULL) {
530 /* Check syntax of command line extensions */
532 X509V3_set_ctx_test(&ctx);
533 X509V3_set_nconf(&ctx, addext_conf);
534 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
535 BIO_printf(bio_err, "Error Loading command line extensions\n");
540 if (passin == NULL) {
541 passin = nofree_passin =
542 NCONF_get_string(req_conf, section, "input_password");
547 if (passout == NULL) {
548 passout = nofree_passout =
549 NCONF_get_string(req_conf, section, "output_password");
554 p = NCONF_get_string(req_conf, section, STRING_MASK);
558 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
559 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
563 if (chtype != MBSTRING_UTF8) {
564 p = NCONF_get_string(req_conf, section, UTF8_IN);
567 else if (strcmp(p, "yes") == 0)
568 chtype = MBSTRING_UTF8;
571 if (req_exts == NULL) {
572 req_exts = NCONF_get_string(req_conf, section, REQ_EXTENSIONS);
573 if (req_exts == NULL)
576 if (req_exts != NULL) {
577 /* Check syntax of file */
579 X509V3_set_ctx_test(&ctx);
580 X509V3_set_nconf(&ctx, req_conf);
581 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
583 "Error Loading request extension section %s\n",
589 if (keyfile != NULL) {
590 pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
592 /* load_key() has already printed an appropriate message */
595 app_RAND_load_conf(req_conf, section);
599 if (newreq && (pkey == NULL)) {
600 app_RAND_load_conf(req_conf, section);
602 if (!NCONF_get_number(req_conf, section, BITS, &newkey)) {
603 newkey = DEFAULT_KEY_LENGTH;
606 if (keyalg != NULL) {
607 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
608 &keyalgstr, gen_eng);
613 if (newkey < MIN_KEY_LENGTH
614 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
615 BIO_printf(bio_err, "private key length is too short,\n");
616 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
617 MIN_KEY_LENGTH, newkey);
621 if (pkey_type == EVP_PKEY_RSA && newkey > OPENSSL_RSA_MAX_MODULUS_BITS)
623 "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
624 " Your key size is %ld! Larger key size may behave not as expected.\n",
625 OPENSSL_RSA_MAX_MODULUS_BITS, newkey);
627 #ifndef OPENSSL_NO_DSA
628 if (pkey_type == EVP_PKEY_DSA && newkey > OPENSSL_DSA_MAX_MODULUS_BITS)
630 "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
631 " Your key size is %ld! Larger key size may behave not as expected.\n",
632 OPENSSL_DSA_MAX_MODULUS_BITS, newkey);
635 if (genctx == NULL) {
636 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
637 &keyalgstr, gen_eng);
642 if (pkeyopts != NULL) {
644 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
645 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
646 if (pkey_ctrl_string(genctx, genopt) <= 0) {
647 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
648 ERR_print_errors(bio_err);
654 if (pkey_type == EVP_PKEY_EC) {
655 BIO_printf(bio_err, "Generating an EC private key\n");
657 BIO_printf(bio_err, "Generating a %s private key\n", keyalgstr);
660 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
661 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
663 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
664 BIO_puts(bio_err, "Error Generating Key\n");
668 EVP_PKEY_CTX_free(genctx);
671 if (keyout == NULL) {
672 keyout = NCONF_get_string(req_conf, section, KEYFILE);
678 BIO_printf(bio_err, "writing new private key to stdout\n");
680 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
681 out = bio_open_owner(keyout, outformat, private);
685 p = NCONF_get_string(req_conf, section, "encrypt_rsa_key");
688 p = NCONF_get_string(req_conf, section, "encrypt_key");
692 if ((p != NULL) && (strcmp(p, "no") == 0))
700 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
701 NULL, 0, NULL, passout)) {
702 if ((ERR_GET_REASON(ERR_peek_error()) ==
703 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
712 BIO_printf(bio_err, "-----\n");
716 in = bio_open_default(infile, 'r', informat);
720 if (informat == FORMAT_ASN1)
721 req = d2i_X509_REQ_bio(in, NULL);
723 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
725 BIO_printf(bio_err, "unable to load X509 request\n");
730 if (newreq || x509) {
732 BIO_printf(bio_err, "you need to specify a private key\n");
737 req = X509_REQ_new();
742 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
743 subj = NULL; /* done processing '-subj' option */
745 BIO_printf(bio_err, "problems making Certificate Request\n");
752 if ((x509ss = X509_new()) == NULL)
755 /* Set version to V3 */
756 if ((extensions != NULL || addext_conf != NULL)
757 && !X509_set_version(x509ss, 2))
759 if (serial != NULL) {
760 if (!X509_set_serialNumber(x509ss, serial))
763 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
767 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
770 /* set default days if it's not specified */
773 if (!set_cert_times(x509ss, NULL, NULL, days))
775 if (!X509_set_subject_name
776 (x509ss, X509_REQ_get_subject_name(req)))
778 tmppkey = X509_REQ_get0_pubkey(req);
779 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
782 /* Set up V3 context struct */
784 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
785 X509V3_set_nconf(&ext_ctx, req_conf);
788 if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
789 &ext_ctx, extensions,
791 BIO_printf(bio_err, "Error Loading extension section %s\n",
795 if (addext_conf != NULL
796 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
798 BIO_printf(bio_err, "Error Loading command line extensions\n");
802 /* If a pre-cert was requested, we need to add a poison extension */
804 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
806 BIO_printf(bio_err, "Error adding poison extension\n");
811 i = do_X509_sign(x509ss, pkey, digest, sigopts);
813 ERR_print_errors(bio_err);
819 /* Set up V3 context struct */
821 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
822 X509V3_set_nconf(&ext_ctx, req_conf);
826 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
828 BIO_printf(bio_err, "Error Loading extension section %s\n",
832 if (addext_conf != NULL
833 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
835 BIO_printf(bio_err, "Error Loading command line extensions\n");
838 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
840 ERR_print_errors(bio_err);
847 BIO_printf(bio_err, "Cannot modify certificate subject\n");
853 BIO_printf(bio_err, "Modifying Request's Subject\n");
854 print_name(bio_err, "old subject=",
855 X509_REQ_get_subject_name(req), get_nameopt());
858 if (build_subject(req, subj, chtype, multirdn) == 0) {
859 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
865 print_name(bio_err, "new subject=",
866 X509_REQ_get_subject_name(req), get_nameopt());
870 if (verify && !x509) {
871 EVP_PKEY *tpubkey = pkey;
873 if (tpubkey == NULL) {
874 tpubkey = X509_REQ_get0_pubkey(req);
879 i = do_X509_REQ_verify(req, tpubkey, vfyopts);
884 BIO_printf(bio_err, "verify failure\n");
885 ERR_print_errors(bio_err);
886 } else { /* if (i > 0) */
887 BIO_printf(bio_err, "verify OK\n");
891 if (noout && !text && !modulus && !subject && !pubkey) {
896 out = bio_open_default(outfile,
897 keyout != NULL && outfile != NULL &&
898 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
904 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
906 if (tpubkey == NULL) {
907 BIO_printf(bio_err, "Error getting public key\n");
908 ERR_print_errors(bio_err);
911 PEM_write_bio_PUBKEY(out, tpubkey);
916 ret = X509_print_ex(out, x509ss, get_nameopt(), reqflag);
918 ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
922 BIO_printf(bio_err, "Error printing certificate\n");
924 BIO_printf(bio_err, "Error printing certificate request\n");
926 ERR_print_errors(bio_err);
933 print_name(out, "subject=", X509_get_subject_name(x509ss),
936 print_name(out, "subject=", X509_REQ_get_subject_name(req),
944 tpubkey = X509_get0_pubkey(x509ss);
946 tpubkey = X509_REQ_get0_pubkey(req);
947 if (tpubkey == NULL) {
948 fprintf(stdout, "Modulus=unavailable\n");
951 fprintf(stdout, "Modulus=");
952 #ifndef OPENSSL_NO_RSA
953 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
955 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
959 fprintf(stdout, "Wrong Algorithm type");
960 fprintf(stdout, "\n");
963 if (!noout && !x509) {
964 if (outformat == FORMAT_ASN1)
965 i = i2d_X509_REQ_bio(out, req);
967 i = PEM_write_bio_X509_REQ_NEW(out, req);
969 i = PEM_write_bio_X509_REQ(out, req);
971 BIO_printf(bio_err, "unable to write X509 request\n");
975 if (!noout && x509 && (x509ss != NULL)) {
976 if (outformat == FORMAT_ASN1)
977 i = i2d_X509_bio(out, x509ss);
979 i = PEM_write_bio_X509(out, x509ss);
981 BIO_printf(bio_err, "unable to write X509 certificate\n");
988 ERR_print_errors(bio_err);
990 NCONF_free(req_conf);
991 NCONF_free(addext_conf);
992 BIO_free(addext_bio);
996 EVP_PKEY_CTX_free(genctx);
997 sk_OPENSSL_STRING_free(pkeyopts);
998 sk_OPENSSL_STRING_free(sigopts);
999 sk_OPENSSL_STRING_free(vfyopts);
1000 lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
1001 lh_OPENSSL_STRING_free(addexts);
1002 #ifndef OPENSSL_NO_ENGINE
1003 ENGINE_free(gen_eng);
1005 OPENSSL_free(keyalgstr);
1008 ASN1_INTEGER_free(serial);
1010 if (passin != nofree_passin)
1011 OPENSSL_free(passin);
1012 if (passout != nofree_passout)
1013 OPENSSL_free(passout);
1017 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1018 int attribs, unsigned long chtype)
1022 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1023 char *tmp, *dn_sect, *attr_sect;
1025 tmp = NCONF_get_string(req_conf, section, PROMPT);
1028 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1031 dn_sect = NCONF_get_string(req_conf, section, DISTINGUISHED_NAME);
1032 if (dn_sect == NULL) {
1033 BIO_printf(bio_err, "unable to find '%s' in config\n",
1034 DISTINGUISHED_NAME);
1037 dn_sk = NCONF_get_section(req_conf, dn_sect);
1038 if (dn_sk == NULL) {
1039 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
1043 attr_sect = NCONF_get_string(req_conf, section, ATTRIBUTES);
1044 if (attr_sect == NULL) {
1048 attr_sk = NCONF_get_section(req_conf, attr_sect);
1049 if (attr_sk == NULL) {
1050 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
1055 /* setup version number */
1056 if (!X509_REQ_set_version(req, 0L))
1057 goto err; /* version 1 */
1060 i = build_subject(req, subj, chtype, multirdn);
1062 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1064 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1069 if (!X509_REQ_set_pubkey(req, pkey))
1078 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1079 * where characters may be escaped by \
1081 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
1086 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
1089 if (!X509_REQ_set_subject_name(req, n)) {
1097 static int prompt_info(X509_REQ *req,
1098 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1099 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1100 int attribs, unsigned long chtype)
1110 X509_NAME *subj = X509_REQ_get_subject_name(req);
1114 "You are about to be asked to enter information that will be incorporated\n");
1115 BIO_printf(bio_err, "into your certificate request.\n");
1117 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1119 "There are quite a few fields but you can leave some blank\n");
1121 "For some fields there will be a default value,\n");
1123 "If you enter '.', the field will be left blank.\n");
1124 BIO_printf(bio_err, "-----\n");
1127 if (sk_CONF_VALUE_num(dn_sk)) {
1132 if (sk_CONF_VALUE_num(dn_sk) <= i)
1135 v = sk_CONF_VALUE_value(dn_sk, i);
1138 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1139 !check_end(type, "_default") || !check_end(type, "_value"))
1142 * Skip past any leading X. X: X, etc to allow for multiple
1145 for (p = v->name; *p; p++)
1146 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1158 /* If OBJ not recognised ignore it */
1159 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1161 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1163 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1168 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1170 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1175 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1177 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1183 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1185 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1190 if (!add_DN_object(subj, v->value, def, value, nid,
1191 n_min, n_max, chtype, mval))
1194 if (X509_NAME_entry_count(subj) == 0) {
1195 BIO_printf(bio_err, "error, no objects specified in config file\n");
1200 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1203 "\nPlease enter the following 'extra' attributes\n");
1205 "to be sent with your certificate request\n");
1212 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1215 v = sk_CONF_VALUE_value(attr_sk, i);
1217 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1220 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1222 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1228 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1230 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1236 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1238 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1243 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1245 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1250 if (!add_attribute_object(req,
1251 v->value, def, value, nid, n_min,
1257 BIO_printf(bio_err, "No template, please set one up.\n");
1265 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1266 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1267 unsigned long chtype)
1269 int i, spec_char, plus_char;
1275 subj = X509_REQ_get_subject_name(req);
1277 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1279 v = sk_CONF_VALUE_value(dn_sk, i);
1283 * Skip past any leading X. X: X, etc to allow for multiple instances
1285 for (p = v->name; *p; p++) {
1286 #ifndef CHARSET_EBCDIC
1287 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1289 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1290 || (*p == os_toascii['.']));
1299 #ifndef CHARSET_EBCDIC
1300 plus_char = (*type == '+');
1302 plus_char = (*type == os_toascii['+']);
1310 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1311 (unsigned char *)v->value, -1, -1,
1317 if (!X509_NAME_entry_count(subj)) {
1318 BIO_printf(bio_err, "error, no objects specified in config file\n");
1322 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1323 v = sk_CONF_VALUE_value(attr_sk, i);
1324 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1325 (unsigned char *)v->value, -1))
1332 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1333 char *value, int nid, int n_min, int n_max,
1334 unsigned long chtype, int mval)
1339 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1340 "DN value", "DN default");
1341 if ((ret == 0) || (ret == 1))
1345 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1346 (unsigned char *)buf, -1, -1, mval))
1352 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1353 char *value, int nid, int n_min,
1354 int n_max, unsigned long chtype)
1359 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1360 "Attribute value", "Attribute default");
1361 if ((ret == 0) || (ret == 1))
1365 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1366 (unsigned char *)buf, -1)) {
1367 BIO_printf(bio_err, "Error adding attribute\n");
1368 ERR_print_errors(bio_err);
1376 static int build_data(char *text, const char *def,
1377 char *value, int n_min, int n_max,
1378 char *buf, const int buf_size,
1379 const char *desc1, const char *desc2
1385 BIO_printf(bio_err, "%s [%s]:", text, def);
1386 (void)BIO_flush(bio_err);
1387 if (value != NULL) {
1388 if (!join(buf, buf_size, value, "\n", desc1))
1390 BIO_printf(bio_err, "%s\n", value);
1394 if (!fgets(buf, buf_size, stdin))
1404 if (buf[0] == '\n') {
1405 if ((def == NULL) || (def[0] == '\0'))
1407 if (!join(buf, buf_size, def, "\n", desc2))
1409 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1414 if (buf[i - 1] != '\n') {
1415 BIO_printf(bio_err, "weird input :-(\n");
1419 #ifdef CHARSET_EBCDIC
1420 ebcdic2ascii(buf, buf, i);
1422 if (!req_check_len(i, n_min, n_max)) {
1430 static int req_check_len(int len, int n_min, int n_max)
1432 if ((n_min > 0) && (len < n_min)) {
1434 "string is too short, it needs to be at least %d bytes long\n",
1438 if ((n_max >= 0) && (len > n_max)) {
1440 "string is too long, it needs to be no more than %d bytes long\n",
1447 /* Check if the end of a string matches 'end' */
1448 static int check_end(const char *str, const char *end)
1457 tmp = str + slen - elen;
1458 return strcmp(tmp, end);
1462 * Merge the two strings together into the result buffer checking for
1463 * overflow and producing an error message if there is.
1465 static int join(char buf[], size_t buf_size, const char *name,
1466 const char *tail, const char *desc)
1468 const size_t name_len = strlen(name), tail_len = strlen(tail);
1470 if (name_len + tail_len + 1 > buf_size) {
1471 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1474 memcpy(buf, name, name_len);
1475 memcpy(buf + name_len, tail, tail_len + 1);
1479 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1480 int *pkey_type, long *pkeylen,
1481 char **palgnam, ENGINE *keygen_engine)
1483 EVP_PKEY_CTX *gctx = NULL;
1484 EVP_PKEY *param = NULL;
1487 const char *paramfile = NULL;
1490 *pkey_type = EVP_PKEY_RSA;
1492 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1493 *pkey_type = EVP_PKEY_RSA;
1494 keylen = atol(gstr);
1496 } else if (strncmp(gstr, "param:", 6) == 0) {
1497 paramfile = gstr + 6;
1499 const char *p = strchr(gstr, ':');
1502 const EVP_PKEY_ASN1_METHOD *ameth;
1509 * The lookup of a the string will cover all engines so keep a note
1510 * of the implementation.
1513 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1515 if (ameth == NULL) {
1516 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1520 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1521 #ifndef OPENSSL_NO_ENGINE
1522 ENGINE_finish(tmpeng);
1524 if (*pkey_type == EVP_PKEY_RSA) {
1526 keylen = atol(p + 1);
1531 } else if (p != NULL) {
1536 if (paramfile != NULL) {
1537 pbio = BIO_new_file(paramfile, "r");
1539 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1542 param = PEM_read_bio_Parameters(pbio, NULL);
1544 if (param == NULL) {
1547 (void)BIO_reset(pbio);
1548 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1550 param = X509_get_pubkey(x);
1557 if (param == NULL) {
1558 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1561 if (*pkey_type == -1) {
1562 *pkey_type = EVP_PKEY_id(param);
1563 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1564 BIO_printf(bio_err, "Key Type does not match parameters\n");
1565 EVP_PKEY_free(param);
1570 if (palgnam != NULL) {
1571 const EVP_PKEY_ASN1_METHOD *ameth;
1575 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1576 if (ameth == NULL) {
1577 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1580 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1581 *palgnam = OPENSSL_strdup(anam);
1582 #ifndef OPENSSL_NO_ENGINE
1583 ENGINE_finish(tmpeng);
1587 if (param != NULL) {
1588 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1589 *pkeylen = EVP_PKEY_bits(param);
1590 EVP_PKEY_free(param);
1592 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1596 BIO_puts(bio_err, "Error allocating keygen context\n");
1597 ERR_print_errors(bio_err);
1601 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1602 BIO_puts(bio_err, "Error initializing keygen context\n");
1603 ERR_print_errors(bio_err);
1604 EVP_PKEY_CTX_free(gctx);
1607 #ifndef OPENSSL_NO_RSA
1608 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1609 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1610 BIO_puts(bio_err, "Error setting RSA keysize\n");
1611 ERR_print_errors(bio_err);
1612 EVP_PKEY_CTX_free(gctx);
1621 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1624 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1626 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1635 BIO_write(b, &c, 1);
1640 static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts)
1647 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1648 char *opt = sk_OPENSSL_STRING_value(opts, i);
1649 if (pkey_ctrl_string(pkctx, opt) <= 0) {
1650 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1651 ERR_print_errors(bio_err);
1659 static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts)
1666 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1667 char *opt = sk_OPENSSL_STRING_value(opts, i);
1668 if (x509_ctrl_string(x, opt) <= 0) {
1669 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1670 ERR_print_errors(bio_err);
1678 static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts)
1685 for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) {
1686 char *opt = sk_OPENSSL_STRING_value(opts, i);
1687 if (x509_req_ctrl_string(x, opt) <= 0) {
1688 BIO_printf(bio_err, "parameter error \"%s\"\n", opt);
1689 ERR_print_errors(bio_err);
1697 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1698 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1700 EVP_PKEY_CTX *pkctx = NULL;
1706 * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is mandatory
1707 * for this algorithm.
1709 if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) == 2
1710 && def_nid == NID_undef) {
1711 /* The signing algorithm requires there to be no digest */
1714 return EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey)
1715 && do_pkey_ctx_init(pkctx, sigopts);
1718 int do_X509_sign(X509 *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_sign_ctx(x, mctx) > 0);
1726 EVP_MD_CTX_free(mctx);
1730 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1731 STACK_OF(OPENSSL_STRING) *sigopts)
1734 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1736 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1737 rv = (X509_REQ_sign_ctx(x, mctx) > 0);
1738 EVP_MD_CTX_free(mctx);
1742 int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts)
1746 if (do_x509_init(x, vfyopts) > 0)
1747 rv = (X509_verify(x, pkey) > 0);
1751 int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey,
1752 STACK_OF(OPENSSL_STRING) *vfyopts)
1756 if (do_x509_req_init(x, vfyopts) > 0)
1757 rv = (X509_REQ_verify(x, pkey) > 0);
1761 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1762 STACK_OF(OPENSSL_STRING) *sigopts)
1765 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1767 if (do_sign_init(mctx, pkey, md, sigopts) > 0)
1768 rv = (X509_CRL_sign_ctx(x, mctx) > 0);
1769 EVP_MD_CTX_free(mctx);