1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to. The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 * must display the following acknowledgement:
32 * "This product includes cryptographic software written by
33 * Eric Young (eay@cryptsoft.com)"
34 * The word 'cryptographic' can be left out if the rouines from the library
35 * being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 * the apps directory (application code) you must include an acknowledgement:
38 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed. i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
63 #include <openssl/bio.h>
64 #include <openssl/evp.h>
65 #include <openssl/conf.h>
66 #include <openssl/err.h>
67 #include <openssl/asn1.h>
68 #include <openssl/x509.h>
69 #include <openssl/x509v3.h>
70 #include <openssl/objects.h>
71 #include <openssl/pem.h>
72 #include <openssl/bn.h>
73 #ifndef OPENSSL_NO_RSA
74 # include <openssl/rsa.h>
76 #ifndef OPENSSL_NO_DSA
77 # include <openssl/dsa.h>
82 #define BITS "default_bits"
83 #define KEYFILE "default_keyfile"
84 #define PROMPT "prompt"
85 #define DISTINGUISHED_NAME "distinguished_name"
86 #define ATTRIBUTES "attributes"
87 #define V3_EXTENSIONS "x509_extensions"
88 #define REQ_EXTENSIONS "req_extensions"
89 #define STRING_MASK "string_mask"
90 #define UTF8_IN "utf8"
92 #define DEFAULT_KEY_LENGTH 2048
93 #define MIN_KEY_LENGTH 512
95 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
96 int attribs, unsigned long chtype);
97 static int build_subject(X509_REQ *req, char *subj, unsigned long chtype,
99 static int prompt_info(X509_REQ *req,
100 STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
101 STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect,
102 int attribs, unsigned long chtype);
103 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
104 STACK_OF(CONF_VALUE) *attr, int attribs,
105 unsigned long chtype);
106 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
107 char *value, int nid, int n_min, int n_max,
108 unsigned long chtype);
109 static int add_DN_object(X509_NAME *n, char *text, const char *def,
110 char *value, int nid, int n_min, int n_max,
111 unsigned long chtype, int mval);
112 static int genpkey_cb(EVP_PKEY_CTX *ctx);
113 static int req_check_len(int len, int n_min, int n_max);
114 static int check_end(const char *str, const char *end);
115 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
116 int *pkey_type, long *pkeylen,
117 char **palgnam, ENGINE *keygen_engine);
118 static CONF *req_conf = NULL;
119 static int batch = 0;
121 typedef enum OPTION_choice {
122 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
123 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
124 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
125 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_RAND, OPT_NEWKEY,
126 OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
127 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
128 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
129 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_EXTENSIONS,
133 OPTIONS req_options[] = {
134 {"help", OPT_HELP, '-', "Display this summary"},
135 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
136 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
137 {"in", OPT_IN, '<', "Input file"},
138 {"out", OPT_OUT, '>', "Output file"},
139 {"key", OPT_KEY, 's', "Private key to use"},
140 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
141 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
142 {"new", OPT_NEW, '-', "New request"},
143 {"config", OPT_CONFIG, '<', "Request template file"},
144 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
145 {"passin", OPT_PASSIN, 's', "Private key password source"},
146 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
147 {"rand", OPT_RAND, 's',
148 "Load the file(s) into the random number generator"},
149 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
150 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
151 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
152 {"batch", OPT_BATCH, '-',
153 "Do not ask anything during request generation"},
154 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
155 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
156 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
157 {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
158 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
159 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
160 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
161 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
162 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
163 {"text", OPT_TEXT, '-', "Text form of request"},
164 {"x509", OPT_X509, '-',
165 "Output a x509 structure instead of a cert request"},
166 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
167 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
168 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
169 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
170 "Enable support for multivalued RDNs"},
171 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
172 {"set_serial", OPT_SET_SERIAL, 'p', "Serial number to use"},
173 {"extensions", OPT_EXTENSIONS, 's',
174 "Cert extension section (override value in config file)"},
175 {"reqexts", OPT_REQEXTS, 's',
176 "Request extension section (override value in config file)"},
177 {"", OPT_MD, '-', "Any supported digest"},
178 #ifndef OPENSSL_NO_ENGINE
179 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
180 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
181 "Specify engine to be used for key generation operations"},
186 int req_main(int argc, char **argv)
188 ASN1_INTEGER *serial = NULL;
189 BIO *in = NULL, *out = NULL;
190 ENGINE *e = NULL, *gen_eng = NULL;
191 EVP_PKEY *pkey = NULL;
192 EVP_PKEY_CTX *genctx = NULL;
193 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
195 X509_REQ *req = NULL;
196 const EVP_CIPHER *cipher = NULL;
197 const EVP_MD *md_alg = NULL, *digest = NULL;
198 char *extensions = NULL, *infile = NULL;
199 char *outfile = NULL, *keyfile = NULL, *inrand = NULL;
200 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
201 char *passin = NULL, *passout = NULL, *req_exts = NULL, *subj = NULL;
202 char *template = default_config_file, *keyout = NULL;
203 const char *keyalg = NULL;
205 int ret = 1, x509 = 0, days = 30, i = 0, newreq = 0, verbose = 0;
206 int pkey_type = -1, private = 0;
207 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
208 int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
209 int nodes = 0, newhdr = 0, subject = 0, pubkey = 0;
211 unsigned long chtype = MBSTRING_ASC, nmflag = 0, reqflag = 0;
214 #ifndef OPENSSL_NO_DES
215 cipher = EVP_des_ede3_cbc();
218 prog = opt_init(argc, argv, req_options);
219 while ((o = opt_next()) != OPT_EOF) {
224 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
227 opt_help(req_options);
231 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
235 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
239 e = setup_engine(opt_arg(), 0);
241 case OPT_KEYGEN_ENGINE:
242 #ifndef OPENSSL_NO_ENGINE
243 gen_eng = ENGINE_by_id(opt_arg());
244 if (gen_eng == NULL) {
245 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
260 template = opt_arg();
263 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
276 passargin = opt_arg();
279 passargout = opt_arg();
290 pkeyopts = sk_OPENSSL_STRING_new_null();
291 if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
296 sigopts = sk_OPENSSL_STRING_new_null();
297 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
322 chtype = MBSTRING_UTF8;
326 if (!set_name_ex(&nmflag, opt_arg()))
330 if (!set_cert_ex(&reqflag, opt_arg()))
340 days = atoi(opt_arg());
343 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
353 case OPT_MULTIVALUE_RDN:
357 extensions = opt_arg();
360 req_exts = opt_arg();
363 if (!opt_md(opt_unknown(), &md_alg))
369 argc = opt_num_rest();
374 nmflag = XN_FLAG_ONELINE;
376 private = newreq && (pkey == NULL) ? 1 : 0;
378 if (!app_passwd(passargin, passargout, &passin, &passout)) {
379 BIO_printf(bio_err, "Error getting passwords\n");
384 BIO_printf(bio_err, "Using configuration from %s\n", template);
385 req_conf = app_load_config(template);
386 if (!app_load_modules(req_conf))
389 if (req_conf != NULL) {
390 p = NCONF_get_string(req_conf, NULL, "oid_file");
396 oid_bio = BIO_new_file(p, "r");
397 if (oid_bio == NULL) {
399 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
400 ERR_print_errors(bio_err);
403 OBJ_create_objects(oid_bio);
408 if (!add_oid_section(req_conf))
411 if (md_alg == NULL) {
412 p = NCONF_get_string(req_conf, SECTION, "default_md");
416 if (!opt_md(p, &md_alg))
423 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
428 /* Check syntax of file */
430 X509V3_set_ctx_test(&ctx);
431 X509V3_set_nconf(&ctx, req_conf);
432 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
434 "Error Loading extension section %s\n", extensions);
440 passin = NCONF_get_string(req_conf, SECTION, "input_password");
446 passout = NCONF_get_string(req_conf, SECTION, "output_password");
451 p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
455 if (p && !ASN1_STRING_set_default_mask_asc(p)) {
456 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
460 if (chtype != MBSTRING_UTF8) {
461 p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
464 else if (strcmp(p, "yes") == 0)
465 chtype = MBSTRING_UTF8;
469 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
474 /* Check syntax of file */
476 X509V3_set_ctx_test(&ctx);
477 X509V3_set_nconf(&ctx, req_conf);
478 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
480 "Error Loading request extension section %s\n",
486 if (keyfile != NULL) {
487 pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
489 /* load_key() has already printed an appropriate message */
492 char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
493 if (randfile == NULL)
495 app_RAND_load_file(randfile, 0);
499 if (newreq && (pkey == NULL)) {
500 char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
501 if (randfile == NULL)
503 app_RAND_load_file(randfile, 0);
505 app_RAND_load_files(inrand);
507 if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
508 newkey = DEFAULT_KEY_LENGTH;
512 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
513 &keyalgstr, gen_eng);
518 if (newkey < MIN_KEY_LENGTH
519 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
520 BIO_printf(bio_err, "private key length is too short,\n");
521 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
522 MIN_KEY_LENGTH, newkey);
527 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
528 &keyalgstr, gen_eng);
535 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
536 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
537 if (pkey_ctrl_string(genctx, genopt) <= 0) {
538 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
539 ERR_print_errors(bio_err);
545 BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
548 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
549 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
551 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
552 BIO_puts(bio_err, "Error Generating Key\n");
556 EVP_PKEY_CTX_free(genctx);
559 app_RAND_write_file(randfile);
561 if (keyout == NULL) {
562 keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
568 BIO_printf(bio_err, "writing new private key to stdout\n");
570 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
571 out = bio_open_owner(keyout, outformat, private);
575 p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
578 p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
582 if ((p != NULL) && (strcmp(p, "no") == 0))
590 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
591 NULL, 0, NULL, passout)) {
592 if ((ERR_GET_REASON(ERR_peek_error()) ==
593 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
602 BIO_printf(bio_err, "-----\n");
606 in = bio_open_default(infile, 'r', informat);
610 if (informat == FORMAT_ASN1)
611 req = d2i_X509_REQ_bio(in, NULL);
613 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
615 BIO_printf(bio_err, "unable to load X509 request\n");
620 if (newreq || x509) {
622 BIO_printf(bio_err, "you need to specify a private key\n");
627 req = X509_REQ_new();
632 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
633 subj = NULL; /* done processing '-subj' option */
635 BIO_printf(bio_err, "problems making Certificate Request\n");
642 if ((x509ss = X509_new()) == NULL)
645 /* Set version to V3 */
646 if (extensions && !X509_set_version(x509ss, 2))
649 if (!X509_set_serialNumber(x509ss, serial))
652 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
656 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
658 if (!X509_gmtime_adj(X509_get_notBefore(x509ss), 0))
660 if (!X509_time_adj_ex(X509_get_notAfter(x509ss), days, 0, NULL))
662 if (!X509_set_subject_name
663 (x509ss, X509_REQ_get_subject_name(req)))
665 tmppkey = X509_REQ_get_pubkey(req);
666 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
668 EVP_PKEY_free(tmppkey);
670 /* Set up V3 context struct */
672 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
673 X509V3_set_nconf(&ext_ctx, req_conf);
676 if (extensions && !X509V3_EXT_add_nconf(req_conf,
677 &ext_ctx, extensions,
679 BIO_printf(bio_err, "Error Loading extension section %s\n",
684 i = do_X509_sign(x509ss, pkey, digest, sigopts);
686 ERR_print_errors(bio_err);
692 /* Set up V3 context struct */
694 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
695 X509V3_set_nconf(&ext_ctx, req_conf);
698 if (req_exts && !X509V3_EXT_REQ_add_nconf(req_conf,
701 BIO_printf(bio_err, "Error Loading extension section %s\n",
705 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
707 ERR_print_errors(bio_err);
714 BIO_printf(bio_err, "Cannot modify certificate subject\n");
720 BIO_printf(bio_err, "Modifying Request's Subject\n");
721 print_name(bio_err, "old subject=",
722 X509_REQ_get_subject_name(req), nmflag);
725 if (build_subject(req, subj, chtype, multirdn) == 0) {
726 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
732 print_name(bio_err, "new subject=",
733 X509_REQ_get_subject_name(req), nmflag);
737 if (verify && !x509) {
741 pkey = X509_REQ_get_pubkey(req);
747 i = X509_REQ_verify(req, pkey);
756 BIO_printf(bio_err, "verify failure\n");
757 ERR_print_errors(bio_err);
758 } else /* if (i > 0) */
759 BIO_printf(bio_err, "verify OK\n");
762 if (noout && !text && !modulus && !subject && !pubkey) {
767 out = bio_open_default(outfile,
768 keyout != NULL && outfile != NULL &&
769 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
776 tpubkey = X509_REQ_get_pubkey(req);
777 if (tpubkey == NULL) {
778 BIO_printf(bio_err, "Error getting public key\n");
779 ERR_print_errors(bio_err);
782 PEM_write_bio_PUBKEY(out, tpubkey);
783 EVP_PKEY_free(tpubkey);
788 X509_print_ex(out, x509ss, nmflag, reqflag);
790 X509_REQ_print_ex(out, req, nmflag, reqflag);
795 print_name(out, "subject=", X509_get_subject_name(x509ss),
798 print_name(out, "subject=", X509_REQ_get_subject_name(req),
806 tpubkey = X509_get_pubkey(x509ss);
808 tpubkey = X509_REQ_get_pubkey(req);
809 if (tpubkey == NULL) {
810 fprintf(stdout, "Modulus=unavailable\n");
813 fprintf(stdout, "Modulus=");
814 #ifndef OPENSSL_NO_RSA
815 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA)
816 BN_print(out, EVP_PKEY_get0_RSA(tpubkey)->n);
819 fprintf(stdout, "Wrong Algorithm type");
820 EVP_PKEY_free(tpubkey);
821 fprintf(stdout, "\n");
824 if (!noout && !x509) {
825 if (outformat == FORMAT_ASN1)
826 i = i2d_X509_REQ_bio(out, req);
828 i = PEM_write_bio_X509_REQ_NEW(out, req);
830 i = PEM_write_bio_X509_REQ(out, req);
832 BIO_printf(bio_err, "unable to write X509 request\n");
836 if (!noout && x509 && (x509ss != NULL)) {
837 if (outformat == FORMAT_ASN1)
838 i = i2d_X509_bio(out, x509ss);
840 i = PEM_write_bio_X509(out, x509ss);
842 BIO_printf(bio_err, "unable to write X509 certificate\n");
849 ERR_print_errors(bio_err);
851 NCONF_free(req_conf);
855 EVP_PKEY_CTX_free(genctx);
856 sk_OPENSSL_STRING_free(pkeyopts);
857 sk_OPENSSL_STRING_free(sigopts);
858 #ifndef OPENSSL_NO_ENGINE
859 ENGINE_free(gen_eng);
861 OPENSSL_free(keyalgstr);
864 ASN1_INTEGER_free(serial);
865 OPENSSL_free(passin);
866 OPENSSL_free(passout);
871 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
872 int attribs, unsigned long chtype)
876 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
877 char *tmp, *dn_sect, *attr_sect;
879 tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
882 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
885 dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
886 if (dn_sect == NULL) {
887 BIO_printf(bio_err, "unable to find '%s' in config\n",
891 dn_sk = NCONF_get_section(req_conf, dn_sect);
893 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
897 attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
898 if (attr_sect == NULL) {
902 attr_sk = NCONF_get_section(req_conf, attr_sect);
903 if (attr_sk == NULL) {
904 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
909 /* setup version number */
910 if (!X509_REQ_set_version(req, 0L))
911 goto err; /* version 1 */
914 i = build_subject(req, subj, chtype, multirdn);
916 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
918 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
923 if (!X509_REQ_set_pubkey(req, pkey))
932 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
933 * where characters may be escaped by \
935 static int build_subject(X509_REQ *req, char *subject, unsigned long chtype,
940 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
943 if (!X509_REQ_set_subject_name(req, n)) {
951 static int prompt_info(X509_REQ *req,
952 STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
953 STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect,
954 int attribs, unsigned long chtype)
965 subj = X509_REQ_get_subject_name(req);
969 "You are about to be asked to enter information that will be incorporated\n");
970 BIO_printf(bio_err, "into your certificate request.\n");
972 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
974 "There are quite a few fields but you can leave some blank\n");
976 "For some fields there will be a default value,\n");
978 "If you enter '.', the field will be left blank.\n");
979 BIO_printf(bio_err, "-----\n");
982 if (sk_CONF_VALUE_num(dn_sk)) {
986 if (sk_CONF_VALUE_num(dn_sk) <= i)
989 v = sk_CONF_VALUE_value(dn_sk, i);
992 if (!check_end(type, "_min") || !check_end(type, "_max") ||
993 !check_end(type, "_default") || !check_end(type, "_value"))
996 * Skip past any leading X. X: X, etc to allow for multiple
999 for (p = v->name; *p; p++)
1000 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1011 /* If OBJ not recognised ignore it */
1012 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1014 if (BIO_snprintf(buf, sizeof buf, "%s_default", v->name)
1015 >= (int)sizeof(buf)) {
1016 BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1020 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1025 BIO_snprintf(buf, sizeof buf, "%s_value", v->name);
1026 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1031 BIO_snprintf(buf, sizeof buf, "%s_min", v->name);
1032 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1037 BIO_snprintf(buf, sizeof buf, "%s_max", v->name);
1038 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1043 if (!add_DN_object(subj, v->value, def, value, nid,
1044 n_min, n_max, chtype, mval))
1047 if (X509_NAME_entry_count(subj) == 0) {
1049 "error, no objects specified in config file\n");
1054 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1057 "\nPlease enter the following 'extra' attributes\n");
1059 "to be sent with your certificate request\n");
1065 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1068 v = sk_CONF_VALUE_value(attr_sk, i);
1070 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1073 if (BIO_snprintf(buf, sizeof buf, "%s_default", type)
1074 >= (int)sizeof(buf)) {
1075 BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1079 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1085 BIO_snprintf(buf, sizeof buf, "%s_value", type);
1086 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1092 BIO_snprintf(buf, sizeof buf, "%s_min", type);
1093 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1098 BIO_snprintf(buf, sizeof buf, "%s_max", type);
1099 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1104 if (!add_attribute_object(req,
1105 v->value, def, value, nid, n_min,
1111 BIO_printf(bio_err, "No template, please set one up.\n");
1119 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1120 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1121 unsigned long chtype)
1123 int i, spec_char, plus_char;
1129 subj = X509_REQ_get_subject_name(req);
1131 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1133 v = sk_CONF_VALUE_value(dn_sk, i);
1137 * Skip past any leading X. X: X, etc to allow for multiple instances
1139 for (p = v->name; *p; p++) {
1140 #ifndef CHARSET_EBCDIC
1141 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1143 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1144 || (*p == os_toascii['.']));
1153 #ifndef CHARSET_EBCDIC
1154 plus_char = (*p == '+');
1156 plus_char = (*p == os_toascii['+']);
1163 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1164 (unsigned char *)v->value, -1, -1,
1170 if (!X509_NAME_entry_count(subj)) {
1171 BIO_printf(bio_err, "error, no objects specified in config file\n");
1175 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1176 v = sk_CONF_VALUE_value(attr_sk, i);
1177 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1178 (unsigned char *)v->value, -1))
1185 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1186 char *value, int nid, int n_min, int n_max,
1187 unsigned long chtype, int mval)
1193 BIO_printf(bio_err, "%s [%s]:", text, def);
1194 (void)BIO_flush(bio_err);
1195 if (value != NULL) {
1196 OPENSSL_strlcpy(buf, value, sizeof buf);
1197 OPENSSL_strlcat(buf, "\n", sizeof buf);
1198 BIO_printf(bio_err, "%s\n", value);
1202 if (!fgets(buf, sizeof buf, stdin))
1212 else if (buf[0] == '\n') {
1213 if ((def == NULL) || (def[0] == '\0'))
1215 OPENSSL_strlcpy(buf, def, sizeof buf);
1216 OPENSSL_strlcat(buf, "\n", sizeof buf);
1217 } else if ((buf[0] == '.') && (buf[1] == '\n'))
1221 if (buf[i - 1] != '\n') {
1222 BIO_printf(bio_err, "weird input :-(\n");
1226 #ifdef CHARSET_EBCDIC
1227 ebcdic2ascii(buf, buf, i);
1229 if (!req_check_len(i, n_min, n_max)) {
1235 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1236 (unsigned char *)buf, -1, -1, mval))
1243 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1244 char *value, int nid, int n_min,
1245 int n_max, unsigned long chtype)
1248 static char buf[1024];
1252 BIO_printf(bio_err, "%s [%s]:", text, def);
1253 (void)BIO_flush(bio_err);
1254 if (value != NULL) {
1255 OPENSSL_strlcpy(buf, value, sizeof buf);
1256 OPENSSL_strlcat(buf, "\n", sizeof buf);
1257 BIO_printf(bio_err, "%s\n", value);
1261 if (!fgets(buf, sizeof buf, stdin))
1271 else if (buf[0] == '\n') {
1272 if ((def == NULL) || (def[0] == '\0'))
1274 OPENSSL_strlcpy(buf, def, sizeof buf);
1275 OPENSSL_strlcat(buf, "\n", sizeof buf);
1276 } else if ((buf[0] == '.') && (buf[1] == '\n'))
1280 if (buf[i - 1] != '\n') {
1281 BIO_printf(bio_err, "weird input :-(\n");
1285 #ifdef CHARSET_EBCDIC
1286 ebcdic2ascii(buf, buf, i);
1288 if (!req_check_len(i, n_min, n_max)) {
1294 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1295 (unsigned char *)buf, -1)) {
1296 BIO_printf(bio_err, "Error adding attribute\n");
1297 ERR_print_errors(bio_err);
1306 static int req_check_len(int len, int n_min, int n_max)
1308 if ((n_min > 0) && (len < n_min)) {
1310 "string is too short, it needs to be at least %d bytes long\n",
1314 if ((n_max >= 0) && (len > n_max)) {
1316 "string is too long, it needs to be less than %d bytes long\n",
1323 /* Check if the end of a string matches 'end' */
1324 static int check_end(const char *str, const char *end)
1332 tmp = str + slen - elen;
1333 return strcmp(tmp, end);
1336 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1337 int *pkey_type, long *pkeylen,
1338 char **palgnam, ENGINE *keygen_engine)
1340 EVP_PKEY_CTX *gctx = NULL;
1341 EVP_PKEY *param = NULL;
1344 const char *paramfile = NULL;
1347 *pkey_type = EVP_PKEY_RSA;
1349 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1350 *pkey_type = EVP_PKEY_RSA;
1351 keylen = atol(gstr);
1353 } else if (strncmp(gstr, "param:", 6) == 0)
1354 paramfile = gstr + 6;
1356 const char *p = strchr(gstr, ':');
1359 const EVP_PKEY_ASN1_METHOD *ameth;
1366 * The lookup of a the string will cover all engines so keep a note
1367 * of the implementation.
1370 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1373 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1377 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1378 #ifndef OPENSSL_NO_ENGINE
1379 ENGINE_finish(tmpeng);
1381 if (*pkey_type == EVP_PKEY_RSA) {
1383 keylen = atol(p + 1);
1392 pbio = BIO_new_file(paramfile, "r");
1394 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1397 param = PEM_read_bio_Parameters(pbio, NULL);
1401 (void)BIO_reset(pbio);
1402 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1404 param = X509_get_pubkey(x);
1412 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1415 if (*pkey_type == -1)
1416 *pkey_type = EVP_PKEY_id(param);
1417 else if (*pkey_type != EVP_PKEY_base_id(param)) {
1418 BIO_printf(bio_err, "Key Type does not match parameters\n");
1419 EVP_PKEY_free(param);
1425 const EVP_PKEY_ASN1_METHOD *ameth;
1428 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1430 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1433 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1434 *palgnam = OPENSSL_strdup(anam);
1435 #ifndef OPENSSL_NO_ENGINE
1436 ENGINE_finish(tmpeng);
1441 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1442 *pkeylen = EVP_PKEY_bits(param);
1443 EVP_PKEY_free(param);
1445 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1448 BIO_puts(bio_err, "Error allocating keygen context\n");
1449 ERR_print_errors(bio_err);
1453 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1454 BIO_puts(bio_err, "Error initializing keygen context\n");
1455 ERR_print_errors(bio_err);
1456 EVP_PKEY_CTX_free(gctx);
1459 #ifndef OPENSSL_NO_RSA
1460 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1461 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1462 BIO_puts(bio_err, "Error setting RSA keysize\n");
1463 ERR_print_errors(bio_err);
1464 EVP_PKEY_CTX_free(gctx);
1473 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1476 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1478 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1487 BIO_write(b, &c, 1);
1492 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1493 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1495 EVP_PKEY_CTX *pkctx = NULL;
1500 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1502 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1503 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1504 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1505 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1506 ERR_print_errors(bio_err);
1513 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1514 STACK_OF(OPENSSL_STRING) *sigopts)
1517 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1519 rv = do_sign_init(mctx, pkey, md, sigopts);
1520 /* Note: X509_sign_ctx() calls ASN1_item_sign_ctx(), which destroys
1521 * the EVP_MD_CTX we send it, so only destroy it here if the former
1524 rv = X509_sign_ctx(x, mctx);
1526 EVP_MD_CTX_free(mctx);
1527 return rv > 0 ? 1 : 0;
1530 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1531 STACK_OF(OPENSSL_STRING) *sigopts)
1534 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1535 rv = do_sign_init(mctx, pkey, md, sigopts);
1536 /* Note: X509_REQ_sign_ctx() calls ASN1_item_sign_ctx(), which destroys
1537 * the EVP_MD_CTX we send it, so only destroy it here if the former
1540 rv = X509_REQ_sign_ctx(x, mctx);
1542 EVP_MD_CTX_free(mctx);
1543 return rv > 0 ? 1 : 0;
1546 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1547 STACK_OF(OPENSSL_STRING) *sigopts)
1550 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1551 rv = do_sign_init(mctx, pkey, md, sigopts);
1552 /* Note: X509_CRL_sign_ctx() calls ASN1_item_sign_ctx(), which destroys
1553 * the EVP_MD_CTX we send it, so only destroy it here if the former
1556 rv = X509_CRL_sign_ctx(x, mctx);
1558 EVP_MD_CTX_free(mctx);
1559 return rv > 0 ? 1 : 0;