2 * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (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
15 #include <openssl/bio.h>
16 #include <openssl/evp.h>
17 #include <openssl/conf.h>
18 #include <openssl/err.h>
19 #include <openssl/asn1.h>
20 #include <openssl/x509.h>
21 #include <openssl/x509v3.h>
22 #include <openssl/objects.h>
23 #include <openssl/pem.h>
24 #include <openssl/bn.h>
25 #ifndef OPENSSL_NO_RSA
26 # include <openssl/rsa.h>
28 #ifndef OPENSSL_NO_DSA
29 # include <openssl/dsa.h>
34 #define BITS "default_bits"
35 #define KEYFILE "default_keyfile"
36 #define PROMPT "prompt"
37 #define DISTINGUISHED_NAME "distinguished_name"
38 #define ATTRIBUTES "attributes"
39 #define V3_EXTENSIONS "x509_extensions"
40 #define REQ_EXTENSIONS "req_extensions"
41 #define STRING_MASK "string_mask"
42 #define UTF8_IN "utf8"
44 #define DEFAULT_KEY_LENGTH 2048
45 #define MIN_KEY_LENGTH 512
47 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
48 int attribs, unsigned long chtype);
49 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
51 static int prompt_info(X509_REQ *req,
52 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
53 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
54 int attribs, unsigned long chtype);
55 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
56 STACK_OF(CONF_VALUE) *attr, int attribs,
57 unsigned long chtype);
58 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
59 char *value, int nid, int n_min, int n_max,
60 unsigned long chtype);
61 static int add_DN_object(X509_NAME *n, char *text, const char *def,
62 char *value, int nid, int n_min, int n_max,
63 unsigned long chtype, int mval);
64 static int genpkey_cb(EVP_PKEY_CTX *ctx);
65 static int req_check_len(int len, int n_min, int n_max);
66 static int check_end(const char *str, const char *end);
67 static int join(char buf[], size_t buf_size, const char *name,
68 const char *tail, const char *desc);
69 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
70 int *pkey_type, long *pkeylen,
71 char **palgnam, ENGINE *keygen_engine);
72 static CONF *req_conf = NULL;
73 static CONF *addext_conf = NULL;
76 typedef enum OPTION_choice {
77 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
78 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
79 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
80 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
81 OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
82 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
83 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
84 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
85 OPT_REQEXTS, OPT_PRECERT, OPT_MD,
89 const OPTIONS req_options[] = {
90 {"help", OPT_HELP, '-', "Display this summary"},
91 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
92 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
93 {"in", OPT_IN, '<', "Input file"},
94 {"out", OPT_OUT, '>', "Output file"},
95 {"key", OPT_KEY, 's', "Private key to use"},
96 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
97 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
98 {"new", OPT_NEW, '-', "New request"},
99 {"config", OPT_CONFIG, '<', "Request template file"},
100 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
101 {"passin", OPT_PASSIN, 's', "Private key password source"},
102 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
104 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
105 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
106 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
107 {"batch", OPT_BATCH, '-',
108 "Do not ask anything during request generation"},
109 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
110 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
111 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
112 {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
113 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
114 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
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 a 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)"},
135 {"", OPT_MD, '-', "Any supported digest"},
136 #ifndef OPENSSL_NO_ENGINE
137 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
138 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
139 "Specify engine to be used for key generation operations"},
144 int req_main(int argc, char **argv)
146 ASN1_INTEGER *serial = NULL;
147 BIO *in = NULL, *out = NULL;
148 ENGINE *e = NULL, *gen_eng = NULL;
149 EVP_PKEY *pkey = NULL;
150 EVP_PKEY_CTX *genctx = NULL;
151 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
153 X509_REQ *req = NULL;
154 const EVP_CIPHER *cipher = NULL;
155 const EVP_MD *md_alg = NULL, *digest = NULL;
156 BIO *addext_bio = NULL;
157 char *extensions = NULL, *infile = NULL;
158 char *outfile = NULL, *keyfile = NULL;
159 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
160 char *passin = NULL, *passout = NULL;
161 char *nofree_passin = NULL, *nofree_passout = NULL;
162 char *req_exts = NULL, *subj = NULL;
163 char *template = default_config_file, *keyout = NULL;
164 const char *keyalg = NULL;
166 int ret = 1, x509 = 0, days = 0, i = 0, newreq = 0, verbose = 0;
167 int pkey_type = -1, private = 0;
168 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
169 int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
170 int nodes = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
172 unsigned long chtype = MBSTRING_ASC, reqflag = 0;
174 #ifndef OPENSSL_NO_DES
175 cipher = EVP_des_ede3_cbc();
178 prog = opt_init(argc, argv, req_options);
179 while ((o = opt_next()) != OPT_EOF) {
184 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
187 opt_help(req_options);
191 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
195 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
199 e = setup_engine(opt_arg(), 0);
201 case OPT_KEYGEN_ENGINE:
202 #ifndef OPENSSL_NO_ENGINE
203 gen_eng = ENGINE_by_id(opt_arg());
204 if (gen_eng == NULL) {
205 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
220 template = opt_arg();
223 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
236 passargin = opt_arg();
239 passargout = opt_arg();
251 pkeyopts = sk_OPENSSL_STRING_new_null();
252 if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
257 sigopts = sk_OPENSSL_STRING_new_null();
258 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
283 chtype = MBSTRING_UTF8;
286 if (!set_nameopt(opt_arg()))
290 if (!set_cert_ex(&reqflag, opt_arg()))
300 days = atoi(opt_arg());
303 if (serial != NULL) {
304 BIO_printf(bio_err, "Serial number supplied twice\n");
307 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
317 case OPT_MULTIVALUE_RDN:
321 if (addext_bio == NULL) {
322 addext_bio = BIO_new(BIO_s_mem());
324 if (addext_bio == NULL
325 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
329 extensions = opt_arg();
332 req_exts = opt_arg();
335 newreq = precert = 1;
338 if (!opt_md(opt_unknown(), &md_alg))
344 argc = opt_num_rest();
349 BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
350 if (x509 && infile == NULL)
353 /* TODO: simplify this as pkey is still always NULL here */
354 private = newreq && (pkey == NULL) ? 1 : 0;
356 if (!app_passwd(passargin, passargout, &passin, &passout)) {
357 BIO_printf(bio_err, "Error getting passwords\n");
362 BIO_printf(bio_err, "Using configuration from %s\n", template);
363 req_conf = app_load_config(template);
367 "Using additional configuraton from command line\n");
368 addext_conf = app_load_config_bio(addext_bio, NULL);
370 if (template != default_config_file && !app_load_modules(req_conf))
373 if (req_conf != NULL) {
374 p = NCONF_get_string(req_conf, NULL, "oid_file");
380 oid_bio = BIO_new_file(p, "r");
381 if (oid_bio == NULL) {
383 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
384 ERR_print_errors(bio_err);
387 OBJ_create_objects(oid_bio);
392 if (!add_oid_section(req_conf))
395 if (md_alg == NULL) {
396 p = NCONF_get_string(req_conf, SECTION, "default_md");
400 if (!opt_md(p, &md_alg))
406 if (extensions == NULL) {
407 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
408 if (extensions == NULL)
411 if (extensions != NULL) {
412 /* Check syntax of file */
414 X509V3_set_ctx_test(&ctx);
415 X509V3_set_nconf(&ctx, req_conf);
416 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
418 "Error Loading extension section %s\n", extensions);
422 if (addext_conf != NULL) {
423 /* Check syntax of command line extensions */
425 X509V3_set_ctx_test(&ctx);
426 X509V3_set_nconf(&ctx, addext_conf);
427 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
428 BIO_printf(bio_err, "Error Loading command line extensions\n");
433 if (passin == NULL) {
434 passin = nofree_passin =
435 NCONF_get_string(req_conf, SECTION, "input_password");
440 if (passout == NULL) {
441 passout = nofree_passout =
442 NCONF_get_string(req_conf, SECTION, "output_password");
447 p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
451 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
452 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
456 if (chtype != MBSTRING_UTF8) {
457 p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
460 else if (strcmp(p, "yes") == 0)
461 chtype = MBSTRING_UTF8;
464 if (req_exts == NULL) {
465 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
466 if (req_exts == NULL)
469 if (req_exts != NULL) {
470 /* Check syntax of file */
472 X509V3_set_ctx_test(&ctx);
473 X509V3_set_nconf(&ctx, req_conf);
474 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
476 "Error Loading request extension section %s\n",
482 if (keyfile != NULL) {
483 pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
485 /* load_key() has already printed an appropriate message */
488 app_RAND_load_conf(req_conf, SECTION);
492 if (newreq && (pkey == NULL)) {
493 app_RAND_load_conf(req_conf, SECTION);
495 if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
496 newkey = DEFAULT_KEY_LENGTH;
499 if (keyalg != NULL) {
500 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
501 &keyalgstr, gen_eng);
506 if (newkey < MIN_KEY_LENGTH
507 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
508 BIO_printf(bio_err, "private key length is too short,\n");
509 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
510 MIN_KEY_LENGTH, newkey);
514 if (genctx == NULL) {
515 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
516 &keyalgstr, gen_eng);
521 if (pkeyopts != NULL) {
523 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
524 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
525 if (pkey_ctrl_string(genctx, genopt) <= 0) {
526 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
527 ERR_print_errors(bio_err);
533 if (pkey_type == EVP_PKEY_EC) {
534 BIO_printf(bio_err, "Generating an EC private key\n");
536 BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
540 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
541 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
543 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
544 BIO_puts(bio_err, "Error Generating Key\n");
548 EVP_PKEY_CTX_free(genctx);
551 if (keyout == NULL) {
552 keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
558 BIO_printf(bio_err, "writing new private key to stdout\n");
560 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
561 out = bio_open_owner(keyout, outformat, private);
565 p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
568 p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
572 if ((p != NULL) && (strcmp(p, "no") == 0))
580 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
581 NULL, 0, NULL, passout)) {
582 if ((ERR_GET_REASON(ERR_peek_error()) ==
583 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
592 BIO_printf(bio_err, "-----\n");
596 in = bio_open_default(infile, 'r', informat);
600 if (informat == FORMAT_ASN1)
601 req = d2i_X509_REQ_bio(in, NULL);
603 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
605 BIO_printf(bio_err, "unable to load X509 request\n");
610 if (newreq || x509) {
612 BIO_printf(bio_err, "you need to specify a private key\n");
617 req = X509_REQ_new();
622 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
623 subj = NULL; /* done processing '-subj' option */
625 BIO_printf(bio_err, "problems making Certificate Request\n");
632 if ((x509ss = X509_new()) == NULL)
635 /* Set version to V3 */
636 if ((extensions != NULL || addext_conf != NULL)
637 && !X509_set_version(x509ss, 2))
639 if (serial != NULL) {
640 if (!X509_set_serialNumber(x509ss, serial))
643 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
647 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
650 /* set default days if it's not specified */
653 if (!set_cert_times(x509ss, NULL, NULL, days))
655 if (!X509_set_subject_name
656 (x509ss, X509_REQ_get_subject_name(req)))
658 tmppkey = X509_REQ_get0_pubkey(req);
659 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
662 /* Set up V3 context struct */
664 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
665 X509V3_set_nconf(&ext_ctx, req_conf);
668 if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
669 &ext_ctx, extensions,
671 BIO_printf(bio_err, "Error Loading extension section %s\n",
675 if (addext_conf != NULL
676 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
678 BIO_printf(bio_err, "Error Loading command line extensions\n");
682 /* If a pre-cert was requested, we need to add a poison extension */
684 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
686 BIO_printf(bio_err, "Error adding poison extension\n");
691 i = do_X509_sign(x509ss, pkey, digest, sigopts);
693 ERR_print_errors(bio_err);
699 /* Set up V3 context struct */
701 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
702 X509V3_set_nconf(&ext_ctx, req_conf);
706 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
708 BIO_printf(bio_err, "Error Loading extension section %s\n",
712 if (addext_conf != NULL
713 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
715 BIO_printf(bio_err, "Error Loading command line extensions\n");
718 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
720 ERR_print_errors(bio_err);
727 BIO_printf(bio_err, "Cannot modify certificate subject\n");
733 BIO_printf(bio_err, "Modifying Request's Subject\n");
734 print_name(bio_err, "old subject=",
735 X509_REQ_get_subject_name(req), get_nameopt());
738 if (build_subject(req, subj, chtype, multirdn) == 0) {
739 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
745 print_name(bio_err, "new subject=",
746 X509_REQ_get_subject_name(req), get_nameopt());
750 if (verify && !x509) {
751 EVP_PKEY *tpubkey = pkey;
753 if (tpubkey == NULL) {
754 tpubkey = X509_REQ_get0_pubkey(req);
759 i = X509_REQ_verify(req, tpubkey);
764 BIO_printf(bio_err, "verify failure\n");
765 ERR_print_errors(bio_err);
766 } else { /* if (i > 0) */
767 BIO_printf(bio_err, "verify OK\n");
771 if (noout && !text && !modulus && !subject && !pubkey) {
776 out = bio_open_default(outfile,
777 keyout != NULL && outfile != NULL &&
778 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
784 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
786 if (tpubkey == NULL) {
787 BIO_printf(bio_err, "Error getting public key\n");
788 ERR_print_errors(bio_err);
791 PEM_write_bio_PUBKEY(out, tpubkey);
796 X509_print_ex(out, x509ss, get_nameopt(), reqflag);
798 X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
803 print_name(out, "subject=", X509_get_subject_name(x509ss),
806 print_name(out, "subject=", X509_REQ_get_subject_name(req),
814 tpubkey = X509_get0_pubkey(x509ss);
816 tpubkey = X509_REQ_get0_pubkey(req);
817 if (tpubkey == NULL) {
818 fprintf(stdout, "Modulus=unavailable\n");
821 fprintf(stdout, "Modulus=");
822 #ifndef OPENSSL_NO_RSA
823 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
825 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
829 fprintf(stdout, "Wrong Algorithm type");
830 fprintf(stdout, "\n");
833 if (!noout && !x509) {
834 if (outformat == FORMAT_ASN1)
835 i = i2d_X509_REQ_bio(out, req);
837 i = PEM_write_bio_X509_REQ_NEW(out, req);
839 i = PEM_write_bio_X509_REQ(out, req);
841 BIO_printf(bio_err, "unable to write X509 request\n");
845 if (!noout && x509 && (x509ss != NULL)) {
846 if (outformat == FORMAT_ASN1)
847 i = i2d_X509_bio(out, x509ss);
849 i = PEM_write_bio_X509(out, x509ss);
851 BIO_printf(bio_err, "unable to write X509 certificate\n");
858 ERR_print_errors(bio_err);
860 NCONF_free(req_conf);
861 BIO_free(addext_bio);
865 EVP_PKEY_CTX_free(genctx);
866 sk_OPENSSL_STRING_free(pkeyopts);
867 sk_OPENSSL_STRING_free(sigopts);
868 #ifndef OPENSSL_NO_ENGINE
869 ENGINE_free(gen_eng);
871 OPENSSL_free(keyalgstr);
874 ASN1_INTEGER_free(serial);
876 if (passin != nofree_passin)
877 OPENSSL_free(passin);
878 if (passout != nofree_passout)
879 OPENSSL_free(passout);
883 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
884 int attribs, unsigned long chtype)
888 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
889 char *tmp, *dn_sect, *attr_sect;
891 tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
894 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
897 dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
898 if (dn_sect == NULL) {
899 BIO_printf(bio_err, "unable to find '%s' in config\n",
903 dn_sk = NCONF_get_section(req_conf, dn_sect);
905 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
909 attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
910 if (attr_sect == NULL) {
914 attr_sk = NCONF_get_section(req_conf, attr_sect);
915 if (attr_sk == NULL) {
916 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
921 /* setup version number */
922 if (!X509_REQ_set_version(req, 0L))
923 goto err; /* version 1 */
926 i = build_subject(req, subj, chtype, multirdn);
928 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
930 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
935 if (!X509_REQ_set_pubkey(req, pkey))
944 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
945 * where characters may be escaped by \
947 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
952 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
955 if (!X509_REQ_set_subject_name(req, n)) {
963 static int prompt_info(X509_REQ *req,
964 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
965 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
966 int attribs, unsigned long chtype)
977 subj = X509_REQ_get_subject_name(req);
981 "You are about to be asked to enter information that will be incorporated\n");
982 BIO_printf(bio_err, "into your certificate request.\n");
984 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
986 "There are quite a few fields but you can leave some blank\n");
988 "For some fields there will be a default value,\n");
990 "If you enter '.', the field will be left blank.\n");
991 BIO_printf(bio_err, "-----\n");
994 if (sk_CONF_VALUE_num(dn_sk)) {
999 if (sk_CONF_VALUE_num(dn_sk) <= i)
1002 v = sk_CONF_VALUE_value(dn_sk, i);
1005 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1006 !check_end(type, "_default") || !check_end(type, "_value"))
1009 * Skip past any leading X. X: X, etc to allow for multiple
1012 for (p = v->name; *p; p++)
1013 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1025 /* If OBJ not recognised ignore it */
1026 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1028 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1030 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1035 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1037 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1042 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1044 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1050 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1052 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1057 if (!add_DN_object(subj, v->value, def, value, nid,
1058 n_min, n_max, chtype, mval))
1061 if (X509_NAME_entry_count(subj) == 0) {
1063 "error, no objects specified in config file\n");
1068 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1071 "\nPlease enter the following 'extra' attributes\n");
1073 "to be sent with your certificate request\n");
1080 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1083 v = sk_CONF_VALUE_value(attr_sk, i);
1085 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1088 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1090 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1096 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1098 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1104 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1106 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1111 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1113 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1118 if (!add_attribute_object(req,
1119 v->value, def, value, nid, n_min,
1125 BIO_printf(bio_err, "No template, please set one up.\n");
1133 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1134 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1135 unsigned long chtype)
1137 int i, spec_char, plus_char;
1143 subj = X509_REQ_get_subject_name(req);
1145 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1147 v = sk_CONF_VALUE_value(dn_sk, i);
1151 * Skip past any leading X. X: X, etc to allow for multiple instances
1153 for (p = v->name; *p; p++) {
1154 #ifndef CHARSET_EBCDIC
1155 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1157 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1158 || (*p == os_toascii['.']));
1167 #ifndef CHARSET_EBCDIC
1168 plus_char = (*type == '+');
1170 plus_char = (*type == os_toascii['+']);
1178 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1179 (unsigned char *)v->value, -1, -1,
1185 if (!X509_NAME_entry_count(subj)) {
1186 BIO_printf(bio_err, "error, no objects specified in config file\n");
1190 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1191 v = sk_CONF_VALUE_value(attr_sk, i);
1192 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1193 (unsigned char *)v->value, -1))
1200 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1201 char *value, int nid, int n_min, int n_max,
1202 unsigned long chtype, int mval)
1208 BIO_printf(bio_err, "%s [%s]:", text, def);
1209 (void)BIO_flush(bio_err);
1210 if (value != NULL) {
1211 if (!join(buf, sizeof(buf), value, "\n", "DN value"))
1213 BIO_printf(bio_err, "%s\n", value);
1217 if (!fgets(buf, sizeof(buf), stdin))
1227 if (buf[0] == '\n') {
1228 if ((def == NULL) || (def[0] == '\0'))
1230 if (!join(buf, sizeof(buf), def, "\n", "DN default"))
1232 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1237 if (buf[i - 1] != '\n') {
1238 BIO_printf(bio_err, "weird input :-(\n");
1242 #ifdef CHARSET_EBCDIC
1243 ebcdic2ascii(buf, buf, i);
1245 if (!req_check_len(i, n_min, n_max)) {
1251 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1252 (unsigned char *)buf, -1, -1, mval))
1259 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1260 char *value, int nid, int n_min,
1261 int n_max, unsigned long chtype)
1264 static char buf[1024];
1268 BIO_printf(bio_err, "%s [%s]:", text, def);
1269 (void)BIO_flush(bio_err);
1270 if (value != NULL) {
1271 if (!join(buf, sizeof(buf), value, "\n", "Attribute value"))
1273 BIO_printf(bio_err, "%s\n", value);
1277 if (!fgets(buf, sizeof(buf), stdin))
1287 if (buf[0] == '\n') {
1288 if ((def == NULL) || (def[0] == '\0'))
1290 if (!join(buf, sizeof(buf), def, "\n", "Attribute default"))
1292 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1297 if (buf[i - 1] != '\n') {
1298 BIO_printf(bio_err, "weird input :-(\n");
1302 #ifdef CHARSET_EBCDIC
1303 ebcdic2ascii(buf, buf, i);
1305 if (!req_check_len(i, n_min, n_max)) {
1311 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1312 (unsigned char *)buf, -1)) {
1313 BIO_printf(bio_err, "Error adding attribute\n");
1314 ERR_print_errors(bio_err);
1323 static int req_check_len(int len, int n_min, int n_max)
1325 if ((n_min > 0) && (len < n_min)) {
1327 "string is too short, it needs to be at least %d bytes long\n",
1331 if ((n_max >= 0) && (len > n_max)) {
1333 "string is too long, it needs to be no more than %d bytes long\n",
1340 /* Check if the end of a string matches 'end' */
1341 static int check_end(const char *str, const char *end)
1350 tmp = str + slen - elen;
1351 return strcmp(tmp, end);
1355 * Merge the two strings together into the result buffer checking for
1356 * overflow and producing an error message if there is.
1358 static int join(char buf[], size_t buf_size, const char *name,
1359 const char *tail, const char *desc)
1361 const size_t name_len = strlen(name), tail_len = strlen(tail);
1363 if (name_len + tail_len + 1 > buf_size) {
1364 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1367 memcpy(buf, name, name_len);
1368 memcpy(buf + name_len, tail, tail_len + 1);
1372 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1373 int *pkey_type, long *pkeylen,
1374 char **palgnam, ENGINE *keygen_engine)
1376 EVP_PKEY_CTX *gctx = NULL;
1377 EVP_PKEY *param = NULL;
1380 const char *paramfile = NULL;
1383 *pkey_type = EVP_PKEY_RSA;
1385 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1386 *pkey_type = EVP_PKEY_RSA;
1387 keylen = atol(gstr);
1389 } else if (strncmp(gstr, "param:", 6) == 0) {
1390 paramfile = gstr + 6;
1392 const char *p = strchr(gstr, ':');
1395 const EVP_PKEY_ASN1_METHOD *ameth;
1402 * The lookup of a the string will cover all engines so keep a note
1403 * of the implementation.
1406 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1408 if (ameth == NULL) {
1409 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1413 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1414 #ifndef OPENSSL_NO_ENGINE
1415 ENGINE_finish(tmpeng);
1417 if (*pkey_type == EVP_PKEY_RSA) {
1419 keylen = atol(p + 1);
1424 } else if (p != NULL) {
1429 if (paramfile != NULL) {
1430 pbio = BIO_new_file(paramfile, "r");
1432 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1435 param = PEM_read_bio_Parameters(pbio, NULL);
1437 if (param == NULL) {
1440 (void)BIO_reset(pbio);
1441 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1443 param = X509_get_pubkey(x);
1450 if (param == NULL) {
1451 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1454 if (*pkey_type == -1) {
1455 *pkey_type = EVP_PKEY_id(param);
1456 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1457 BIO_printf(bio_err, "Key Type does not match parameters\n");
1458 EVP_PKEY_free(param);
1463 if (palgnam != NULL) {
1464 const EVP_PKEY_ASN1_METHOD *ameth;
1468 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1469 if (ameth == NULL) {
1470 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1473 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1474 *palgnam = OPENSSL_strdup(anam);
1475 #ifndef OPENSSL_NO_ENGINE
1476 ENGINE_finish(tmpeng);
1480 if (param != NULL) {
1481 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1482 *pkeylen = EVP_PKEY_bits(param);
1483 EVP_PKEY_free(param);
1485 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1489 BIO_puts(bio_err, "Error allocating keygen context\n");
1490 ERR_print_errors(bio_err);
1494 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1495 BIO_puts(bio_err, "Error initializing keygen context\n");
1496 ERR_print_errors(bio_err);
1497 EVP_PKEY_CTX_free(gctx);
1500 #ifndef OPENSSL_NO_RSA
1501 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1502 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1503 BIO_puts(bio_err, "Error setting RSA keysize\n");
1504 ERR_print_errors(bio_err);
1505 EVP_PKEY_CTX_free(gctx);
1514 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1517 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1519 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1528 BIO_write(b, &c, 1);
1533 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1534 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1536 EVP_PKEY_CTX *pkctx = NULL;
1541 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1543 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1544 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1545 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1546 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1547 ERR_print_errors(bio_err);
1554 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1555 STACK_OF(OPENSSL_STRING) *sigopts)
1558 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1560 rv = do_sign_init(mctx, pkey, md, sigopts);
1562 rv = X509_sign_ctx(x, mctx);
1563 EVP_MD_CTX_free(mctx);
1564 return rv > 0 ? 1 : 0;
1567 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1568 STACK_OF(OPENSSL_STRING) *sigopts)
1571 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1572 rv = do_sign_init(mctx, pkey, md, sigopts);
1574 rv = X509_REQ_sign_ctx(x, mctx);
1575 EVP_MD_CTX_free(mctx);
1576 return rv > 0 ? 1 : 0;
1579 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1580 STACK_OF(OPENSSL_STRING) *sigopts)
1583 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1584 rv = do_sign_init(mctx, pkey, md, sigopts);
1586 rv = X509_CRL_sign_ctx(x, mctx);
1587 EVP_MD_CTX_free(mctx);
1588 return rv > 0 ? 1 : 0;