2 * Copyright 1995-2018 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
16 #include <openssl/bio.h>
17 #include <openssl/evp.h>
18 #include <openssl/conf.h>
19 #include <openssl/err.h>
20 #include <openssl/asn1.h>
21 #include <openssl/x509.h>
22 #include <openssl/x509v3.h>
23 #include <openssl/objects.h>
24 #include <openssl/pem.h>
25 #include <openssl/bn.h>
26 #ifndef OPENSSL_NO_RSA
27 # include <openssl/rsa.h>
29 #ifndef OPENSSL_NO_DSA
30 # include <openssl/dsa.h>
35 #define BITS "default_bits"
36 #define KEYFILE "default_keyfile"
37 #define PROMPT "prompt"
38 #define DISTINGUISHED_NAME "distinguished_name"
39 #define ATTRIBUTES "attributes"
40 #define V3_EXTENSIONS "x509_extensions"
41 #define REQ_EXTENSIONS "req_extensions"
42 #define STRING_MASK "string_mask"
43 #define UTF8_IN "utf8"
45 #define DEFAULT_KEY_LENGTH 2048
46 #define MIN_KEY_LENGTH 512
48 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
49 int attribs, unsigned long chtype);
50 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
52 static int prompt_info(X509_REQ *req,
53 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
54 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
55 int attribs, unsigned long chtype);
56 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
57 STACK_OF(CONF_VALUE) *attr, int attribs,
58 unsigned long chtype);
59 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
60 char *value, int nid, int n_min, int n_max,
61 unsigned long chtype);
62 static int add_DN_object(X509_NAME *n, char *text, const char *def,
63 char *value, int nid, int n_min, int n_max,
64 unsigned long chtype, int mval);
65 static int genpkey_cb(EVP_PKEY_CTX *ctx);
66 static int req_check_len(int len, int n_min, int n_max);
67 static int check_end(const char *str, const char *end);
68 static int join(char buf[], size_t buf_size, const char *name,
69 const char *tail, const char *desc);
70 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
71 int *pkey_type, long *pkeylen,
72 char **palgnam, ENGINE *keygen_engine);
73 static CONF *req_conf = NULL;
74 static CONF *addext_conf = NULL;
77 typedef enum OPTION_choice {
78 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
79 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
80 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
81 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
82 OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
83 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
84 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
85 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
86 OPT_REQEXTS, OPT_PRECERT, OPT_MD,
90 const OPTIONS req_options[] = {
91 {"help", OPT_HELP, '-', "Display this summary"},
92 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
93 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
94 {"in", OPT_IN, '<', "Input file"},
95 {"out", OPT_OUT, '>', "Output file"},
96 {"key", OPT_KEY, 's', "Private key to use"},
97 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
98 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
99 {"new", OPT_NEW, '-', "New request"},
100 {"config", OPT_CONFIG, '<', "Request template file"},
101 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
102 {"passin", OPT_PASSIN, 's', "Private key password source"},
103 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
105 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
106 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
107 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
108 {"batch", OPT_BATCH, '-',
109 "Do not ask anything during request generation"},
110 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
111 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
112 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
113 {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
114 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
115 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
116 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
117 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
118 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
119 {"text", OPT_TEXT, '-', "Text form of request"},
120 {"x509", OPT_X509, '-',
121 "Output a x509 structure instead of a cert request"},
122 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
123 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
124 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
125 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
126 "Enable support for multivalued RDNs"},
127 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
128 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
129 {"addext", OPT_ADDEXT, 's',
130 "Additional cert extension key=value pair (may be given more than once)"},
131 {"extensions", OPT_EXTENSIONS, 's',
132 "Cert extension section (override value in config file)"},
133 {"reqexts", OPT_REQEXTS, 's',
134 "Request extension section (override value in config file)"},
135 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
136 {"", OPT_MD, '-', "Any supported digest"},
137 #ifndef OPENSSL_NO_ENGINE
138 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
139 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
140 "Specify engine to be used for key generation operations"},
145 int req_main(int argc, char **argv)
147 ASN1_INTEGER *serial = NULL;
148 BIO *in = NULL, *out = NULL;
149 ENGINE *e = NULL, *gen_eng = NULL;
150 EVP_PKEY *pkey = NULL;
151 EVP_PKEY_CTX *genctx = NULL;
152 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
154 X509_REQ *req = NULL;
155 const EVP_CIPHER *cipher = NULL;
156 const EVP_MD *md_alg = NULL, *digest = NULL;
157 BIO *addext_bio = NULL;
158 char *extensions = NULL, *infile = NULL;
159 char *outfile = NULL, *keyfile = NULL;
160 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
161 char *passin = NULL, *passout = NULL;
162 char *nofree_passin = NULL, *nofree_passout = NULL;
163 char *req_exts = NULL, *subj = NULL;
164 char *template = default_config_file, *keyout = NULL;
165 const char *keyalg = NULL;
167 int ret = 1, x509 = 0, days = 0, i = 0, newreq = 0, verbose = 0;
168 int pkey_type = -1, private = 0;
169 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
170 int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
171 int nodes = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
173 unsigned long chtype = MBSTRING_ASC, reqflag = 0;
175 #ifndef OPENSSL_NO_DES
176 cipher = EVP_des_ede3_cbc();
179 prog = opt_init(argc, argv, req_options);
180 while ((o = opt_next()) != OPT_EOF) {
185 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
188 opt_help(req_options);
192 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
196 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
200 e = setup_engine(opt_arg(), 0);
202 case OPT_KEYGEN_ENGINE:
203 #ifndef OPENSSL_NO_ENGINE
204 gen_eng = ENGINE_by_id(opt_arg());
205 if (gen_eng == NULL) {
206 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
221 template = opt_arg();
224 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
237 passargin = opt_arg();
240 passargout = opt_arg();
252 pkeyopts = sk_OPENSSL_STRING_new_null();
253 if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
258 sigopts = sk_OPENSSL_STRING_new_null();
259 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
284 chtype = MBSTRING_UTF8;
287 if (!set_nameopt(opt_arg()))
291 if (!set_cert_ex(&reqflag, opt_arg()))
301 days = atoi(opt_arg());
304 if (serial != NULL) {
305 BIO_printf(bio_err, "Serial number supplied twice\n");
308 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
318 case OPT_MULTIVALUE_RDN:
322 if (addext_bio == NULL) {
323 addext_bio = BIO_new(BIO_s_mem());
325 if (addext_bio == NULL
326 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
330 extensions = opt_arg();
333 req_exts = opt_arg();
336 newreq = precert = 1;
339 if (!opt_md(opt_unknown(), &md_alg))
345 argc = opt_num_rest();
350 BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
351 if (x509 && infile == NULL)
354 /* TODO: simplify this as pkey is still always NULL here */
355 private = newreq && (pkey == NULL) ? 1 : 0;
357 if (!app_passwd(passargin, passargout, &passin, &passout)) {
358 BIO_printf(bio_err, "Error getting passwords\n");
363 BIO_printf(bio_err, "Using configuration from %s\n", template);
364 req_conf = app_load_config(template);
368 "Using additional configuraton from command line\n");
369 addext_conf = app_load_config_bio(addext_bio, NULL);
371 if (template != default_config_file && !app_load_modules(req_conf))
374 if (req_conf != NULL) {
375 p = NCONF_get_string(req_conf, NULL, "oid_file");
381 oid_bio = BIO_new_file(p, "r");
382 if (oid_bio == NULL) {
384 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
385 ERR_print_errors(bio_err);
388 OBJ_create_objects(oid_bio);
393 if (!add_oid_section(req_conf))
396 if (md_alg == NULL) {
397 p = NCONF_get_string(req_conf, SECTION, "default_md");
401 if (!opt_md(p, &md_alg))
407 if (extensions == NULL) {
408 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
409 if (extensions == NULL)
412 if (extensions != NULL) {
413 /* Check syntax of file */
415 X509V3_set_ctx_test(&ctx);
416 X509V3_set_nconf(&ctx, req_conf);
417 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
419 "Error Loading extension section %s\n", extensions);
423 if (addext_conf != NULL) {
424 /* Check syntax of command line extensions */
426 X509V3_set_ctx_test(&ctx);
427 X509V3_set_nconf(&ctx, addext_conf);
428 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
429 BIO_printf(bio_err, "Error Loading command line extensions\n");
434 if (passin == NULL) {
435 passin = nofree_passin =
436 NCONF_get_string(req_conf, SECTION, "input_password");
441 if (passout == NULL) {
442 passout = nofree_passout =
443 NCONF_get_string(req_conf, SECTION, "output_password");
448 p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
452 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
453 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
457 if (chtype != MBSTRING_UTF8) {
458 p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
461 else if (strcmp(p, "yes") == 0)
462 chtype = MBSTRING_UTF8;
465 if (req_exts == NULL) {
466 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
467 if (req_exts == NULL)
470 if (req_exts != NULL) {
471 /* Check syntax of file */
473 X509V3_set_ctx_test(&ctx);
474 X509V3_set_nconf(&ctx, req_conf);
475 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
477 "Error Loading request extension section %s\n",
483 if (keyfile != NULL) {
484 pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
486 /* load_key() has already printed an appropriate message */
489 app_RAND_load_conf(req_conf, SECTION);
493 if (newreq && (pkey == NULL)) {
494 app_RAND_load_conf(req_conf, SECTION);
496 if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
497 newkey = DEFAULT_KEY_LENGTH;
500 if (keyalg != NULL) {
501 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
502 &keyalgstr, gen_eng);
507 if (newkey < MIN_KEY_LENGTH
508 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
509 BIO_printf(bio_err, "private key length is too short,\n");
510 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
511 MIN_KEY_LENGTH, newkey);
515 if (genctx == NULL) {
516 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
517 &keyalgstr, gen_eng);
522 if (pkeyopts != NULL) {
524 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
525 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
526 if (pkey_ctrl_string(genctx, genopt) <= 0) {
527 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
528 ERR_print_errors(bio_err);
534 if (pkey_type == EVP_PKEY_EC) {
535 BIO_printf(bio_err, "Generating an EC private key\n");
537 BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
541 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
542 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
544 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
545 BIO_puts(bio_err, "Error Generating Key\n");
549 EVP_PKEY_CTX_free(genctx);
552 if (keyout == NULL) {
553 keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
559 BIO_printf(bio_err, "writing new private key to stdout\n");
561 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
562 out = bio_open_owner(keyout, outformat, private);
566 p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
569 p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
573 if ((p != NULL) && (strcmp(p, "no") == 0))
581 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
582 NULL, 0, NULL, passout)) {
583 if ((ERR_GET_REASON(ERR_peek_error()) ==
584 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
593 BIO_printf(bio_err, "-----\n");
597 in = bio_open_default(infile, 'r', informat);
601 if (informat == FORMAT_ASN1)
602 req = d2i_X509_REQ_bio(in, NULL);
604 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
606 BIO_printf(bio_err, "unable to load X509 request\n");
611 if (newreq || x509) {
613 BIO_printf(bio_err, "you need to specify a private key\n");
618 req = X509_REQ_new();
623 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
624 subj = NULL; /* done processing '-subj' option */
626 BIO_printf(bio_err, "problems making Certificate Request\n");
633 if ((x509ss = X509_new()) == NULL)
636 /* Set version to V3 */
637 if ((extensions != NULL || addext_conf != NULL)
638 && !X509_set_version(x509ss, 2))
640 if (serial != NULL) {
641 if (!X509_set_serialNumber(x509ss, serial))
644 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
648 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
651 /* set default days if it's not specified */
654 if (!set_cert_times(x509ss, NULL, NULL, days))
656 if (!X509_set_subject_name
657 (x509ss, X509_REQ_get_subject_name(req)))
659 tmppkey = X509_REQ_get0_pubkey(req);
660 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
663 /* Set up V3 context struct */
665 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
666 X509V3_set_nconf(&ext_ctx, req_conf);
669 if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
670 &ext_ctx, extensions,
672 BIO_printf(bio_err, "Error Loading extension section %s\n",
676 if (addext_conf != NULL
677 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
679 BIO_printf(bio_err, "Error Loading command line extensions\n");
683 /* If a pre-cert was requested, we need to add a poison extension */
685 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
687 BIO_printf(bio_err, "Error adding poison extension\n");
692 i = do_X509_sign(x509ss, pkey, digest, sigopts);
694 ERR_print_errors(bio_err);
700 /* Set up V3 context struct */
702 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
703 X509V3_set_nconf(&ext_ctx, req_conf);
707 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
709 BIO_printf(bio_err, "Error Loading extension section %s\n",
713 if (addext_conf != NULL
714 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
716 BIO_printf(bio_err, "Error Loading command line extensions\n");
719 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
721 ERR_print_errors(bio_err);
728 BIO_printf(bio_err, "Cannot modify certificate subject\n");
734 BIO_printf(bio_err, "Modifying Request's Subject\n");
735 print_name(bio_err, "old subject=",
736 X509_REQ_get_subject_name(req), get_nameopt());
739 if (build_subject(req, subj, chtype, multirdn) == 0) {
740 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
746 print_name(bio_err, "new subject=",
747 X509_REQ_get_subject_name(req), get_nameopt());
751 if (verify && !x509) {
752 EVP_PKEY *tpubkey = pkey;
754 if (tpubkey == NULL) {
755 tpubkey = X509_REQ_get0_pubkey(req);
760 i = X509_REQ_verify(req, tpubkey);
765 BIO_printf(bio_err, "verify failure\n");
766 ERR_print_errors(bio_err);
767 } else { /* if (i > 0) */
768 BIO_printf(bio_err, "verify OK\n");
772 if (noout && !text && !modulus && !subject && !pubkey) {
777 out = bio_open_default(outfile,
778 keyout != NULL && outfile != NULL &&
779 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
785 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
787 if (tpubkey == NULL) {
788 BIO_printf(bio_err, "Error getting public key\n");
789 ERR_print_errors(bio_err);
792 PEM_write_bio_PUBKEY(out, tpubkey);
797 X509_print_ex(out, x509ss, get_nameopt(), reqflag);
799 X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
804 print_name(out, "subject=", X509_get_subject_name(x509ss),
807 print_name(out, "subject=", X509_REQ_get_subject_name(req),
815 tpubkey = X509_get0_pubkey(x509ss);
817 tpubkey = X509_REQ_get0_pubkey(req);
818 if (tpubkey == NULL) {
819 fprintf(stdout, "Modulus=unavailable\n");
822 fprintf(stdout, "Modulus=");
823 #ifndef OPENSSL_NO_RSA
824 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
826 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
830 fprintf(stdout, "Wrong Algorithm type");
831 fprintf(stdout, "\n");
834 if (!noout && !x509) {
835 if (outformat == FORMAT_ASN1)
836 i = i2d_X509_REQ_bio(out, req);
838 i = PEM_write_bio_X509_REQ_NEW(out, req);
840 i = PEM_write_bio_X509_REQ(out, req);
842 BIO_printf(bio_err, "unable to write X509 request\n");
846 if (!noout && x509 && (x509ss != NULL)) {
847 if (outformat == FORMAT_ASN1)
848 i = i2d_X509_bio(out, x509ss);
850 i = PEM_write_bio_X509(out, x509ss);
852 BIO_printf(bio_err, "unable to write X509 certificate\n");
859 ERR_print_errors(bio_err);
861 NCONF_free(req_conf);
862 BIO_free(addext_bio);
866 EVP_PKEY_CTX_free(genctx);
867 sk_OPENSSL_STRING_free(pkeyopts);
868 sk_OPENSSL_STRING_free(sigopts);
869 #ifndef OPENSSL_NO_ENGINE
870 ENGINE_free(gen_eng);
872 OPENSSL_free(keyalgstr);
875 ASN1_INTEGER_free(serial);
877 if (passin != nofree_passin)
878 OPENSSL_free(passin);
879 if (passout != nofree_passout)
880 OPENSSL_free(passout);
884 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
885 int attribs, unsigned long chtype)
889 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
890 char *tmp, *dn_sect, *attr_sect;
892 tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
895 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
898 dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
899 if (dn_sect == NULL) {
900 BIO_printf(bio_err, "unable to find '%s' in config\n",
904 dn_sk = NCONF_get_section(req_conf, dn_sect);
906 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
910 attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
911 if (attr_sect == NULL) {
915 attr_sk = NCONF_get_section(req_conf, attr_sect);
916 if (attr_sk == NULL) {
917 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
922 /* setup version number */
923 if (!X509_REQ_set_version(req, 0L))
924 goto err; /* version 1 */
927 i = build_subject(req, subj, chtype, multirdn);
929 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
931 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
936 if (!X509_REQ_set_pubkey(req, pkey))
945 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
946 * where characters may be escaped by \
948 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
953 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
956 if (!X509_REQ_set_subject_name(req, n)) {
964 static int prompt_info(X509_REQ *req,
965 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
966 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
967 int attribs, unsigned long chtype)
978 subj = X509_REQ_get_subject_name(req);
982 "You are about to be asked to enter information that will be incorporated\n");
983 BIO_printf(bio_err, "into your certificate request.\n");
985 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
987 "There are quite a few fields but you can leave some blank\n");
989 "For some fields there will be a default value,\n");
991 "If you enter '.', the field will be left blank.\n");
992 BIO_printf(bio_err, "-----\n");
995 if (sk_CONF_VALUE_num(dn_sk)) {
1000 if (sk_CONF_VALUE_num(dn_sk) <= i)
1003 v = sk_CONF_VALUE_value(dn_sk, i);
1006 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1007 !check_end(type, "_default") || !check_end(type, "_value"))
1010 * Skip past any leading X. X: X, etc to allow for multiple
1013 for (p = v->name; *p; p++)
1014 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1026 /* If OBJ not recognised ignore it */
1027 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1029 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1031 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1036 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1038 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1043 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1045 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1051 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1053 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1058 if (!add_DN_object(subj, v->value, def, value, nid,
1059 n_min, n_max, chtype, mval))
1062 if (X509_NAME_entry_count(subj) == 0) {
1064 "error, no objects specified in config file\n");
1069 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1072 "\nPlease enter the following 'extra' attributes\n");
1074 "to be sent with your certificate request\n");
1081 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1084 v = sk_CONF_VALUE_value(attr_sk, i);
1086 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1089 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1091 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1097 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1099 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1105 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1107 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1112 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1114 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1119 if (!add_attribute_object(req,
1120 v->value, def, value, nid, n_min,
1126 BIO_printf(bio_err, "No template, please set one up.\n");
1134 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1135 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1136 unsigned long chtype)
1138 int i, spec_char, plus_char;
1144 subj = X509_REQ_get_subject_name(req);
1146 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1148 v = sk_CONF_VALUE_value(dn_sk, i);
1152 * Skip past any leading X. X: X, etc to allow for multiple instances
1154 for (p = v->name; *p; p++) {
1155 #ifndef CHARSET_EBCDIC
1156 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1158 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1159 || (*p == os_toascii['.']));
1168 #ifndef CHARSET_EBCDIC
1169 plus_char = (*type == '+');
1171 plus_char = (*type == os_toascii['+']);
1179 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1180 (unsigned char *)v->value, -1, -1,
1186 if (!X509_NAME_entry_count(subj)) {
1187 BIO_printf(bio_err, "error, no objects specified in config file\n");
1191 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1192 v = sk_CONF_VALUE_value(attr_sk, i);
1193 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1194 (unsigned char *)v->value, -1))
1201 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1202 char *value, int nid, int n_min, int n_max,
1203 unsigned long chtype, int mval)
1209 BIO_printf(bio_err, "%s [%s]:", text, def);
1210 (void)BIO_flush(bio_err);
1211 if (value != NULL) {
1212 if (!join(buf, sizeof(buf), value, "\n", "DN value"))
1214 BIO_printf(bio_err, "%s\n", value);
1218 if (!fgets(buf, sizeof(buf), stdin))
1228 if (buf[0] == '\n') {
1229 if ((def == NULL) || (def[0] == '\0'))
1231 if (!join(buf, sizeof(buf), def, "\n", "DN default"))
1233 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1238 if (buf[i - 1] != '\n') {
1239 BIO_printf(bio_err, "weird input :-(\n");
1243 #ifdef CHARSET_EBCDIC
1244 ebcdic2ascii(buf, buf, i);
1246 if (!req_check_len(i, n_min, n_max)) {
1252 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1253 (unsigned char *)buf, -1, -1, mval))
1260 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1261 char *value, int nid, int n_min,
1262 int n_max, unsigned long chtype)
1265 static char buf[1024];
1269 BIO_printf(bio_err, "%s [%s]:", text, def);
1270 (void)BIO_flush(bio_err);
1271 if (value != NULL) {
1272 if (!join(buf, sizeof(buf), value, "\n", "Attribute value"))
1274 BIO_printf(bio_err, "%s\n", value);
1278 if (!fgets(buf, sizeof(buf), stdin))
1288 if (buf[0] == '\n') {
1289 if ((def == NULL) || (def[0] == '\0'))
1291 if (!join(buf, sizeof(buf), def, "\n", "Attribute default"))
1293 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1298 if (buf[i - 1] != '\n') {
1299 BIO_printf(bio_err, "weird input :-(\n");
1303 #ifdef CHARSET_EBCDIC
1304 ebcdic2ascii(buf, buf, i);
1306 if (!req_check_len(i, n_min, n_max)) {
1312 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1313 (unsigned char *)buf, -1)) {
1314 BIO_printf(bio_err, "Error adding attribute\n");
1315 ERR_print_errors(bio_err);
1324 static int req_check_len(int len, int n_min, int n_max)
1326 if ((n_min > 0) && (len < n_min)) {
1328 "string is too short, it needs to be at least %d bytes long\n",
1332 if ((n_max >= 0) && (len > n_max)) {
1334 "string is too long, it needs to be no more than %d bytes long\n",
1341 /* Check if the end of a string matches 'end' */
1342 static int check_end(const char *str, const char *end)
1351 tmp = str + slen - elen;
1352 return strcmp(tmp, end);
1356 * Merge the two strings together into the result buffer checking for
1357 * overflow and producing an error message if there is.
1359 static int join(char buf[], size_t buf_size, const char *name,
1360 const char *tail, const char *desc)
1362 const size_t name_len = strlen(name), tail_len = strlen(tail);
1364 if (name_len + tail_len + 1 > buf_size) {
1365 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1368 memcpy(buf, name, name_len);
1369 memcpy(buf + name_len, tail, tail_len + 1);
1373 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1374 int *pkey_type, long *pkeylen,
1375 char **palgnam, ENGINE *keygen_engine)
1377 EVP_PKEY_CTX *gctx = NULL;
1378 EVP_PKEY *param = NULL;
1381 const char *paramfile = NULL;
1384 *pkey_type = EVP_PKEY_RSA;
1386 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1387 *pkey_type = EVP_PKEY_RSA;
1388 keylen = atol(gstr);
1390 } else if (strncmp(gstr, "param:", 6) == 0) {
1391 paramfile = gstr + 6;
1393 const char *p = strchr(gstr, ':');
1396 const EVP_PKEY_ASN1_METHOD *ameth;
1403 * The lookup of a the string will cover all engines so keep a note
1404 * of the implementation.
1407 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1409 if (ameth == NULL) {
1410 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1414 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1415 #ifndef OPENSSL_NO_ENGINE
1416 ENGINE_finish(tmpeng);
1418 if (*pkey_type == EVP_PKEY_RSA) {
1420 keylen = atol(p + 1);
1425 } else if (p != NULL) {
1430 if (paramfile != NULL) {
1431 pbio = BIO_new_file(paramfile, "r");
1433 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1436 param = PEM_read_bio_Parameters(pbio, NULL);
1438 if (param == NULL) {
1441 (void)BIO_reset(pbio);
1442 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1444 param = X509_get_pubkey(x);
1451 if (param == NULL) {
1452 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1455 if (*pkey_type == -1) {
1456 *pkey_type = EVP_PKEY_id(param);
1457 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1458 BIO_printf(bio_err, "Key Type does not match parameters\n");
1459 EVP_PKEY_free(param);
1464 if (palgnam != NULL) {
1465 const EVP_PKEY_ASN1_METHOD *ameth;
1469 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1470 if (ameth == NULL) {
1471 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1474 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1475 *palgnam = OPENSSL_strdup(anam);
1476 #ifndef OPENSSL_NO_ENGINE
1477 ENGINE_finish(tmpeng);
1481 if (param != NULL) {
1482 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1483 *pkeylen = EVP_PKEY_bits(param);
1484 EVP_PKEY_free(param);
1486 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1490 BIO_puts(bio_err, "Error allocating keygen context\n");
1491 ERR_print_errors(bio_err);
1495 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1496 BIO_puts(bio_err, "Error initializing keygen context\n");
1497 ERR_print_errors(bio_err);
1498 EVP_PKEY_CTX_free(gctx);
1501 #ifndef OPENSSL_NO_RSA
1502 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1503 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1504 BIO_puts(bio_err, "Error setting RSA keysize\n");
1505 ERR_print_errors(bio_err);
1506 EVP_PKEY_CTX_free(gctx);
1515 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1518 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1520 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1529 BIO_write(b, &c, 1);
1534 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1535 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1537 EVP_PKEY_CTX *pkctx = NULL;
1542 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1544 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1545 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1546 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1547 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1548 ERR_print_errors(bio_err);
1555 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1556 STACK_OF(OPENSSL_STRING) *sigopts)
1559 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1561 rv = do_sign_init(mctx, pkey, md, sigopts);
1563 rv = X509_sign_ctx(x, mctx);
1564 EVP_MD_CTX_free(mctx);
1565 return rv > 0 ? 1 : 0;
1568 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1569 STACK_OF(OPENSSL_STRING) *sigopts)
1572 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1573 rv = do_sign_init(mctx, pkey, md, sigopts);
1575 rv = X509_REQ_sign_ctx(x, mctx);
1576 EVP_MD_CTX_free(mctx);
1577 return rv > 0 ? 1 : 0;
1580 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1581 STACK_OF(OPENSSL_STRING) *sigopts)
1584 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1585 rv = do_sign_init(mctx, pkey, md, sigopts);
1587 rv = X509_CRL_sign_ctx(x, mctx);
1588 EVP_MD_CTX_free(mctx);
1589 return rv > 0 ? 1 : 0;