2 * Copyright 1995-2016 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 EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
68 int *pkey_type, long *pkeylen,
69 char **palgnam, ENGINE *keygen_engine);
70 static CONF *req_conf = NULL;
73 typedef enum OPTION_choice {
74 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
75 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
76 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
77 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_RAND, OPT_NEWKEY,
78 OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
79 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
80 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
81 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_EXTENSIONS,
82 OPT_REQEXTS, OPT_PRECERT, OPT_MD
85 const OPTIONS req_options[] = {
86 {"help", OPT_HELP, '-', "Display this summary"},
87 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
88 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
89 {"in", OPT_IN, '<', "Input file"},
90 {"out", OPT_OUT, '>', "Output file"},
91 {"key", OPT_KEY, 's', "Private key to use"},
92 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
93 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
94 {"new", OPT_NEW, '-', "New request"},
95 {"config", OPT_CONFIG, '<', "Request template file"},
96 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
97 {"passin", OPT_PASSIN, 's', "Private key password source"},
98 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
99 {"rand", OPT_RAND, 's',
100 "Load the file(s) into the random number generator"},
101 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
102 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
103 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
104 {"batch", OPT_BATCH, '-',
105 "Do not ask anything during request generation"},
106 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
107 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
108 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
109 {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
110 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
111 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
112 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
113 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
114 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
115 {"text", OPT_TEXT, '-', "Text form of request"},
116 {"x509", OPT_X509, '-',
117 "Output a x509 structure instead of a cert request"},
118 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
119 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
120 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
121 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
122 "Enable support for multivalued RDNs"},
123 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
124 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
125 {"extensions", OPT_EXTENSIONS, 's',
126 "Cert extension section (override value in config file)"},
127 {"reqexts", OPT_REQEXTS, 's',
128 "Request extension section (override value in config file)"},
129 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
130 {"", OPT_MD, '-', "Any supported digest"},
131 #ifndef OPENSSL_NO_ENGINE
132 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
133 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
134 "Specify engine to be used for key generation operations"},
139 int req_main(int argc, char **argv)
141 ASN1_INTEGER *serial = NULL;
142 BIO *in = NULL, *out = NULL;
143 ENGINE *e = NULL, *gen_eng = NULL;
144 EVP_PKEY *pkey = NULL;
145 EVP_PKEY_CTX *genctx = NULL;
146 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
148 X509_REQ *req = NULL;
149 const EVP_CIPHER *cipher = NULL;
150 const EVP_MD *md_alg = NULL, *digest = NULL;
151 char *extensions = NULL, *infile = NULL;
152 char *outfile = NULL, *keyfile = NULL, *inrand = NULL;
153 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
154 char *passin = NULL, *passout = NULL;
155 char *nofree_passin = NULL, *nofree_passout = NULL;
156 char *req_exts = NULL, *subj = NULL;
157 char *template = default_config_file, *keyout = NULL;
158 const char *keyalg = NULL;
160 int ret = 1, x509 = 0, days = 30, i = 0, newreq = 0, verbose = 0;
161 int pkey_type = -1, private = 0;
162 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
163 int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
164 int nodes = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
166 unsigned long chtype = MBSTRING_ASC, nmflag = 0, reqflag = 0;
169 #ifndef OPENSSL_NO_DES
170 cipher = EVP_des_ede3_cbc();
173 prog = opt_init(argc, argv, req_options);
174 while ((o = opt_next()) != OPT_EOF) {
179 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
182 opt_help(req_options);
186 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
190 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
194 e = setup_engine(opt_arg(), 0);
196 case OPT_KEYGEN_ENGINE:
197 #ifndef OPENSSL_NO_ENGINE
198 gen_eng = ENGINE_by_id(opt_arg());
199 if (gen_eng == NULL) {
200 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
215 template = opt_arg();
218 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
231 passargin = opt_arg();
234 passargout = opt_arg();
245 pkeyopts = sk_OPENSSL_STRING_new_null();
246 if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
251 sigopts = sk_OPENSSL_STRING_new_null();
252 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
277 chtype = MBSTRING_UTF8;
281 if (!set_name_ex(&nmflag, opt_arg()))
285 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();
337 nmflag = XN_FLAG_ONELINE;
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))
387 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
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 && !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;
435 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
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 char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
459 if (randfile == NULL)
461 app_RAND_load_file(randfile, 0);
465 if (newreq && (pkey == NULL)) {
466 char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
467 if (randfile == NULL)
469 app_RAND_load_file(randfile, 0);
471 app_RAND_load_files(inrand);
473 if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
474 newkey = DEFAULT_KEY_LENGTH;
478 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
479 &keyalgstr, gen_eng);
484 if (newkey < MIN_KEY_LENGTH
485 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
486 BIO_printf(bio_err, "private key length is too short,\n");
487 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
488 MIN_KEY_LENGTH, newkey);
493 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
494 &keyalgstr, gen_eng);
501 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
502 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
503 if (pkey_ctrl_string(genctx, genopt) <= 0) {
504 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
505 ERR_print_errors(bio_err);
511 if (pkey_type == EVP_PKEY_EC) {
512 BIO_printf(bio_err, "Generating an EC private key\n");
514 BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
518 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
519 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
521 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
522 BIO_puts(bio_err, "Error Generating Key\n");
526 EVP_PKEY_CTX_free(genctx);
529 app_RAND_write_file(randfile);
531 if (keyout == NULL) {
532 keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
538 BIO_printf(bio_err, "writing new private key to stdout\n");
540 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
541 out = bio_open_owner(keyout, outformat, private);
545 p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
548 p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
552 if ((p != NULL) && (strcmp(p, "no") == 0))
560 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
561 NULL, 0, NULL, passout)) {
562 if ((ERR_GET_REASON(ERR_peek_error()) ==
563 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
572 BIO_printf(bio_err, "-----\n");
576 in = bio_open_default(infile, 'r', informat);
580 if (informat == FORMAT_ASN1)
581 req = d2i_X509_REQ_bio(in, NULL);
583 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
585 BIO_printf(bio_err, "unable to load X509 request\n");
592 BIO_printf(bio_err, "you need to specify a private key\n");
597 req = X509_REQ_new();
602 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
603 subj = NULL; /* done processing '-subj' option */
605 BIO_printf(bio_err, "problems making Certificate Request\n");
612 if ((x509ss = X509_new()) == NULL)
615 /* Set version to V3 */
616 if (extensions && !X509_set_version(x509ss, 2))
619 if (!X509_set_serialNumber(x509ss, serial))
622 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
626 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
628 if (!set_cert_times(x509ss, NULL, NULL, days))
630 if (!X509_set_subject_name
631 (x509ss, X509_REQ_get_subject_name(req)))
633 tmppkey = X509_REQ_get0_pubkey(req);
634 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
637 /* Set up V3 context struct */
639 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
640 X509V3_set_nconf(&ext_ctx, req_conf);
643 if (extensions && !X509V3_EXT_add_nconf(req_conf,
644 &ext_ctx, extensions,
646 BIO_printf(bio_err, "Error Loading extension section %s\n",
651 /* If a pre-cert was requested, we need to add a poison extension */
653 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
655 BIO_printf(bio_err, "Error adding poison extension\n");
660 i = do_X509_sign(x509ss, pkey, digest, sigopts);
662 ERR_print_errors(bio_err);
668 /* Set up V3 context struct */
670 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
671 X509V3_set_nconf(&ext_ctx, req_conf);
674 if (req_exts && !X509V3_EXT_REQ_add_nconf(req_conf,
677 BIO_printf(bio_err, "Error Loading extension section %s\n",
681 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
683 ERR_print_errors(bio_err);
690 BIO_printf(bio_err, "Cannot modify certificate subject\n");
696 BIO_printf(bio_err, "Modifying Request's Subject\n");
697 print_name(bio_err, "old subject=",
698 X509_REQ_get_subject_name(req), nmflag);
701 if (build_subject(req, subj, chtype, multirdn) == 0) {
702 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
708 print_name(bio_err, "new subject=",
709 X509_REQ_get_subject_name(req), nmflag);
713 if (verify && !x509) {
714 EVP_PKEY *tpubkey = pkey;
716 if (tpubkey == NULL) {
717 tpubkey = X509_REQ_get0_pubkey(req);
722 i = X509_REQ_verify(req, tpubkey);
727 BIO_printf(bio_err, "verify failure\n");
728 ERR_print_errors(bio_err);
729 } else /* if (i > 0) */
730 BIO_printf(bio_err, "verify OK\n");
733 if (noout && !text && !modulus && !subject && !pubkey) {
738 out = bio_open_default(outfile,
739 keyout != NULL && outfile != NULL &&
740 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
746 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
748 if (tpubkey == NULL) {
749 BIO_printf(bio_err, "Error getting public key\n");
750 ERR_print_errors(bio_err);
753 PEM_write_bio_PUBKEY(out, tpubkey);
758 X509_print_ex(out, x509ss, nmflag, reqflag);
760 X509_REQ_print_ex(out, req, nmflag, reqflag);
765 print_name(out, "subject=", X509_get_subject_name(x509ss),
768 print_name(out, "subject=", X509_REQ_get_subject_name(req),
776 tpubkey = X509_get0_pubkey(x509ss);
778 tpubkey = X509_REQ_get0_pubkey(req);
779 if (tpubkey == NULL) {
780 fprintf(stdout, "Modulus=unavailable\n");
783 fprintf(stdout, "Modulus=");
784 #ifndef OPENSSL_NO_RSA
785 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
787 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
791 fprintf(stdout, "Wrong Algorithm type");
792 fprintf(stdout, "\n");
795 if (!noout && !x509) {
796 if (outformat == FORMAT_ASN1)
797 i = i2d_X509_REQ_bio(out, req);
799 i = PEM_write_bio_X509_REQ_NEW(out, req);
801 i = PEM_write_bio_X509_REQ(out, req);
803 BIO_printf(bio_err, "unable to write X509 request\n");
807 if (!noout && x509 && (x509ss != NULL)) {
808 if (outformat == FORMAT_ASN1)
809 i = i2d_X509_bio(out, x509ss);
811 i = PEM_write_bio_X509(out, x509ss);
813 BIO_printf(bio_err, "unable to write X509 certificate\n");
820 ERR_print_errors(bio_err);
822 NCONF_free(req_conf);
826 EVP_PKEY_CTX_free(genctx);
827 sk_OPENSSL_STRING_free(pkeyopts);
828 sk_OPENSSL_STRING_free(sigopts);
829 #ifndef OPENSSL_NO_ENGINE
830 ENGINE_free(gen_eng);
832 OPENSSL_free(keyalgstr);
835 ASN1_INTEGER_free(serial);
837 if (passin != nofree_passin)
838 OPENSSL_free(passin);
839 if (passout != nofree_passout)
840 OPENSSL_free(passout);
844 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
845 int attribs, unsigned long chtype)
849 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
850 char *tmp, *dn_sect, *attr_sect;
852 tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
855 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
858 dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
859 if (dn_sect == NULL) {
860 BIO_printf(bio_err, "unable to find '%s' in config\n",
864 dn_sk = NCONF_get_section(req_conf, dn_sect);
866 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
870 attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
871 if (attr_sect == NULL) {
875 attr_sk = NCONF_get_section(req_conf, attr_sect);
876 if (attr_sk == NULL) {
877 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
882 /* setup version number */
883 if (!X509_REQ_set_version(req, 0L))
884 goto err; /* version 1 */
887 i = build_subject(req, subj, chtype, multirdn);
889 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
891 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
896 if (!X509_REQ_set_pubkey(req, pkey))
905 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
906 * where characters may be escaped by \
908 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
913 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
916 if (!X509_REQ_set_subject_name(req, n)) {
924 static int prompt_info(X509_REQ *req,
925 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
926 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
927 int attribs, unsigned long chtype)
938 subj = X509_REQ_get_subject_name(req);
942 "You are about to be asked to enter information that will be incorporated\n");
943 BIO_printf(bio_err, "into your certificate request.\n");
945 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
947 "There are quite a few fields but you can leave some blank\n");
949 "For some fields there will be a default value,\n");
951 "If you enter '.', the field will be left blank.\n");
952 BIO_printf(bio_err, "-----\n");
955 if (sk_CONF_VALUE_num(dn_sk)) {
959 if (sk_CONF_VALUE_num(dn_sk) <= i)
962 v = sk_CONF_VALUE_value(dn_sk, i);
965 if (!check_end(type, "_min") || !check_end(type, "_max") ||
966 !check_end(type, "_default") || !check_end(type, "_value"))
969 * Skip past any leading X. X: X, etc to allow for multiple
972 for (p = v->name; *p; p++)
973 if ((*p == ':') || (*p == ',') || (*p == '.')) {
984 /* If OBJ not recognised ignore it */
985 if ((nid = OBJ_txt2nid(type)) == NID_undef)
987 if (BIO_snprintf(buf, sizeof buf, "%s_default", v->name)
988 >= (int)sizeof(buf)) {
989 BIO_printf(bio_err, "Name '%s' too long\n", v->name);
993 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
998 BIO_snprintf(buf, sizeof buf, "%s_value", v->name);
999 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1004 BIO_snprintf(buf, sizeof buf, "%s_min", v->name);
1005 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1010 BIO_snprintf(buf, sizeof buf, "%s_max", v->name);
1011 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1016 if (!add_DN_object(subj, v->value, def, value, nid,
1017 n_min, n_max, chtype, mval))
1020 if (X509_NAME_entry_count(subj) == 0) {
1022 "error, no objects specified in config file\n");
1027 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1030 "\nPlease enter the following 'extra' attributes\n");
1032 "to be sent with your certificate request\n");
1038 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1041 v = sk_CONF_VALUE_value(attr_sk, i);
1043 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1046 if (BIO_snprintf(buf, sizeof buf, "%s_default", type)
1047 >= (int)sizeof(buf)) {
1048 BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1052 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1058 BIO_snprintf(buf, sizeof buf, "%s_value", type);
1059 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1065 BIO_snprintf(buf, sizeof buf, "%s_min", type);
1066 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1071 BIO_snprintf(buf, sizeof buf, "%s_max", type);
1072 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1077 if (!add_attribute_object(req,
1078 v->value, def, value, nid, n_min,
1084 BIO_printf(bio_err, "No template, please set one up.\n");
1092 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1093 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1094 unsigned long chtype)
1096 int i, spec_char, plus_char;
1102 subj = X509_REQ_get_subject_name(req);
1104 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1106 v = sk_CONF_VALUE_value(dn_sk, i);
1110 * Skip past any leading X. X: X, etc to allow for multiple instances
1112 for (p = v->name; *p; p++) {
1113 #ifndef CHARSET_EBCDIC
1114 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1116 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1117 || (*p == os_toascii['.']));
1126 #ifndef CHARSET_EBCDIC
1127 plus_char = (*type == '+');
1129 plus_char = (*type == os_toascii['+']);
1136 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1137 (unsigned char *)v->value, -1, -1,
1143 if (!X509_NAME_entry_count(subj)) {
1144 BIO_printf(bio_err, "error, no objects specified in config file\n");
1148 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1149 v = sk_CONF_VALUE_value(attr_sk, i);
1150 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1151 (unsigned char *)v->value, -1))
1158 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1159 char *value, int nid, int n_min, int n_max,
1160 unsigned long chtype, int mval)
1166 BIO_printf(bio_err, "%s [%s]:", text, def);
1167 (void)BIO_flush(bio_err);
1168 if (value != NULL) {
1169 OPENSSL_strlcpy(buf, value, sizeof buf);
1170 OPENSSL_strlcat(buf, "\n", sizeof buf);
1171 BIO_printf(bio_err, "%s\n", value);
1175 if (!fgets(buf, sizeof buf, stdin))
1185 else if (buf[0] == '\n') {
1186 if ((def == NULL) || (def[0] == '\0'))
1188 OPENSSL_strlcpy(buf, def, sizeof buf);
1189 OPENSSL_strlcat(buf, "\n", sizeof buf);
1190 } else if ((buf[0] == '.') && (buf[1] == '\n'))
1194 if (buf[i - 1] != '\n') {
1195 BIO_printf(bio_err, "weird input :-(\n");
1199 #ifdef CHARSET_EBCDIC
1200 ebcdic2ascii(buf, buf, i);
1202 if (!req_check_len(i, n_min, n_max)) {
1208 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1209 (unsigned char *)buf, -1, -1, mval))
1216 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1217 char *value, int nid, int n_min,
1218 int n_max, unsigned long chtype)
1221 static char buf[1024];
1225 BIO_printf(bio_err, "%s [%s]:", text, def);
1226 (void)BIO_flush(bio_err);
1227 if (value != NULL) {
1228 OPENSSL_strlcpy(buf, value, sizeof buf);
1229 OPENSSL_strlcat(buf, "\n", sizeof buf);
1230 BIO_printf(bio_err, "%s\n", value);
1234 if (!fgets(buf, sizeof buf, stdin))
1244 else if (buf[0] == '\n') {
1245 if ((def == NULL) || (def[0] == '\0'))
1247 OPENSSL_strlcpy(buf, def, sizeof buf);
1248 OPENSSL_strlcat(buf, "\n", sizeof buf);
1249 } else if ((buf[0] == '.') && (buf[1] == '\n'))
1253 if (buf[i - 1] != '\n') {
1254 BIO_printf(bio_err, "weird input :-(\n");
1258 #ifdef CHARSET_EBCDIC
1259 ebcdic2ascii(buf, buf, i);
1261 if (!req_check_len(i, n_min, n_max)) {
1267 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1268 (unsigned char *)buf, -1)) {
1269 BIO_printf(bio_err, "Error adding attribute\n");
1270 ERR_print_errors(bio_err);
1279 static int req_check_len(int len, int n_min, int n_max)
1281 if ((n_min > 0) && (len < n_min)) {
1283 "string is too short, it needs to be at least %d bytes long\n",
1287 if ((n_max >= 0) && (len > n_max)) {
1289 "string is too long, it needs to be no more than %d bytes long\n",
1296 /* Check if the end of a string matches 'end' */
1297 static int check_end(const char *str, const char *end)
1305 tmp = str + slen - elen;
1306 return strcmp(tmp, end);
1309 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1310 int *pkey_type, long *pkeylen,
1311 char **palgnam, ENGINE *keygen_engine)
1313 EVP_PKEY_CTX *gctx = NULL;
1314 EVP_PKEY *param = NULL;
1317 const char *paramfile = NULL;
1320 *pkey_type = EVP_PKEY_RSA;
1322 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1323 *pkey_type = EVP_PKEY_RSA;
1324 keylen = atol(gstr);
1326 } else if (strncmp(gstr, "param:", 6) == 0)
1327 paramfile = gstr + 6;
1329 const char *p = strchr(gstr, ':');
1332 const EVP_PKEY_ASN1_METHOD *ameth;
1339 * The lookup of a the string will cover all engines so keep a note
1340 * of the implementation.
1343 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1346 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1350 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1351 #ifndef OPENSSL_NO_ENGINE
1352 ENGINE_finish(tmpeng);
1354 if (*pkey_type == EVP_PKEY_RSA) {
1356 keylen = atol(p + 1);
1365 pbio = BIO_new_file(paramfile, "r");
1367 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1370 param = PEM_read_bio_Parameters(pbio, NULL);
1374 (void)BIO_reset(pbio);
1375 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1377 param = X509_get_pubkey(x);
1385 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1388 if (*pkey_type == -1)
1389 *pkey_type = EVP_PKEY_id(param);
1390 else if (*pkey_type != EVP_PKEY_base_id(param)) {
1391 BIO_printf(bio_err, "Key Type does not match parameters\n");
1392 EVP_PKEY_free(param);
1398 const EVP_PKEY_ASN1_METHOD *ameth;
1401 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1403 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1406 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1407 *palgnam = OPENSSL_strdup(anam);
1408 #ifndef OPENSSL_NO_ENGINE
1409 ENGINE_finish(tmpeng);
1414 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1415 *pkeylen = EVP_PKEY_bits(param);
1416 EVP_PKEY_free(param);
1418 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1421 BIO_puts(bio_err, "Error allocating keygen context\n");
1422 ERR_print_errors(bio_err);
1426 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1427 BIO_puts(bio_err, "Error initializing keygen context\n");
1428 ERR_print_errors(bio_err);
1429 EVP_PKEY_CTX_free(gctx);
1432 #ifndef OPENSSL_NO_RSA
1433 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1434 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1435 BIO_puts(bio_err, "Error setting RSA keysize\n");
1436 ERR_print_errors(bio_err);
1437 EVP_PKEY_CTX_free(gctx);
1446 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1449 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1451 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1460 BIO_write(b, &c, 1);
1465 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1466 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1468 EVP_PKEY_CTX *pkctx = NULL;
1473 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1475 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1476 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1477 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1478 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1479 ERR_print_errors(bio_err);
1486 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1487 STACK_OF(OPENSSL_STRING) *sigopts)
1490 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1492 rv = do_sign_init(mctx, pkey, md, sigopts);
1494 rv = X509_sign_ctx(x, mctx);
1495 EVP_MD_CTX_free(mctx);
1496 return rv > 0 ? 1 : 0;
1499 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1500 STACK_OF(OPENSSL_STRING) *sigopts)
1503 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1504 rv = do_sign_init(mctx, pkey, md, sigopts);
1506 rv = X509_REQ_sign_ctx(x, mctx);
1507 EVP_MD_CTX_free(mctx);
1508 return rv > 0 ? 1 : 0;
1511 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1512 STACK_OF(OPENSSL_STRING) *sigopts)
1515 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1516 rv = do_sign_init(mctx, pkey, md, sigopts);
1518 rv = X509_CRL_sign_ctx(x, mctx);
1519 EVP_MD_CTX_free(mctx);
1520 return rv > 0 ? 1 : 0;