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 512
93 #define MIN_KEY_LENGTH 384
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_SUBJECT
, OPT_TEXT
, OPT_X509
,
129 OPT_ASN1_KLUDGE
, OPT_NO_ASN1_KLUDGE
, OPT_MULTIVALUE_RDN
,
130 OPT_DAYS
, OPT_SET_SERIAL
, OPT_EXTENSIONS
, OPT_REQEXTS
, OPT_MD
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
, '<', "Use the private key contained in file"},
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'},
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'},
151 {"sigopt", OPT_SIGOPT
, 's'},
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
, '-'},
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 {"asn1-kludge", OPT_ASN1_KLUDGE
, '-',
167 "Output the request in a format that is wrong"},
168 {OPT_MORE_STR
, 1, 1, "(Required by some CA's)"},
169 {"no-asn1-kludge", OPT_NO_ASN1_KLUDGE
, '-'},
170 {"subject", OPT_SUBJECT
, 's', "Output the request's subject"},
171 {"multivalue-rdn", OPT_MULTIVALUE_RDN
, '-',
172 "Enable support for multivalued RDNs"},
173 {"days", OPT_DAYS
, 'p', "Number of days cert is valid for"},
174 {"set-serial", OPT_SET_SERIAL
, 'p', "Serial number to use"},
175 {"extensions", OPT_EXTENSIONS
, 's',
176 "Cert extension section (override value in config file)"},
177 {"reqexts", OPT_REQEXTS
, 's',
178 "Request extension section (override value in config file)"},
179 #ifndef OPENSSL_NO_ENGINE
180 {"engine", OPT_ENGINE
, 's', "Use engine, possibly a hardware device"},
181 {"keygen_engine", OPT_KEYGEN_ENGINE
, 's'},
183 {"", OPT_MD
, '-', "Any supported digest"},
187 int req_main(int argc
, char **argv
)
189 ASN1_INTEGER
*serial
= NULL
;
190 BIO
*in
= NULL
, *out
= NULL
;
191 ENGINE
*e
= NULL
, *gen_eng
= NULL
;
192 EVP_PKEY
*pkey
= NULL
;
193 EVP_PKEY_CTX
*genctx
= NULL
;
194 STACK_OF(OPENSSL_STRING
) *pkeyopts
= NULL
, *sigopts
= NULL
;
196 X509_REQ
*req
= NULL
;
197 const EVP_CIPHER
*cipher
= NULL
;
198 const EVP_MD
*md_alg
= NULL
, *digest
= NULL
;
199 char *extensions
= NULL
, *infile
= NULL
;
200 char *outfile
= NULL
, *keyfile
= NULL
, *inrand
= NULL
;
201 char *keyalgstr
= NULL
, *p
, *prog
, *passargin
= NULL
, *passargout
= NULL
;
202 char *passin
= NULL
, *passout
= NULL
, *req_exts
= NULL
, *subj
= NULL
;
203 char *template = NULL
, *keyout
= NULL
;
204 const char *keyalg
= NULL
;
206 int ret
= 1, x509
= 0, days
= 30, i
= 0, newreq
= 0, verbose
=
208 int informat
= FORMAT_PEM
, outformat
= FORMAT_PEM
, keyform
= FORMAT_PEM
;
209 int modulus
= 0, multirdn
= 0, verify
= 0, noout
= 0, text
= 0;
210 int nodes
= 0, kludge
= 0, newhdr
= 0, subject
= 0, pubkey
= 0;
212 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 (void)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_PEMDER
, &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
;
325 if (!set_name_ex(&nmflag
, opt_arg()))
329 if (!set_cert_ex(&reqflag
, opt_arg()))
338 case OPT_ASN1_KLUDGE
:
341 case OPT_NO_ASN1_KLUDGE
:
346 days
= atoi(opt_arg());
349 serial
= s2i_ASN1_INTEGER(NULL
, opt_arg());
356 case OPT_MULTIVALUE_RDN
:
360 extensions
= opt_arg();
363 req_exts
= opt_arg();
366 if (!opt_md(opt_unknown(), &md_alg
))
372 argc
= opt_num_rest();
375 if (!app_passwd(passargin
, passargout
, &passin
, &passout
)) {
376 BIO_printf(bio_err
, "Error getting passwords\n");
380 if (template != NULL
) {
384 BIO_printf(bio_err
, "Using configuration from %s\n", template);
385 req_conf
= NCONF_new(NULL
);
386 i
= NCONF_load(req_conf
, template, &errline
);
388 BIO_printf(bio_err
, "error on line %ld of %s\n", errline
,
395 if (req_conf
== NULL
) {
396 BIO_printf(bio_err
, "Unable to load config info from %s\n",
397 default_config_file
);
401 BIO_printf(bio_err
, "Using configuration from %s\n",
402 default_config_file
);
405 if (req_conf
!= NULL
) {
406 p
= NCONF_get_string(req_conf
, NULL
, "oid_file");
412 oid_bio
= BIO_new_file(p
, "r");
413 if (oid_bio
== NULL
) {
415 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
416 ERR_print_errors(bio_err);
419 OBJ_create_objects(oid_bio
);
424 if (!add_oid_section(req_conf
))
427 if (md_alg
== NULL
) {
428 p
= NCONF_get_string(req_conf
, SECTION
, "default_md");
432 if (!opt_md(p
, &md_alg
))
439 extensions
= NCONF_get_string(req_conf
, SECTION
, V3_EXTENSIONS
);
444 /* Check syntax of file */
446 X509V3_set_ctx_test(&ctx
);
447 X509V3_set_nconf(&ctx
, req_conf
);
448 if (!X509V3_EXT_add_nconf(req_conf
, &ctx
, extensions
, NULL
)) {
450 "Error Loading extension section %s\n", extensions
);
456 passin
= NCONF_get_string(req_conf
, SECTION
, "input_password");
462 passout
= NCONF_get_string(req_conf
, SECTION
, "output_password");
467 p
= NCONF_get_string(req_conf
, SECTION
, STRING_MASK
);
471 if (p
&& !ASN1_STRING_set_default_mask_asc(p
)) {
472 BIO_printf(bio_err
, "Invalid global string mask setting %s\n", p
);
476 if (chtype
!= MBSTRING_UTF8
) {
477 p
= NCONF_get_string(req_conf
, SECTION
, UTF8_IN
);
480 else if (!strcmp(p
, "yes"))
481 chtype
= MBSTRING_UTF8
;
485 req_exts
= NCONF_get_string(req_conf
, SECTION
, REQ_EXTENSIONS
);
490 /* Check syntax of file */
492 X509V3_set_ctx_test(&ctx
);
493 X509V3_set_nconf(&ctx
, req_conf
);
494 if (!X509V3_EXT_add_nconf(req_conf
, &ctx
, req_exts
, NULL
)) {
496 "Error Loading request extension section %s\n",
502 if (keyfile
!= NULL
) {
503 pkey
= load_key(keyfile
, keyform
, 0, passin
, e
, "Private Key");
505 /* load_key() has already printed an appropriate message */
508 char *randfile
= NCONF_get_string(req_conf
, SECTION
, "RANDFILE");
509 if (randfile
== NULL
)
511 app_RAND_load_file(randfile
, 0);
515 if (newreq
&& (pkey
== NULL
)) {
516 char *randfile
= NCONF_get_string(req_conf
, SECTION
, "RANDFILE");
517 if (randfile
== NULL
)
519 app_RAND_load_file(randfile
, 0);
521 app_RAND_load_files(inrand
);
523 if (!NCONF_get_number(req_conf
, SECTION
, BITS
, &newkey
)) {
524 newkey
= DEFAULT_KEY_LENGTH
;
528 genctx
= set_keygen_ctx(keyalg
, &pkey_type
, &newkey
,
529 &keyalgstr
, gen_eng
);
534 if (newkey
< MIN_KEY_LENGTH
535 && (pkey_type
== EVP_PKEY_RSA
|| pkey_type
== EVP_PKEY_DSA
)) {
536 BIO_printf(bio_err
, "private key length is too short,\n");
537 BIO_printf(bio_err
, "it needs to be at least %d bits, not %ld\n",
538 MIN_KEY_LENGTH
, newkey
);
543 genctx
= set_keygen_ctx(NULL
, &pkey_type
, &newkey
,
544 &keyalgstr
, gen_eng
);
551 for (i
= 0; i
< sk_OPENSSL_STRING_num(pkeyopts
); i
++) {
552 genopt
= sk_OPENSSL_STRING_value(pkeyopts
, i
);
553 if (pkey_ctrl_string(genctx
, genopt
) <= 0) {
554 BIO_printf(bio_err
, "parameter error \"%s\"\n", genopt
);
555 ERR_print_errors(bio_err
);
561 BIO_printf(bio_err
, "Generating a %ld bit %s private key\n",
564 EVP_PKEY_CTX_set_cb(genctx
, genpkey_cb
);
565 EVP_PKEY_CTX_set_app_data(genctx
, bio_err
);
567 if (EVP_PKEY_keygen(genctx
, &pkey
) <= 0) {
568 BIO_puts(bio_err
, "Error Generating Key\n");
572 EVP_PKEY_CTX_free(genctx
);
575 app_RAND_write_file(randfile
);
577 if (keyout
== NULL
) {
578 keyout
= NCONF_get_string(req_conf
, SECTION
, KEYFILE
);
584 BIO_printf(bio_err
, "writing new private key to stdout\n");
586 BIO_printf(bio_err
, "writing new private key to '%s'\n", keyout
);
587 out
= bio_open_default(keyout
, "w");
591 p
= NCONF_get_string(req_conf
, SECTION
, "encrypt_rsa_key");
594 p
= NCONF_get_string(req_conf
, SECTION
, "encrypt_key");
598 if ((p
!= NULL
) && (strcmp(p
, "no") == 0))
605 if (!PEM_write_bio_PrivateKey(out
, pkey
, cipher
,
606 NULL
, 0, NULL
, passout
)) {
607 if ((ERR_GET_REASON(ERR_peek_error()) ==
608 PEM_R_PROBLEMS_GETTING_PASSWORD
) && (i
< 3)) {
615 BIO_printf(bio_err
, "-----\n");
620 * Since we are using a pre-existing certificate request, the kludge
621 * 'format' info should not be changed.
624 in
= bio_open_default(infile
, RB(informat
));
628 if (informat
== FORMAT_ASN1
)
629 req
= d2i_X509_REQ_bio(in
, NULL
);
631 req
= PEM_read_bio_X509_REQ(in
, NULL
, NULL
, NULL
);
633 BIO_printf(bio_err
, "unable to load X509 request\n");
638 if (newreq
|| x509
) {
640 BIO_printf(bio_err
, "you need to specify a private key\n");
645 req
= X509_REQ_new();
650 i
= make_REQ(req
, pkey
, subj
, multirdn
, !x509
, chtype
);
651 subj
= NULL
; /* done processing '-subj' option */
653 && !sk_X509_ATTRIBUTE_num(req
->req_info
->attributes
)) {
654 sk_X509_ATTRIBUTE_free(req
->req_info
->attributes
);
655 req
->req_info
->attributes
= NULL
;
658 BIO_printf(bio_err
, "problems making Certificate Request\n");
665 if ((x509ss
= X509_new()) == NULL
)
668 /* Set version to V3 */
669 if (extensions
&& !X509_set_version(x509ss
, 2))
672 if (!X509_set_serialNumber(x509ss
, serial
))
675 if (!rand_serial(NULL
, X509_get_serialNumber(x509ss
)))
679 if (!X509_set_issuer_name(x509ss
, X509_REQ_get_subject_name(req
)))
681 if (!X509_gmtime_adj(X509_get_notBefore(x509ss
), 0))
683 if (!X509_time_adj_ex(X509_get_notAfter(x509ss
), days
, 0, NULL
))
685 if (!X509_set_subject_name
686 (x509ss
, X509_REQ_get_subject_name(req
)))
688 tmppkey
= X509_REQ_get_pubkey(req
);
689 if (!tmppkey
|| !X509_set_pubkey(x509ss
, tmppkey
))
691 EVP_PKEY_free(tmppkey
);
693 /* Set up V3 context struct */
695 X509V3_set_ctx(&ext_ctx
, x509ss
, x509ss
, NULL
, NULL
, 0);
696 X509V3_set_nconf(&ext_ctx
, req_conf
);
699 if (extensions
&& !X509V3_EXT_add_nconf(req_conf
,
700 &ext_ctx
, extensions
,
702 BIO_printf(bio_err
, "Error Loading extension section %s\n",
707 i
= do_X509_sign(x509ss
, pkey
, digest
, sigopts
);
709 ERR_print_errors(bio_err
);
715 /* Set up V3 context struct */
717 X509V3_set_ctx(&ext_ctx
, NULL
, NULL
, req
, NULL
, 0);
718 X509V3_set_nconf(&ext_ctx
, req_conf
);
721 if (req_exts
&& !X509V3_EXT_REQ_add_nconf(req_conf
,
724 BIO_printf(bio_err
, "Error Loading extension section %s\n",
728 i
= do_X509_REQ_sign(req
, pkey
, digest
, sigopts
);
730 ERR_print_errors(bio_err
);
737 BIO_printf(bio_err
, "Cannot modify certificate subject\n");
743 BIO_printf(bio_err
, "Modifying Request's Subject\n");
744 print_name(bio_err
, "old subject=",
745 X509_REQ_get_subject_name(req
), nmflag
);
748 if (build_subject(req
, subj
, chtype
, multirdn
) == 0) {
749 BIO_printf(bio_err
, "ERROR: cannot modify subject\n");
754 req
->req_info
->enc
.modified
= 1;
757 print_name(bio_err
, "new subject=",
758 X509_REQ_get_subject_name(req
), nmflag
);
762 if (verify
&& !x509
) {
766 pkey
= X509_REQ_get_pubkey(req
);
772 i
= X509_REQ_verify(req
, pkey
);
781 BIO_printf(bio_err
, "verify failure\n");
782 ERR_print_errors(bio_err
);
783 } else /* if (i > 0) */
784 BIO_printf(bio_err
, "verify OK\n");
787 if (noout
&& !text
&& !modulus
&& !subject
&& !pubkey
) {
792 out
= bio_open_default(outfile
,
793 keyout
!= NULL
&& outfile
!= NULL
&&
794 strcmp(keyout
, outfile
) == 0 ? "a" : "w");
800 tpubkey
= X509_REQ_get_pubkey(req
);
801 if (tpubkey
== NULL
) {
802 BIO_printf(bio_err
, "Error getting public key\n");
803 ERR_print_errors(bio_err
);
806 PEM_write_bio_PUBKEY(out
, tpubkey
);
807 EVP_PKEY_free(tpubkey
);
812 X509_print_ex(out
, x509ss
, nmflag
, reqflag
);
814 X509_REQ_print_ex(out
, req
, nmflag
, reqflag
);
819 print_name(out
, "subject=", X509_get_subject_name(x509ss
),
822 print_name(out
, "subject=", X509_REQ_get_subject_name(req
),
830 tpubkey
= X509_get_pubkey(x509ss
);
832 tpubkey
= X509_REQ_get_pubkey(req
);
833 if (tpubkey
== NULL
) {
834 fprintf(stdout
, "Modulus=unavailable\n");
837 fprintf(stdout
, "Modulus=");
838 #ifndef OPENSSL_NO_RSA
839 if (EVP_PKEY_base_id(tpubkey
) == EVP_PKEY_RSA
)
840 BN_print(out
, tpubkey
->pkey
.rsa
->n
);
843 fprintf(stdout
, "Wrong Algorithm type");
844 EVP_PKEY_free(tpubkey
);
845 fprintf(stdout
, "\n");
848 if (!noout
&& !x509
) {
849 if (outformat
== FORMAT_ASN1
)
850 i
= i2d_X509_REQ_bio(out
, req
);
852 i
= PEM_write_bio_X509_REQ_NEW(out
, req
);
854 i
= PEM_write_bio_X509_REQ(out
, req
);
856 BIO_printf(bio_err
, "unable to write X509 request\n");
860 if (!noout
&& x509
&& (x509ss
!= NULL
)) {
861 if (outformat
== FORMAT_ASN1
)
862 i
= i2d_X509_bio(out
, x509ss
);
864 i
= PEM_write_bio_X509(out
, x509ss
);
866 BIO_printf(bio_err
, "unable to write X509 certificate\n");
873 ERR_print_errors(bio_err
);
875 if (req_conf
!= config
)
876 NCONF_free(req_conf
);
880 EVP_PKEY_CTX_free(genctx
);
881 sk_OPENSSL_STRING_free(pkeyopts
);
882 sk_OPENSSL_STRING_free(sigopts
);
883 #ifndef OPENSSL_NO_ENGINE
884 ENGINE_free(gen_eng
);
886 OPENSSL_free(keyalgstr
);
889 ASN1_INTEGER_free(serial
);
890 OPENSSL_free(passin
);
891 OPENSSL_free(passout
);
896 static int make_REQ(X509_REQ
*req
, EVP_PKEY
*pkey
, char *subj
, int multirdn
,
897 int attribs
, unsigned long chtype
)
901 STACK_OF(CONF_VALUE
) *dn_sk
, *attr_sk
= NULL
;
902 char *tmp
, *dn_sect
, *attr_sect
;
904 tmp
= NCONF_get_string(req_conf
, SECTION
, PROMPT
);
907 if ((tmp
!= NULL
) && !strcmp(tmp
, "no"))
910 dn_sect
= NCONF_get_string(req_conf
, SECTION
, DISTINGUISHED_NAME
);
911 if (dn_sect
== NULL
) {
912 BIO_printf(bio_err
, "unable to find '%s' in config\n",
916 dn_sk
= NCONF_get_section(req_conf
, dn_sect
);
918 BIO_printf(bio_err
, "unable to get '%s' section\n", dn_sect
);
922 attr_sect
= NCONF_get_string(req_conf
, SECTION
, ATTRIBUTES
);
923 if (attr_sect
== NULL
) {
927 attr_sk
= NCONF_get_section(req_conf
, attr_sect
);
928 if (attr_sk
== NULL
) {
929 BIO_printf(bio_err
, "unable to get '%s' section\n", attr_sect
);
934 /* setup version number */
935 if (!X509_REQ_set_version(req
, 0L))
936 goto err
; /* version 1 */
939 i
= build_subject(req
, subj
, chtype
, multirdn
);
941 i
= auto_info(req
, dn_sk
, attr_sk
, attribs
, chtype
);
943 i
= prompt_info(req
, dn_sk
, dn_sect
, attr_sk
, attr_sect
, attribs
,
948 if (!X509_REQ_set_pubkey(req
, pkey
))
957 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
958 * where characters may be escaped by \
960 static int build_subject(X509_REQ
*req
, char *subject
, unsigned long chtype
,
965 if (!(n
= parse_name(subject
, chtype
, multirdn
)))
968 if (!X509_REQ_set_subject_name(req
, n
)) {
976 static int prompt_info(X509_REQ
*req
,
977 STACK_OF(CONF_VALUE
) *dn_sk
, char *dn_sect
,
978 STACK_OF(CONF_VALUE
) *attr_sk
, char *attr_sect
,
979 int attribs
, unsigned long chtype
)
990 subj
= X509_REQ_get_subject_name(req
);
994 "You are about to be asked to enter information that will be incorporated\n");
995 BIO_printf(bio_err
, "into your certificate request.\n");
997 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
999 "There are quite a few fields but you can leave some blank\n");
1001 "For some fields there will be a default value,\n");
1003 "If you enter '.', the field will be left blank.\n");
1004 BIO_printf(bio_err
, "-----\n");
1007 if (sk_CONF_VALUE_num(dn_sk
)) {
1011 if (sk_CONF_VALUE_num(dn_sk
) <= i
)
1014 v
= sk_CONF_VALUE_value(dn_sk
, i
);
1017 if (!check_end(type
, "_min") || !check_end(type
, "_max") ||
1018 !check_end(type
, "_default") || !check_end(type
, "_value"))
1021 * Skip past any leading X. X: X, etc to allow for multiple
1024 for (p
= v
->name
; *p
; p
++)
1025 if ((*p
== ':') || (*p
== ',') || (*p
== '.')) {
1036 /* If OBJ not recognised ignore it */
1037 if ((nid
= OBJ_txt2nid(type
)) == NID_undef
)
1039 if (BIO_snprintf(buf
, sizeof buf
, "%s_default", v
->name
)
1040 >= (int)sizeof(buf
)) {
1041 BIO_printf(bio_err
, "Name '%s' too long\n", v
->name
);
1045 if ((def
= NCONF_get_string(req_conf
, dn_sect
, buf
)) == NULL
) {
1050 BIO_snprintf(buf
, sizeof buf
, "%s_value", v
->name
);
1051 if ((value
= NCONF_get_string(req_conf
, dn_sect
, buf
)) == NULL
) {
1056 BIO_snprintf(buf
, sizeof buf
, "%s_min", v
->name
);
1057 if (!NCONF_get_number(req_conf
, dn_sect
, buf
, &n_min
)) {
1062 BIO_snprintf(buf
, sizeof buf
, "%s_max", v
->name
);
1063 if (!NCONF_get_number(req_conf
, dn_sect
, buf
, &n_max
)) {
1068 if (!add_DN_object(subj
, v
->value
, def
, value
, nid
,
1069 n_min
, n_max
, chtype
, mval
))
1072 if (X509_NAME_entry_count(subj
) == 0) {
1074 "error, no objects specified in config file\n");
1079 if ((attr_sk
!= NULL
) && (sk_CONF_VALUE_num(attr_sk
) > 0)
1082 "\nPlease enter the following 'extra' attributes\n");
1084 "to be sent with your certificate request\n");
1090 if ((attr_sk
== NULL
) || (sk_CONF_VALUE_num(attr_sk
) <= i
))
1093 v
= sk_CONF_VALUE_value(attr_sk
, i
);
1095 if ((nid
= OBJ_txt2nid(type
)) == NID_undef
)
1098 if (BIO_snprintf(buf
, sizeof buf
, "%s_default", type
)
1099 >= (int)sizeof(buf
)) {
1100 BIO_printf(bio_err
, "Name '%s' too long\n", v
->name
);
1104 if ((def
= NCONF_get_string(req_conf
, attr_sect
, buf
))
1110 BIO_snprintf(buf
, sizeof buf
, "%s_value", type
);
1111 if ((value
= NCONF_get_string(req_conf
, attr_sect
, buf
))
1117 BIO_snprintf(buf
, sizeof buf
, "%s_min", type
);
1118 if (!NCONF_get_number(req_conf
, attr_sect
, buf
, &n_min
)) {
1123 BIO_snprintf(buf
, sizeof buf
, "%s_max", type
);
1124 if (!NCONF_get_number(req_conf
, attr_sect
, buf
, &n_max
)) {
1129 if (!add_attribute_object(req
,
1130 v
->value
, def
, value
, nid
, n_min
,
1136 BIO_printf(bio_err
, "No template, please set one up.\n");
1144 static int auto_info(X509_REQ
*req
, STACK_OF(CONF_VALUE
) *dn_sk
,
1145 STACK_OF(CONF_VALUE
) *attr_sk
, int attribs
,
1146 unsigned long chtype
)
1154 subj
= X509_REQ_get_subject_name(req
);
1156 for (i
= 0; i
< sk_CONF_VALUE_num(dn_sk
); i
++) {
1158 v
= sk_CONF_VALUE_value(dn_sk
, i
);
1162 * Skip past any leading X. X: X, etc to allow for multiple instances
1164 for (p
= v
->name
; *p
; p
++)
1165 #ifndef CHARSET_EBCDIC
1166 if ((*p
== ':') || (*p
== ',') || (*p
== '.')) {
1168 if ((*p
== os_toascii
[':']) || (*p
== os_toascii
[','])
1169 || (*p
== os_toascii
['.'])) {
1176 #ifndef CHARSET_EBCDIC
1179 if (*p
== os_toascii
['+'])
1186 if (!X509_NAME_add_entry_by_txt(subj
, type
, chtype
,
1187 (unsigned char *)v
->value
, -1, -1,
1193 if (!X509_NAME_entry_count(subj
)) {
1194 BIO_printf(bio_err
, "error, no objects specified in config file\n");
1198 for (i
= 0; i
< sk_CONF_VALUE_num(attr_sk
); i
++) {
1199 v
= sk_CONF_VALUE_value(attr_sk
, i
);
1200 if (!X509_REQ_add1_attr_by_txt(req
, v
->name
, chtype
,
1201 (unsigned char *)v
->value
, -1))
1208 static int add_DN_object(X509_NAME
*n
, char *text
, const char *def
,
1209 char *value
, int nid
, int n_min
, int n_max
,
1210 unsigned long chtype
, int mval
)
1216 BIO_printf(bio_err
, "%s [%s]:", text
, def
);
1217 (void)BIO_flush(bio_err
);
1218 if (value
!= NULL
) {
1219 BUF_strlcpy(buf
, value
, sizeof buf
);
1220 BUF_strlcat(buf
, "\n", sizeof buf
);
1221 BIO_printf(bio_err
, "%s\n", value
);
1225 if (!fgets(buf
, sizeof buf
, stdin
))
1235 else if (buf
[0] == '\n') {
1236 if ((def
== NULL
) || (def
[0] == '\0'))
1238 BUF_strlcpy(buf
, def
, sizeof buf
);
1239 BUF_strlcat(buf
, "\n", sizeof buf
);
1240 } else if ((buf
[0] == '.') && (buf
[1] == '\n'))
1244 if (buf
[i
- 1] != '\n') {
1245 BIO_printf(bio_err
, "weird input :-(\n");
1249 #ifdef CHARSET_EBCDIC
1250 ebcdic2ascii(buf
, buf
, i
);
1252 if (!req_check_len(i
, n_min
, n_max
)) {
1258 if (!X509_NAME_add_entry_by_NID(n
, nid
, chtype
,
1259 (unsigned char *)buf
, -1, -1, mval
))
1266 static int add_attribute_object(X509_REQ
*req
, char *text
, const char *def
,
1267 char *value
, int nid
, int n_min
,
1268 int n_max
, unsigned long chtype
)
1271 static char buf
[1024];
1275 BIO_printf(bio_err
, "%s [%s]:", text
, def
);
1276 (void)BIO_flush(bio_err
);
1277 if (value
!= NULL
) {
1278 BUF_strlcpy(buf
, value
, sizeof buf
);
1279 BUF_strlcat(buf
, "\n", sizeof buf
);
1280 BIO_printf(bio_err
, "%s\n", value
);
1284 if (!fgets(buf
, sizeof buf
, stdin
))
1294 else if (buf
[0] == '\n') {
1295 if ((def
== NULL
) || (def
[0] == '\0'))
1297 BUF_strlcpy(buf
, def
, sizeof buf
);
1298 BUF_strlcat(buf
, "\n", sizeof buf
);
1299 } else if ((buf
[0] == '.') && (buf
[1] == '\n'))
1303 if (buf
[i
- 1] != '\n') {
1304 BIO_printf(bio_err
, "weird input :-(\n");
1308 #ifdef CHARSET_EBCDIC
1309 ebcdic2ascii(buf
, buf
, i
);
1311 if (!req_check_len(i
, n_min
, n_max
)) {
1317 if (!X509_REQ_add1_attr_by_NID(req
, nid
, chtype
,
1318 (unsigned char *)buf
, -1)) {
1319 BIO_printf(bio_err
, "Error adding attribute\n");
1320 ERR_print_errors(bio_err
);
1329 static int req_check_len(int len
, int n_min
, int n_max
)
1331 if ((n_min
> 0) && (len
< n_min
)) {
1333 "string is too short, it needs to be at least %d bytes long\n",
1337 if ((n_max
>= 0) && (len
> n_max
)) {
1339 "string is too long, it needs to be less than %d bytes long\n",
1346 /* Check if the end of a string matches 'end' */
1347 static int check_end(const char *str
, const char *end
)
1355 tmp
= str
+ slen
- elen
;
1356 return strcmp(tmp
, end
);
1359 static EVP_PKEY_CTX
*set_keygen_ctx(const char *gstr
,
1360 int *pkey_type
, long *pkeylen
,
1361 char **palgnam
, ENGINE
*keygen_engine
)
1363 EVP_PKEY_CTX
*gctx
= NULL
;
1364 EVP_PKEY
*param
= NULL
;
1367 const char *paramfile
= NULL
;
1370 *pkey_type
= EVP_PKEY_RSA
;
1372 } else if (gstr
[0] >= '0' && gstr
[0] <= '9') {
1373 *pkey_type
= EVP_PKEY_RSA
;
1374 keylen
= atol(gstr
);
1376 } else if (!strncmp(gstr
, "param:", 6))
1377 paramfile
= gstr
+ 6;
1379 const char *p
= strchr(gstr
, ':');
1382 const EVP_PKEY_ASN1_METHOD
*ameth
;
1389 * The lookup of a the string will cover all engines so keep a note
1390 * of the implementation.
1393 ameth
= EVP_PKEY_asn1_find_str(&tmpeng
, gstr
, len
);
1396 BIO_printf(bio_err
, "Unknown algorithm %.*s\n", len
, gstr
);
1400 EVP_PKEY_asn1_get0_info(NULL
, pkey_type
, NULL
, NULL
, NULL
, ameth
);
1401 #ifndef OPENSSL_NO_ENGINE
1403 ENGINE_finish(tmpeng
);
1405 if (*pkey_type
== EVP_PKEY_RSA
) {
1407 keylen
= atol(p
+ 1);
1416 pbio
= BIO_new_file(paramfile
, "r");
1418 BIO_printf(bio_err
, "Can't open parameter file %s\n", paramfile
);
1421 param
= PEM_read_bio_Parameters(pbio
, NULL
);
1425 (void)BIO_reset(pbio
);
1426 x
= PEM_read_bio_X509(pbio
, NULL
, NULL
, NULL
);
1428 param
= X509_get_pubkey(x
);
1436 BIO_printf(bio_err
, "Error reading parameter file %s\n", paramfile
);
1439 if (*pkey_type
== -1)
1440 *pkey_type
= EVP_PKEY_id(param
);
1441 else if (*pkey_type
!= EVP_PKEY_base_id(param
)) {
1442 BIO_printf(bio_err
, "Key Type does not match parameters\n");
1443 EVP_PKEY_free(param
);
1449 const EVP_PKEY_ASN1_METHOD
*ameth
;
1452 ameth
= EVP_PKEY_asn1_find(&tmpeng
, *pkey_type
);
1454 BIO_puts(bio_err
, "Internal error: can't find key algorithm\n");
1457 EVP_PKEY_asn1_get0_info(NULL
, NULL
, NULL
, NULL
, &anam
, ameth
);
1458 *palgnam
= BUF_strdup(anam
);
1459 #ifndef OPENSSL_NO_ENGINE
1461 ENGINE_finish(tmpeng
);
1466 gctx
= EVP_PKEY_CTX_new(param
, keygen_engine
);
1467 *pkeylen
= EVP_PKEY_bits(param
);
1468 EVP_PKEY_free(param
);
1470 gctx
= EVP_PKEY_CTX_new_id(*pkey_type
, keygen_engine
);
1473 BIO_puts(bio_err
, "Error allocating keygen context\n");
1474 ERR_print_errors(bio_err
);
1478 if (EVP_PKEY_keygen_init(gctx
) <= 0) {
1479 BIO_puts(bio_err
, "Error initializing keygen context\n");
1480 ERR_print_errors(bio_err
);
1483 #ifndef OPENSSL_NO_RSA
1484 if ((*pkey_type
== EVP_PKEY_RSA
) && (keylen
!= -1)) {
1485 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx
, keylen
) <= 0) {
1486 BIO_puts(bio_err
, "Error setting RSA keysize\n");
1487 ERR_print_errors(bio_err
);
1488 EVP_PKEY_CTX_free(gctx
);
1497 static int genpkey_cb(EVP_PKEY_CTX
*ctx
)
1500 BIO
*b
= EVP_PKEY_CTX_get_app_data(ctx
);
1502 p
= EVP_PKEY_CTX_get_keygen_info(ctx
, 0);
1511 BIO_write(b
, &c
, 1);
1516 static int do_sign_init(EVP_MD_CTX
*ctx
, EVP_PKEY
*pkey
,
1517 const EVP_MD
*md
, STACK_OF(OPENSSL_STRING
) *sigopts
)
1519 EVP_PKEY_CTX
*pkctx
= NULL
;
1522 EVP_MD_CTX_init(ctx
);
1523 if (!EVP_DigestSignInit(ctx
, &pkctx
, md
, NULL
, pkey
))
1525 for (i
= 0; i
< sk_OPENSSL_STRING_num(sigopts
); i
++) {
1526 char *sigopt
= sk_OPENSSL_STRING_value(sigopts
, i
);
1527 if (pkey_ctrl_string(pkctx
, sigopt
) <= 0) {
1528 BIO_printf(bio_err
, "parameter error \"%s\"\n", sigopt
);
1529 ERR_print_errors(bio_err
);
1536 int do_X509_sign(X509
*x
, EVP_PKEY
*pkey
, const EVP_MD
*md
,
1537 STACK_OF(OPENSSL_STRING
) *sigopts
)
1542 EVP_MD_CTX_init(&mctx
);
1543 rv
= do_sign_init(&mctx
, pkey
, md
, sigopts
);
1545 rv
= X509_sign_ctx(x
, &mctx
);
1546 EVP_MD_CTX_cleanup(&mctx
);
1547 return rv
> 0 ? 1 : 0;
1550 int do_X509_REQ_sign(X509_REQ
*x
, EVP_PKEY
*pkey
, const EVP_MD
*md
,
1551 STACK_OF(OPENSSL_STRING
) *sigopts
)
1556 EVP_MD_CTX_init(&mctx
);
1557 rv
= do_sign_init(&mctx
, pkey
, md
, sigopts
);
1559 rv
= X509_REQ_sign_ctx(x
, &mctx
);
1560 EVP_MD_CTX_cleanup(&mctx
);
1561 return rv
> 0 ? 1 : 0;
1564 int do_X509_CRL_sign(X509_CRL
*x
, EVP_PKEY
*pkey
, const EVP_MD
*md
,
1565 STACK_OF(OPENSSL_STRING
) *sigopts
)
1570 EVP_MD_CTX_init(&mctx
);
1571 rv
= do_sign_init(&mctx
, pkey
, md
, sigopts
);
1573 rv
= X509_CRL_sign_ctx(x
, &mctx
);
1574 EVP_MD_CTX_cleanup(&mctx
);
1575 return rv
> 0 ? 1 : 0;