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;
75 typedef enum OPTION_choice {
76 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
77 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
78 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
79 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
80 OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
81 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
82 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
83 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_EXTENSIONS,
84 OPT_REQEXTS, OPT_PRECERT, OPT_MD,
88 const OPTIONS req_options[] = {
89 {"help", OPT_HELP, '-', "Display this summary"},
90 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
91 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
92 {"in", OPT_IN, '<', "Input file"},
93 {"out", OPT_OUT, '>', "Output file"},
94 {"key", OPT_KEY, 's', "Private key to use"},
95 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
96 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
97 {"new", OPT_NEW, '-', "New request"},
98 {"config", OPT_CONFIG, '<', "Request template file"},
99 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
100 {"passin", OPT_PASSIN, 's', "Private key password source"},
101 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
103 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
104 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
105 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
106 {"batch", OPT_BATCH, '-',
107 "Do not ask anything during request generation"},
108 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
109 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
110 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
111 {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
112 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
113 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
114 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
115 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
116 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
117 {"text", OPT_TEXT, '-', "Text form of request"},
118 {"x509", OPT_X509, '-',
119 "Output a x509 structure instead of a cert request"},
120 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
121 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
122 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
123 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
124 "Enable support for multivalued RDNs"},
125 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
126 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
127 {"extensions", OPT_EXTENSIONS, 's',
128 "Cert extension section (override value in config file)"},
129 {"reqexts", OPT_REQEXTS, 's',
130 "Request extension section (override value in config file)"},
131 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
132 {"", OPT_MD, '-', "Any supported digest"},
133 #ifndef OPENSSL_NO_ENGINE
134 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
135 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
136 "Specify engine to be used for key generation operations"},
141 int req_main(int argc, char **argv)
143 ASN1_INTEGER *serial = NULL;
144 BIO *in = NULL, *out = NULL;
145 ENGINE *e = NULL, *gen_eng = NULL;
146 EVP_PKEY *pkey = NULL;
147 EVP_PKEY_CTX *genctx = NULL;
148 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
150 X509_REQ *req = NULL;
151 const EVP_CIPHER *cipher = NULL;
152 const EVP_MD *md_alg = NULL, *digest = NULL;
153 char *extensions = NULL, *infile = NULL;
154 char *outfile = NULL, *keyfile = NULL;
155 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
156 char *passin = NULL, *passout = NULL;
157 char *nofree_passin = NULL, *nofree_passout = NULL;
158 char *req_exts = NULL, *subj = NULL;
159 char *template = default_config_file, *keyout = NULL;
160 const char *keyalg = NULL;
162 int ret = 1, x509 = 0, days = 30, i = 0, newreq = 0, verbose = 0;
163 int pkey_type = -1, private = 0;
164 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
165 int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
166 int nodes = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
168 unsigned long chtype = MBSTRING_ASC, reqflag = 0;
170 #ifndef OPENSSL_NO_DES
171 cipher = EVP_des_ede3_cbc();
174 prog = opt_init(argc, argv, req_options);
175 while ((o = opt_next()) != OPT_EOF) {
180 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
183 opt_help(req_options);
187 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
191 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
195 e = setup_engine(opt_arg(), 0);
197 case OPT_KEYGEN_ENGINE:
198 #ifndef OPENSSL_NO_ENGINE
199 gen_eng = ENGINE_by_id(opt_arg());
200 if (gen_eng == NULL) {
201 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
216 template = opt_arg();
219 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
232 passargin = opt_arg();
235 passargout = opt_arg();
247 pkeyopts = sk_OPENSSL_STRING_new_null();
248 if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
253 sigopts = sk_OPENSSL_STRING_new_null();
254 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
279 chtype = MBSTRING_UTF8;
282 if (!set_nameopt(opt_arg()))
286 if (!set_cert_ex(&reqflag, opt_arg()))
296 days = atoi(opt_arg());
299 if (serial != NULL) {
300 BIO_printf(bio_err, "Serial number supplied twice\n");
303 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
313 case OPT_MULTIVALUE_RDN:
317 extensions = opt_arg();
320 req_exts = opt_arg();
323 newreq = precert = 1;
326 if (!opt_md(opt_unknown(), &md_alg))
332 argc = opt_num_rest();
336 if (x509 && infile == NULL)
339 /* TODO: simplify this as pkey is still always NULL here */
340 private = newreq && (pkey == NULL) ? 1 : 0;
342 if (!app_passwd(passargin, passargout, &passin, &passout)) {
343 BIO_printf(bio_err, "Error getting passwords\n");
348 BIO_printf(bio_err, "Using configuration from %s\n", template);
349 req_conf = app_load_config(template);
350 if (template != default_config_file && !app_load_modules(req_conf))
353 if (req_conf != NULL) {
354 p = NCONF_get_string(req_conf, NULL, "oid_file");
360 oid_bio = BIO_new_file(p, "r");
361 if (oid_bio == NULL) {
363 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
364 ERR_print_errors(bio_err);
367 OBJ_create_objects(oid_bio);
372 if (!add_oid_section(req_conf))
375 if (md_alg == NULL) {
376 p = NCONF_get_string(req_conf, SECTION, "default_md");
380 if (!opt_md(p, &md_alg))
386 if (extensions == NULL) {
387 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
388 if (extensions == NULL)
391 if (extensions != NULL) {
392 /* Check syntax of file */
394 X509V3_set_ctx_test(&ctx);
395 X509V3_set_nconf(&ctx, req_conf);
396 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
398 "Error Loading extension section %s\n", extensions);
403 if (passin == NULL) {
404 passin = nofree_passin =
405 NCONF_get_string(req_conf, SECTION, "input_password");
410 if (passout == NULL) {
411 passout = nofree_passout =
412 NCONF_get_string(req_conf, SECTION, "output_password");
417 p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
421 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
422 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
426 if (chtype != MBSTRING_UTF8) {
427 p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
430 else if (strcmp(p, "yes") == 0)
431 chtype = MBSTRING_UTF8;
434 if (req_exts == NULL) {
435 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
436 if (req_exts == NULL)
439 if (req_exts != NULL) {
440 /* Check syntax of file */
442 X509V3_set_ctx_test(&ctx);
443 X509V3_set_nconf(&ctx, req_conf);
444 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
446 "Error Loading request extension section %s\n",
452 if (keyfile != NULL) {
453 pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
455 /* load_key() has already printed an appropriate message */
458 app_RAND_load_conf(req_conf, SECTION);
462 if (newreq && (pkey == NULL)) {
463 app_RAND_load_conf(req_conf, SECTION);
465 if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
466 newkey = DEFAULT_KEY_LENGTH;
469 if (keyalg != NULL) {
470 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
471 &keyalgstr, gen_eng);
476 if (newkey < MIN_KEY_LENGTH
477 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
478 BIO_printf(bio_err, "private key length is too short,\n");
479 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
480 MIN_KEY_LENGTH, newkey);
484 if (genctx == NULL) {
485 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
486 &keyalgstr, gen_eng);
491 if (pkeyopts != NULL) {
493 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
494 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
495 if (pkey_ctrl_string(genctx, genopt) <= 0) {
496 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
497 ERR_print_errors(bio_err);
503 if (pkey_type == EVP_PKEY_EC) {
504 BIO_printf(bio_err, "Generating an EC private key\n");
506 BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
510 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
511 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
513 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
514 BIO_puts(bio_err, "Error Generating Key\n");
518 EVP_PKEY_CTX_free(genctx);
521 if (keyout == NULL) {
522 keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
528 BIO_printf(bio_err, "writing new private key to stdout\n");
530 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
531 out = bio_open_owner(keyout, outformat, private);
535 p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
538 p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
542 if ((p != NULL) && (strcmp(p, "no") == 0))
550 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
551 NULL, 0, NULL, passout)) {
552 if ((ERR_GET_REASON(ERR_peek_error()) ==
553 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
562 BIO_printf(bio_err, "-----\n");
566 in = bio_open_default(infile, 'r', informat);
570 if (informat == FORMAT_ASN1)
571 req = d2i_X509_REQ_bio(in, NULL);
573 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
575 BIO_printf(bio_err, "unable to load X509 request\n");
580 if (newreq || x509) {
582 BIO_printf(bio_err, "you need to specify a private key\n");
587 req = X509_REQ_new();
592 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
593 subj = NULL; /* done processing '-subj' option */
595 BIO_printf(bio_err, "problems making Certificate Request\n");
602 if ((x509ss = X509_new()) == NULL)
605 /* Set version to V3 */
606 if (extensions != NULL && !X509_set_version(x509ss, 2))
608 if (serial != NULL) {
609 if (!X509_set_serialNumber(x509ss, serial))
612 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
616 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
618 if (!set_cert_times(x509ss, NULL, NULL, days))
620 if (!X509_set_subject_name
621 (x509ss, X509_REQ_get_subject_name(req)))
623 tmppkey = X509_REQ_get0_pubkey(req);
624 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
627 /* Set up V3 context struct */
629 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
630 X509V3_set_nconf(&ext_ctx, req_conf);
633 if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
634 &ext_ctx, extensions,
636 BIO_printf(bio_err, "Error Loading extension section %s\n",
641 /* If a pre-cert was requested, we need to add a poison extension */
643 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
645 BIO_printf(bio_err, "Error adding poison extension\n");
650 i = do_X509_sign(x509ss, pkey, digest, sigopts);
652 ERR_print_errors(bio_err);
658 /* Set up V3 context struct */
660 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
661 X509V3_set_nconf(&ext_ctx, req_conf);
665 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
667 BIO_printf(bio_err, "Error Loading extension section %s\n",
671 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
673 ERR_print_errors(bio_err);
680 BIO_printf(bio_err, "Cannot modify certificate subject\n");
686 BIO_printf(bio_err, "Modifying Request's Subject\n");
687 print_name(bio_err, "old subject=",
688 X509_REQ_get_subject_name(req), get_nameopt());
691 if (build_subject(req, subj, chtype, multirdn) == 0) {
692 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
698 print_name(bio_err, "new subject=",
699 X509_REQ_get_subject_name(req), get_nameopt());
703 if (verify && !x509) {
704 EVP_PKEY *tpubkey = pkey;
706 if (tpubkey == NULL) {
707 tpubkey = X509_REQ_get0_pubkey(req);
712 i = X509_REQ_verify(req, tpubkey);
717 BIO_printf(bio_err, "verify failure\n");
718 ERR_print_errors(bio_err);
719 } else { /* if (i > 0) */
720 BIO_printf(bio_err, "verify OK\n");
724 if (noout && !text && !modulus && !subject && !pubkey) {
729 out = bio_open_default(outfile,
730 keyout != NULL && outfile != NULL &&
731 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
737 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
739 if (tpubkey == NULL) {
740 BIO_printf(bio_err, "Error getting public key\n");
741 ERR_print_errors(bio_err);
744 PEM_write_bio_PUBKEY(out, tpubkey);
749 X509_print_ex(out, x509ss, get_nameopt(), reqflag);
751 X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
756 print_name(out, "subject=", X509_get_subject_name(x509ss),
759 print_name(out, "subject=", X509_REQ_get_subject_name(req),
767 tpubkey = X509_get0_pubkey(x509ss);
769 tpubkey = X509_REQ_get0_pubkey(req);
770 if (tpubkey == NULL) {
771 fprintf(stdout, "Modulus=unavailable\n");
774 fprintf(stdout, "Modulus=");
775 #ifndef OPENSSL_NO_RSA
776 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
778 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
782 fprintf(stdout, "Wrong Algorithm type");
783 fprintf(stdout, "\n");
786 if (!noout && !x509) {
787 if (outformat == FORMAT_ASN1)
788 i = i2d_X509_REQ_bio(out, req);
790 i = PEM_write_bio_X509_REQ_NEW(out, req);
792 i = PEM_write_bio_X509_REQ(out, req);
794 BIO_printf(bio_err, "unable to write X509 request\n");
798 if (!noout && x509 && (x509ss != NULL)) {
799 if (outformat == FORMAT_ASN1)
800 i = i2d_X509_bio(out, x509ss);
802 i = PEM_write_bio_X509(out, x509ss);
804 BIO_printf(bio_err, "unable to write X509 certificate\n");
811 ERR_print_errors(bio_err);
813 NCONF_free(req_conf);
817 EVP_PKEY_CTX_free(genctx);
818 sk_OPENSSL_STRING_free(pkeyopts);
819 sk_OPENSSL_STRING_free(sigopts);
820 #ifndef OPENSSL_NO_ENGINE
821 ENGINE_free(gen_eng);
823 OPENSSL_free(keyalgstr);
826 ASN1_INTEGER_free(serial);
828 if (passin != nofree_passin)
829 OPENSSL_free(passin);
830 if (passout != nofree_passout)
831 OPENSSL_free(passout);
835 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
836 int attribs, unsigned long chtype)
840 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
841 char *tmp, *dn_sect, *attr_sect;
843 tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
846 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
849 dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
850 if (dn_sect == NULL) {
851 BIO_printf(bio_err, "unable to find '%s' in config\n",
855 dn_sk = NCONF_get_section(req_conf, dn_sect);
857 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
861 attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
862 if (attr_sect == NULL) {
866 attr_sk = NCONF_get_section(req_conf, attr_sect);
867 if (attr_sk == NULL) {
868 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
873 /* setup version number */
874 if (!X509_REQ_set_version(req, 0L))
875 goto err; /* version 1 */
878 i = build_subject(req, subj, chtype, multirdn);
880 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
882 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
887 if (!X509_REQ_set_pubkey(req, pkey))
896 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
897 * where characters may be escaped by \
899 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
904 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
907 if (!X509_REQ_set_subject_name(req, n)) {
915 static int prompt_info(X509_REQ *req,
916 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
917 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
918 int attribs, unsigned long chtype)
929 subj = X509_REQ_get_subject_name(req);
933 "You are about to be asked to enter information that will be incorporated\n");
934 BIO_printf(bio_err, "into your certificate request.\n");
936 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
938 "There are quite a few fields but you can leave some blank\n");
940 "For some fields there will be a default value,\n");
942 "If you enter '.', the field will be left blank.\n");
943 BIO_printf(bio_err, "-----\n");
946 if (sk_CONF_VALUE_num(dn_sk)) {
951 if (sk_CONF_VALUE_num(dn_sk) <= i)
954 v = sk_CONF_VALUE_value(dn_sk, i);
957 if (!check_end(type, "_min") || !check_end(type, "_max") ||
958 !check_end(type, "_default") || !check_end(type, "_value"))
961 * Skip past any leading X. X: X, etc to allow for multiple
964 for (p = v->name; *p; p++)
965 if ((*p == ':') || (*p == ',') || (*p == '.')) {
977 /* If OBJ not recognised ignore it */
978 if ((nid = OBJ_txt2nid(type)) == NID_undef)
980 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
982 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
987 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
989 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
994 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
996 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1002 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1004 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1009 if (!add_DN_object(subj, v->value, def, value, nid,
1010 n_min, n_max, chtype, mval))
1013 if (X509_NAME_entry_count(subj) == 0) {
1015 "error, no objects specified in config file\n");
1020 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1023 "\nPlease enter the following 'extra' attributes\n");
1025 "to be sent with your certificate request\n");
1032 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1035 v = sk_CONF_VALUE_value(attr_sk, i);
1037 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1040 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1042 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1048 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1050 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1056 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1058 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1063 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1065 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1070 if (!add_attribute_object(req,
1071 v->value, def, value, nid, n_min,
1077 BIO_printf(bio_err, "No template, please set one up.\n");
1085 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1086 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1087 unsigned long chtype)
1089 int i, spec_char, plus_char;
1095 subj = X509_REQ_get_subject_name(req);
1097 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1099 v = sk_CONF_VALUE_value(dn_sk, i);
1103 * Skip past any leading X. X: X, etc to allow for multiple instances
1105 for (p = v->name; *p; p++) {
1106 #ifndef CHARSET_EBCDIC
1107 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1109 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1110 || (*p == os_toascii['.']));
1119 #ifndef CHARSET_EBCDIC
1120 plus_char = (*type == '+');
1122 plus_char = (*type == os_toascii['+']);
1130 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1131 (unsigned char *)v->value, -1, -1,
1137 if (!X509_NAME_entry_count(subj)) {
1138 BIO_printf(bio_err, "error, no objects specified in config file\n");
1142 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1143 v = sk_CONF_VALUE_value(attr_sk, i);
1144 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1145 (unsigned char *)v->value, -1))
1152 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1153 char *value, int nid, int n_min, int n_max,
1154 unsigned long chtype, int mval)
1160 BIO_printf(bio_err, "%s [%s]:", text, def);
1161 (void)BIO_flush(bio_err);
1162 if (value != NULL) {
1163 if (!join(buf, sizeof(buf), value, "\n", "DN value"))
1165 BIO_printf(bio_err, "%s\n", value);
1169 if (!fgets(buf, sizeof buf, stdin))
1179 if (buf[0] == '\n') {
1180 if ((def == NULL) || (def[0] == '\0'))
1182 if (!join(buf, sizeof(buf), def, "\n", "DN default"))
1184 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1189 if (buf[i - 1] != '\n') {
1190 BIO_printf(bio_err, "weird input :-(\n");
1194 #ifdef CHARSET_EBCDIC
1195 ebcdic2ascii(buf, buf, i);
1197 if (!req_check_len(i, n_min, n_max)) {
1203 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1204 (unsigned char *)buf, -1, -1, mval))
1211 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1212 char *value, int nid, int n_min,
1213 int n_max, unsigned long chtype)
1216 static char buf[1024];
1220 BIO_printf(bio_err, "%s [%s]:", text, def);
1221 (void)BIO_flush(bio_err);
1222 if (value != NULL) {
1223 if (!join(buf, sizeof(buf), value, "\n", "Attribute value"))
1225 BIO_printf(bio_err, "%s\n", value);
1229 if (!fgets(buf, sizeof buf, stdin))
1239 if (buf[0] == '\n') {
1240 if ((def == NULL) || (def[0] == '\0'))
1242 if (!join(buf, sizeof(buf), def, "\n", "Attribute default"))
1244 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1249 if (buf[i - 1] != '\n') {
1250 BIO_printf(bio_err, "weird input :-(\n");
1254 #ifdef CHARSET_EBCDIC
1255 ebcdic2ascii(buf, buf, i);
1257 if (!req_check_len(i, n_min, n_max)) {
1263 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1264 (unsigned char *)buf, -1)) {
1265 BIO_printf(bio_err, "Error adding attribute\n");
1266 ERR_print_errors(bio_err);
1275 static int req_check_len(int len, int n_min, int n_max)
1277 if ((n_min > 0) && (len < n_min)) {
1279 "string is too short, it needs to be at least %d bytes long\n",
1283 if ((n_max >= 0) && (len > n_max)) {
1285 "string is too long, it needs to be no more than %d bytes long\n",
1292 /* Check if the end of a string matches 'end' */
1293 static int check_end(const char *str, const char *end)
1302 tmp = str + slen - elen;
1303 return strcmp(tmp, end);
1307 * Merge the two strings together into the result buffer checking for
1308 * overflow and producing an error message if there is.
1310 static int join(char buf[], size_t buf_size, const char *name,
1311 const char *tail, const char *desc)
1313 const size_t name_len = strlen(name), tail_len = strlen(tail);
1315 if (name_len + tail_len + 1 > buf_size) {
1316 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1319 memcpy(buf, name, name_len);
1320 memcpy(buf + name_len, tail, tail_len + 1);
1324 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1325 int *pkey_type, long *pkeylen,
1326 char **palgnam, ENGINE *keygen_engine)
1328 EVP_PKEY_CTX *gctx = NULL;
1329 EVP_PKEY *param = NULL;
1332 const char *paramfile = NULL;
1335 *pkey_type = EVP_PKEY_RSA;
1337 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1338 *pkey_type = EVP_PKEY_RSA;
1339 keylen = atol(gstr);
1341 } else if (strncmp(gstr, "param:", 6) == 0) {
1342 paramfile = gstr + 6;
1344 const char *p = strchr(gstr, ':');
1347 const EVP_PKEY_ASN1_METHOD *ameth;
1354 * The lookup of a the string will cover all engines so keep a note
1355 * of the implementation.
1358 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1360 if (ameth == NULL) {
1361 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1365 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1366 #ifndef OPENSSL_NO_ENGINE
1367 ENGINE_finish(tmpeng);
1369 if (*pkey_type == EVP_PKEY_RSA) {
1371 keylen = atol(p + 1);
1376 } else if (p != NULL) {
1381 if (paramfile != NULL) {
1382 pbio = BIO_new_file(paramfile, "r");
1384 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1387 param = PEM_read_bio_Parameters(pbio, NULL);
1389 if (param == NULL) {
1392 (void)BIO_reset(pbio);
1393 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1395 param = X509_get_pubkey(x);
1402 if (param == NULL) {
1403 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1406 if (*pkey_type == -1) {
1407 *pkey_type = EVP_PKEY_id(param);
1408 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1409 BIO_printf(bio_err, "Key Type does not match parameters\n");
1410 EVP_PKEY_free(param);
1415 if (palgnam != NULL) {
1416 const EVP_PKEY_ASN1_METHOD *ameth;
1420 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1421 if (ameth == NULL) {
1422 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1425 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1426 *palgnam = OPENSSL_strdup(anam);
1427 #ifndef OPENSSL_NO_ENGINE
1428 ENGINE_finish(tmpeng);
1432 if (param != NULL) {
1433 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1434 *pkeylen = EVP_PKEY_bits(param);
1435 EVP_PKEY_free(param);
1437 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1441 BIO_puts(bio_err, "Error allocating keygen context\n");
1442 ERR_print_errors(bio_err);
1446 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1447 BIO_puts(bio_err, "Error initializing keygen context\n");
1448 ERR_print_errors(bio_err);
1449 EVP_PKEY_CTX_free(gctx);
1452 #ifndef OPENSSL_NO_RSA
1453 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1454 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1455 BIO_puts(bio_err, "Error setting RSA keysize\n");
1456 ERR_print_errors(bio_err);
1457 EVP_PKEY_CTX_free(gctx);
1466 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1469 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1471 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1480 BIO_write(b, &c, 1);
1485 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1486 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1488 EVP_PKEY_CTX *pkctx = NULL;
1493 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1495 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1496 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1497 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1498 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1499 ERR_print_errors(bio_err);
1506 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1507 STACK_OF(OPENSSL_STRING) *sigopts)
1510 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1512 rv = do_sign_init(mctx, pkey, md, sigopts);
1514 rv = X509_sign_ctx(x, mctx);
1515 EVP_MD_CTX_free(mctx);
1516 return rv > 0 ? 1 : 0;
1519 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1520 STACK_OF(OPENSSL_STRING) *sigopts)
1523 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1524 rv = do_sign_init(mctx, pkey, md, sigopts);
1526 rv = X509_REQ_sign_ctx(x, mctx);
1527 EVP_MD_CTX_free(mctx);
1528 return rv > 0 ? 1 : 0;
1531 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1532 STACK_OF(OPENSSL_STRING) *sigopts)
1535 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1536 rv = do_sign_init(mctx, pkey, md, sigopts);
1538 rv = X509_CRL_sign_ctx(x, mctx);
1539 EVP_MD_CTX_free(mctx);
1540 return rv > 0 ? 1 : 0;