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
17 #include <openssl/bio.h>
18 #include <openssl/evp.h>
19 #include <openssl/conf.h>
20 #include <openssl/err.h>
21 #include <openssl/asn1.h>
22 #include <openssl/x509.h>
23 #include <openssl/x509v3.h>
24 #include <openssl/objects.h>
25 #include <openssl/pem.h>
26 #include <openssl/bn.h>
27 #include <openssl/bn.h>
28 #include <openssl/lhash.h>
29 #ifndef OPENSSL_NO_RSA
30 # include <openssl/rsa.h>
32 #ifndef OPENSSL_NO_DSA
33 # include <openssl/dsa.h>
38 #define BITS "default_bits"
39 #define KEYFILE "default_keyfile"
40 #define PROMPT "prompt"
41 #define DISTINGUISHED_NAME "distinguished_name"
42 #define ATTRIBUTES "attributes"
43 #define V3_EXTENSIONS "x509_extensions"
44 #define REQ_EXTENSIONS "req_extensions"
45 #define STRING_MASK "string_mask"
46 #define UTF8_IN "utf8"
48 #define DEFAULT_KEY_LENGTH 2048
49 #define MIN_KEY_LENGTH 512
51 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
52 int attribs, unsigned long chtype);
53 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
55 static int prompt_info(X509_REQ *req,
56 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
57 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
58 int attribs, unsigned long chtype);
59 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
60 STACK_OF(CONF_VALUE) *attr, int attribs,
61 unsigned long chtype);
62 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
63 char *value, int nid, int n_min, int n_max,
64 unsigned long chtype);
65 static int add_DN_object(X509_NAME *n, char *text, const char *def,
66 char *value, int nid, int n_min, int n_max,
67 unsigned long chtype, int mval);
68 static int genpkey_cb(EVP_PKEY_CTX *ctx);
69 static int build_data(char *text, const char *def,
70 char *value, int n_min, int n_max,
71 char *buf, const int buf_size,
72 const char *desc1, const char *desc2
74 static int req_check_len(int len, int n_min, int n_max);
75 static int check_end(const char *str, const char *end);
76 static int join(char buf[], size_t buf_size, const char *name,
77 const char *tail, const char *desc);
78 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
79 int *pkey_type, long *pkeylen,
80 char **palgnam, ENGINE *keygen_engine);
81 static CONF *req_conf = NULL;
82 static CONF *addext_conf = NULL;
85 typedef enum OPTION_choice {
86 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
87 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
88 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
89 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
90 OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
91 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
92 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
93 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
94 OPT_REQEXTS, OPT_PRECERT, OPT_MD,
98 const OPTIONS req_options[] = {
99 {"help", OPT_HELP, '-', "Display this summary"},
100 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
101 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
102 {"in", OPT_IN, '<', "Input file"},
103 {"out", OPT_OUT, '>', "Output file"},
104 {"key", OPT_KEY, 's', "Private key to use"},
105 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
106 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
107 {"new", OPT_NEW, '-', "New request"},
108 {"config", OPT_CONFIG, '<', "Request template file"},
109 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
110 {"passin", OPT_PASSIN, 's', "Private key password source"},
111 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
113 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
114 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
115 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
116 {"batch", OPT_BATCH, '-',
117 "Do not ask anything during request generation"},
118 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
119 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
120 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
121 {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
122 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
123 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
124 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
125 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
126 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
127 {"text", OPT_TEXT, '-', "Text form of request"},
128 {"x509", OPT_X509, '-',
129 "Output a x509 structure instead of a cert request"},
130 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
131 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
132 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
133 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
134 "Enable support for multivalued RDNs"},
135 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
136 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
137 {"addext", OPT_ADDEXT, 's',
138 "Additional cert extension key=value pair (may be given more than once)"},
139 {"extensions", OPT_EXTENSIONS, 's',
140 "Cert extension section (override value in config file)"},
141 {"reqexts", OPT_REQEXTS, 's',
142 "Request extension section (override value in config file)"},
143 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
144 {"", OPT_MD, '-', "Any supported digest"},
145 #ifndef OPENSSL_NO_ENGINE
146 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
147 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
148 "Specify engine to be used for key generation operations"},
155 * An LHASH of strings, where each string is an extension name.
157 static unsigned long ext_name_hash(const OPENSSL_STRING *a)
159 return OPENSSL_LH_strhash((const char *)a);
162 static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
164 return strcmp((const char *)a, (const char *)b);
167 static void exts_cleanup(OPENSSL_STRING *x)
169 OPENSSL_free((char *)x);
173 * Is the |kv| key already duplicated? This is remarkably tricky to get
174 * right. Return 0 if unique, -1 on runtime error; 1 if found or a syntax
177 static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
182 if (strchr(kv, '=') == NULL)
185 /* Skip leading whitespace, make a copy. */
186 while (*kv && isspace(*kv))
189 if ((kv = OPENSSL_strdup(kv)) == NULL)
192 /* Skip trailing space before the equal sign. */
193 for (p = strchr(kv, '='); p > kv; --p)
194 if (p[-1] != ' ' && p[-1] != '\t')
202 /* Finally have a clean "key"; see if it's there. */
203 if (lh_OPENSSL_STRING_retrieve(addexts, (OPENSSL_STRING*)kv) != NULL) {
204 BIO_printf(bio_err, "Extension \"%s\" repeated\n", kv);
209 /* Not found; add it. */
210 if (lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING*)kv) == NULL)
215 int req_main(int argc, char **argv)
217 ASN1_INTEGER *serial = NULL;
218 BIO *in = NULL, *out = NULL;
219 ENGINE *e = NULL, *gen_eng = NULL;
220 EVP_PKEY *pkey = NULL;
221 EVP_PKEY_CTX *genctx = NULL;
222 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
223 LHASH_OF(OPENSSL_STRING) *addexts = NULL;
225 X509_REQ *req = NULL;
226 const EVP_CIPHER *cipher = NULL;
227 const EVP_MD *md_alg = NULL, *digest = NULL;
228 BIO *addext_bio = NULL;
229 char *extensions = NULL, *infile = NULL;
230 char *outfile = NULL, *keyfile = NULL;
231 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
232 char *passin = NULL, *passout = NULL;
233 char *nofree_passin = NULL, *nofree_passout = NULL;
234 char *req_exts = NULL, *subj = NULL;
235 char *template = default_config_file, *keyout = NULL;
236 const char *keyalg = NULL;
238 int ret = 1, x509 = 0, days = 0, i = 0, newreq = 0, verbose = 0;
239 int pkey_type = -1, private = 0;
240 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
241 int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
242 int nodes = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
244 unsigned long chtype = MBSTRING_ASC, reqflag = 0;
246 #ifndef OPENSSL_NO_DES
247 cipher = EVP_des_ede3_cbc();
250 prog = opt_init(argc, argv, req_options);
251 while ((o = opt_next()) != OPT_EOF) {
256 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
259 opt_help(req_options);
263 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
267 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
271 e = setup_engine(opt_arg(), 0);
273 case OPT_KEYGEN_ENGINE:
274 #ifndef OPENSSL_NO_ENGINE
275 gen_eng = ENGINE_by_id(opt_arg());
276 if (gen_eng == NULL) {
277 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
292 template = opt_arg();
295 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
308 passargin = opt_arg();
311 passargout = opt_arg();
323 pkeyopts = sk_OPENSSL_STRING_new_null();
324 if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
329 sigopts = sk_OPENSSL_STRING_new_null();
330 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
355 chtype = MBSTRING_UTF8;
358 if (!set_nameopt(opt_arg()))
362 if (!set_cert_ex(&reqflag, opt_arg()))
372 days = atoi(opt_arg());
375 if (serial != NULL) {
376 BIO_printf(bio_err, "Serial number supplied twice\n");
379 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
389 case OPT_MULTIVALUE_RDN:
394 if (addexts == NULL) {
395 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
396 addext_bio = BIO_new(BIO_s_mem());
397 if (addexts == NULL || addext_bio == NULL)
400 i = duplicated(addexts, p);
403 if (i < 0 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
407 extensions = opt_arg();
410 req_exts = opt_arg();
413 newreq = precert = 1;
416 if (!opt_md(opt_unknown(), &md_alg))
422 argc = opt_num_rest();
427 BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
428 if (x509 && infile == NULL)
431 /* TODO: simplify this as pkey is still always NULL here */
432 private = newreq && (pkey == NULL) ? 1 : 0;
434 if (!app_passwd(passargin, passargout, &passin, &passout)) {
435 BIO_printf(bio_err, "Error getting passwords\n");
440 BIO_printf(bio_err, "Using configuration from %s\n", template);
441 req_conf = app_load_config(template);
445 "Using additional configuration from command line\n");
446 addext_conf = app_load_config_bio(addext_bio, NULL);
448 if (template != default_config_file && !app_load_modules(req_conf))
451 if (req_conf != NULL) {
452 p = NCONF_get_string(req_conf, NULL, "oid_file");
458 oid_bio = BIO_new_file(p, "r");
459 if (oid_bio == NULL) {
461 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
462 ERR_print_errors(bio_err);
465 OBJ_create_objects(oid_bio);
470 if (!add_oid_section(req_conf))
473 if (md_alg == NULL) {
474 p = NCONF_get_string(req_conf, SECTION, "default_md");
478 if (!opt_md(p, &md_alg))
484 if (extensions == NULL) {
485 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
486 if (extensions == NULL)
489 if (extensions != NULL) {
490 /* Check syntax of file */
492 X509V3_set_ctx_test(&ctx);
493 X509V3_set_nconf(&ctx, req_conf);
494 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
496 "Error Loading extension section %s\n", extensions);
500 if (addext_conf != NULL) {
501 /* Check syntax of command line extensions */
503 X509V3_set_ctx_test(&ctx);
504 X509V3_set_nconf(&ctx, addext_conf);
505 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
506 BIO_printf(bio_err, "Error Loading command line extensions\n");
511 if (passin == NULL) {
512 passin = nofree_passin =
513 NCONF_get_string(req_conf, SECTION, "input_password");
518 if (passout == NULL) {
519 passout = nofree_passout =
520 NCONF_get_string(req_conf, SECTION, "output_password");
525 p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
529 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
530 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
534 if (chtype != MBSTRING_UTF8) {
535 p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
538 else if (strcmp(p, "yes") == 0)
539 chtype = MBSTRING_UTF8;
542 if (req_exts == NULL) {
543 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
544 if (req_exts == NULL)
547 if (req_exts != NULL) {
548 /* Check syntax of file */
550 X509V3_set_ctx_test(&ctx);
551 X509V3_set_nconf(&ctx, req_conf);
552 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
554 "Error Loading request extension section %s\n",
560 if (keyfile != NULL) {
561 pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
563 /* load_key() has already printed an appropriate message */
566 app_RAND_load_conf(req_conf, SECTION);
570 if (newreq && (pkey == NULL)) {
571 app_RAND_load_conf(req_conf, SECTION);
573 if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
574 newkey = DEFAULT_KEY_LENGTH;
577 if (keyalg != NULL) {
578 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
579 &keyalgstr, gen_eng);
584 if (newkey < MIN_KEY_LENGTH
585 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
586 BIO_printf(bio_err, "private key length is too short,\n");
587 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
588 MIN_KEY_LENGTH, newkey);
592 if (pkey_type == EVP_PKEY_RSA && newkey > OPENSSL_RSA_MAX_MODULUS_BITS)
594 "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
595 " Your key size is %ld! Larger key size may behave not as expected.\n",
596 OPENSSL_RSA_MAX_MODULUS_BITS, newkey);
598 #ifndef OPENSSL_NO_DSA
599 if (pkey_type == EVP_PKEY_DSA && newkey > OPENSSL_DSA_MAX_MODULUS_BITS)
601 "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
602 " Your key size is %ld! Larger key size may behave not as expected.\n",
603 OPENSSL_DSA_MAX_MODULUS_BITS, newkey);
606 if (genctx == NULL) {
607 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
608 &keyalgstr, gen_eng);
613 if (pkeyopts != NULL) {
615 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
616 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
617 if (pkey_ctrl_string(genctx, genopt) <= 0) {
618 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
619 ERR_print_errors(bio_err);
625 if (pkey_type == EVP_PKEY_EC) {
626 BIO_printf(bio_err, "Generating an EC private key\n");
628 BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
632 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
633 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
635 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
636 BIO_puts(bio_err, "Error Generating Key\n");
640 EVP_PKEY_CTX_free(genctx);
643 if (keyout == NULL) {
644 keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
650 BIO_printf(bio_err, "writing new private key to stdout\n");
652 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
653 out = bio_open_owner(keyout, outformat, private);
657 p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
660 p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
664 if ((p != NULL) && (strcmp(p, "no") == 0))
672 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
673 NULL, 0, NULL, passout)) {
674 if ((ERR_GET_REASON(ERR_peek_error()) ==
675 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
684 BIO_printf(bio_err, "-----\n");
688 in = bio_open_default(infile, 'r', informat);
692 if (informat == FORMAT_ASN1)
693 req = d2i_X509_REQ_bio(in, NULL);
695 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
697 BIO_printf(bio_err, "unable to load X509 request\n");
702 if (newreq || x509) {
704 BIO_printf(bio_err, "you need to specify a private key\n");
709 req = X509_REQ_new();
714 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
715 subj = NULL; /* done processing '-subj' option */
717 BIO_printf(bio_err, "problems making Certificate Request\n");
724 if ((x509ss = X509_new()) == NULL)
727 /* Set version to V3 */
728 if ((extensions != NULL || addext_conf != NULL)
729 && !X509_set_version(x509ss, 2))
731 if (serial != NULL) {
732 if (!X509_set_serialNumber(x509ss, serial))
735 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
739 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
742 /* set default days if it's not specified */
745 if (!set_cert_times(x509ss, NULL, NULL, days))
747 if (!X509_set_subject_name
748 (x509ss, X509_REQ_get_subject_name(req)))
750 tmppkey = X509_REQ_get0_pubkey(req);
751 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
754 /* Set up V3 context struct */
756 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
757 X509V3_set_nconf(&ext_ctx, req_conf);
760 if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
761 &ext_ctx, extensions,
763 BIO_printf(bio_err, "Error Loading extension section %s\n",
767 if (addext_conf != NULL
768 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
770 BIO_printf(bio_err, "Error Loading command line extensions\n");
774 /* If a pre-cert was requested, we need to add a poison extension */
776 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
778 BIO_printf(bio_err, "Error adding poison extension\n");
783 i = do_X509_sign(x509ss, pkey, digest, sigopts);
785 ERR_print_errors(bio_err);
791 /* Set up V3 context struct */
793 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
794 X509V3_set_nconf(&ext_ctx, req_conf);
798 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
800 BIO_printf(bio_err, "Error Loading extension section %s\n",
804 if (addext_conf != NULL
805 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
807 BIO_printf(bio_err, "Error Loading command line extensions\n");
810 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
812 ERR_print_errors(bio_err);
819 BIO_printf(bio_err, "Cannot modify certificate subject\n");
825 BIO_printf(bio_err, "Modifying Request's Subject\n");
826 print_name(bio_err, "old subject=",
827 X509_REQ_get_subject_name(req), get_nameopt());
830 if (build_subject(req, subj, chtype, multirdn) == 0) {
831 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
837 print_name(bio_err, "new subject=",
838 X509_REQ_get_subject_name(req), get_nameopt());
842 if (verify && !x509) {
843 EVP_PKEY *tpubkey = pkey;
845 if (tpubkey == NULL) {
846 tpubkey = X509_REQ_get0_pubkey(req);
851 i = X509_REQ_verify(req, tpubkey);
856 BIO_printf(bio_err, "verify failure\n");
857 ERR_print_errors(bio_err);
858 } else { /* if (i > 0) */
859 BIO_printf(bio_err, "verify OK\n");
863 if (noout && !text && !modulus && !subject && !pubkey) {
868 out = bio_open_default(outfile,
869 keyout != NULL && outfile != NULL &&
870 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
876 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
878 if (tpubkey == NULL) {
879 BIO_printf(bio_err, "Error getting public key\n");
880 ERR_print_errors(bio_err);
883 PEM_write_bio_PUBKEY(out, tpubkey);
888 X509_print_ex(out, x509ss, get_nameopt(), reqflag);
890 X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
895 print_name(out, "subject=", X509_get_subject_name(x509ss),
898 print_name(out, "subject=", X509_REQ_get_subject_name(req),
906 tpubkey = X509_get0_pubkey(x509ss);
908 tpubkey = X509_REQ_get0_pubkey(req);
909 if (tpubkey == NULL) {
910 fprintf(stdout, "Modulus=unavailable\n");
913 fprintf(stdout, "Modulus=");
914 #ifndef OPENSSL_NO_RSA
915 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
917 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
921 fprintf(stdout, "Wrong Algorithm type");
922 fprintf(stdout, "\n");
925 if (!noout && !x509) {
926 if (outformat == FORMAT_ASN1)
927 i = i2d_X509_REQ_bio(out, req);
929 i = PEM_write_bio_X509_REQ_NEW(out, req);
931 i = PEM_write_bio_X509_REQ(out, req);
933 BIO_printf(bio_err, "unable to write X509 request\n");
937 if (!noout && x509 && (x509ss != NULL)) {
938 if (outformat == FORMAT_ASN1)
939 i = i2d_X509_bio(out, x509ss);
941 i = PEM_write_bio_X509(out, x509ss);
943 BIO_printf(bio_err, "unable to write X509 certificate\n");
950 ERR_print_errors(bio_err);
952 NCONF_free(req_conf);
953 BIO_free(addext_bio);
957 EVP_PKEY_CTX_free(genctx);
958 sk_OPENSSL_STRING_free(pkeyopts);
959 sk_OPENSSL_STRING_free(sigopts);
960 lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
961 lh_OPENSSL_STRING_free(addexts);
962 #ifndef OPENSSL_NO_ENGINE
963 ENGINE_free(gen_eng);
965 OPENSSL_free(keyalgstr);
968 ASN1_INTEGER_free(serial);
970 if (passin != nofree_passin)
971 OPENSSL_free(passin);
972 if (passout != nofree_passout)
973 OPENSSL_free(passout);
977 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
978 int attribs, unsigned long chtype)
982 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
983 char *tmp, *dn_sect, *attr_sect;
985 tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
988 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
991 dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
992 if (dn_sect == NULL) {
993 BIO_printf(bio_err, "unable to find '%s' in config\n",
997 dn_sk = NCONF_get_section(req_conf, dn_sect);
999 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
1003 attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
1004 if (attr_sect == NULL) {
1008 attr_sk = NCONF_get_section(req_conf, attr_sect);
1009 if (attr_sk == NULL) {
1010 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
1015 /* setup version number */
1016 if (!X509_REQ_set_version(req, 0L))
1017 goto err; /* version 1 */
1020 i = build_subject(req, subj, chtype, multirdn);
1022 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1024 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1029 if (!X509_REQ_set_pubkey(req, pkey))
1038 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1039 * where characters may be escaped by \
1041 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
1046 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
1049 if (!X509_REQ_set_subject_name(req, n)) {
1057 static int prompt_info(X509_REQ *req,
1058 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1059 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1060 int attribs, unsigned long chtype)
1071 subj = X509_REQ_get_subject_name(req);
1075 "You are about to be asked to enter information that will be incorporated\n");
1076 BIO_printf(bio_err, "into your certificate request.\n");
1078 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1080 "There are quite a few fields but you can leave some blank\n");
1082 "For some fields there will be a default value,\n");
1084 "If you enter '.', the field will be left blank.\n");
1085 BIO_printf(bio_err, "-----\n");
1088 if (sk_CONF_VALUE_num(dn_sk)) {
1093 if (sk_CONF_VALUE_num(dn_sk) <= i)
1096 v = sk_CONF_VALUE_value(dn_sk, i);
1099 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1100 !check_end(type, "_default") || !check_end(type, "_value"))
1103 * Skip past any leading X. X: X, etc to allow for multiple
1106 for (p = v->name; *p; p++)
1107 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1119 /* If OBJ not recognised ignore it */
1120 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1122 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1124 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1129 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1131 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1136 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1138 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1144 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1146 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1151 if (!add_DN_object(subj, v->value, def, value, nid,
1152 n_min, n_max, chtype, mval))
1155 if (X509_NAME_entry_count(subj) == 0) {
1157 "error, no objects specified in config file\n");
1162 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1165 "\nPlease enter the following 'extra' attributes\n");
1167 "to be sent with your certificate request\n");
1174 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1177 v = sk_CONF_VALUE_value(attr_sk, i);
1179 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1182 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1184 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1190 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1192 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1198 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1200 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1205 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1207 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1212 if (!add_attribute_object(req,
1213 v->value, def, value, nid, n_min,
1219 BIO_printf(bio_err, "No template, please set one up.\n");
1227 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1228 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1229 unsigned long chtype)
1231 int i, spec_char, plus_char;
1237 subj = X509_REQ_get_subject_name(req);
1239 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1241 v = sk_CONF_VALUE_value(dn_sk, i);
1245 * Skip past any leading X. X: X, etc to allow for multiple instances
1247 for (p = v->name; *p; p++) {
1248 #ifndef CHARSET_EBCDIC
1249 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1251 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1252 || (*p == os_toascii['.']));
1261 #ifndef CHARSET_EBCDIC
1262 plus_char = (*type == '+');
1264 plus_char = (*type == os_toascii['+']);
1272 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1273 (unsigned char *)v->value, -1, -1,
1279 if (!X509_NAME_entry_count(subj)) {
1280 BIO_printf(bio_err, "error, no objects specified in config file\n");
1284 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1285 v = sk_CONF_VALUE_value(attr_sk, i);
1286 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1287 (unsigned char *)v->value, -1))
1294 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1295 char *value, int nid, int n_min, int n_max,
1296 unsigned long chtype, int mval)
1301 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1302 "DN value", "DN default");
1303 if ((ret == 0) || (ret == 1))
1307 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1308 (unsigned char *)buf, -1, -1, mval))
1314 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1315 char *value, int nid, int n_min,
1316 int n_max, unsigned long chtype)
1321 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1322 "Attribute value", "Attribute default");
1323 if ((ret == 0) || (ret == 1))
1327 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1328 (unsigned char *)buf, -1)) {
1329 BIO_printf(bio_err, "Error adding attribute\n");
1330 ERR_print_errors(bio_err);
1338 static int build_data(char *text, const char *def,
1339 char *value, int n_min, int n_max,
1340 char *buf, const int buf_size,
1341 const char *desc1, const char *desc2
1347 BIO_printf(bio_err, "%s [%s]:", text, def);
1348 (void)BIO_flush(bio_err);
1349 if (value != NULL) {
1350 if (!join(buf, buf_size, value, "\n", desc1))
1352 BIO_printf(bio_err, "%s\n", value);
1356 if (!fgets(buf, buf_size, stdin))
1366 if (buf[0] == '\n') {
1367 if ((def == NULL) || (def[0] == '\0'))
1369 if (!join(buf, buf_size, def, "\n", desc2))
1371 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1376 if (buf[i - 1] != '\n') {
1377 BIO_printf(bio_err, "weird input :-(\n");
1381 #ifdef CHARSET_EBCDIC
1382 ebcdic2ascii(buf, buf, i);
1384 if (!req_check_len(i, n_min, n_max)) {
1392 static int req_check_len(int len, int n_min, int n_max)
1394 if ((n_min > 0) && (len < n_min)) {
1396 "string is too short, it needs to be at least %d bytes long\n",
1400 if ((n_max >= 0) && (len > n_max)) {
1402 "string is too long, it needs to be no more than %d bytes long\n",
1409 /* Check if the end of a string matches 'end' */
1410 static int check_end(const char *str, const char *end)
1419 tmp = str + slen - elen;
1420 return strcmp(tmp, end);
1424 * Merge the two strings together into the result buffer checking for
1425 * overflow and producing an error message if there is.
1427 static int join(char buf[], size_t buf_size, const char *name,
1428 const char *tail, const char *desc)
1430 const size_t name_len = strlen(name), tail_len = strlen(tail);
1432 if (name_len + tail_len + 1 > buf_size) {
1433 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1436 memcpy(buf, name, name_len);
1437 memcpy(buf + name_len, tail, tail_len + 1);
1441 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1442 int *pkey_type, long *pkeylen,
1443 char **palgnam, ENGINE *keygen_engine)
1445 EVP_PKEY_CTX *gctx = NULL;
1446 EVP_PKEY *param = NULL;
1449 const char *paramfile = NULL;
1452 *pkey_type = EVP_PKEY_RSA;
1454 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1455 *pkey_type = EVP_PKEY_RSA;
1456 keylen = atol(gstr);
1458 } else if (strncmp(gstr, "param:", 6) == 0) {
1459 paramfile = gstr + 6;
1461 const char *p = strchr(gstr, ':');
1464 const EVP_PKEY_ASN1_METHOD *ameth;
1471 * The lookup of a the string will cover all engines so keep a note
1472 * of the implementation.
1475 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1477 if (ameth == NULL) {
1478 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1482 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1483 #ifndef OPENSSL_NO_ENGINE
1484 ENGINE_finish(tmpeng);
1486 if (*pkey_type == EVP_PKEY_RSA) {
1488 keylen = atol(p + 1);
1493 } else if (p != NULL) {
1498 if (paramfile != NULL) {
1499 pbio = BIO_new_file(paramfile, "r");
1501 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1504 param = PEM_read_bio_Parameters(pbio, NULL);
1506 if (param == NULL) {
1509 (void)BIO_reset(pbio);
1510 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1512 param = X509_get_pubkey(x);
1519 if (param == NULL) {
1520 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1523 if (*pkey_type == -1) {
1524 *pkey_type = EVP_PKEY_id(param);
1525 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1526 BIO_printf(bio_err, "Key Type does not match parameters\n");
1527 EVP_PKEY_free(param);
1532 if (palgnam != NULL) {
1533 const EVP_PKEY_ASN1_METHOD *ameth;
1537 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1538 if (ameth == NULL) {
1539 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1542 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1543 *palgnam = OPENSSL_strdup(anam);
1544 #ifndef OPENSSL_NO_ENGINE
1545 ENGINE_finish(tmpeng);
1549 if (param != NULL) {
1550 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1551 *pkeylen = EVP_PKEY_bits(param);
1552 EVP_PKEY_free(param);
1554 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1558 BIO_puts(bio_err, "Error allocating keygen context\n");
1559 ERR_print_errors(bio_err);
1563 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1564 BIO_puts(bio_err, "Error initializing keygen context\n");
1565 ERR_print_errors(bio_err);
1566 EVP_PKEY_CTX_free(gctx);
1569 #ifndef OPENSSL_NO_RSA
1570 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1571 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1572 BIO_puts(bio_err, "Error setting RSA keysize\n");
1573 ERR_print_errors(bio_err);
1574 EVP_PKEY_CTX_free(gctx);
1583 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1586 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1588 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1597 BIO_write(b, &c, 1);
1602 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1603 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1605 EVP_PKEY_CTX *pkctx = NULL;
1610 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1612 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1613 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1614 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1615 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1616 ERR_print_errors(bio_err);
1623 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1624 STACK_OF(OPENSSL_STRING) *sigopts)
1627 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1629 rv = do_sign_init(mctx, pkey, md, sigopts);
1631 rv = X509_sign_ctx(x, mctx);
1632 EVP_MD_CTX_free(mctx);
1633 return rv > 0 ? 1 : 0;
1636 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1637 STACK_OF(OPENSSL_STRING) *sigopts)
1640 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1641 rv = do_sign_init(mctx, pkey, md, sigopts);
1643 rv = X509_REQ_sign_ctx(x, mctx);
1644 EVP_MD_CTX_free(mctx);
1645 return rv > 0 ? 1 : 0;
1648 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1649 STACK_OF(OPENSSL_STRING) *sigopts)
1652 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1653 rv = do_sign_init(mctx, pkey, md, sigopts);
1655 rv = X509_CRL_sign_ctx(x, mctx);
1656 EVP_MD_CTX_free(mctx);
1657 return rv > 0 ? 1 : 0;