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 build_data(char *text, const char *def,
67 char *value, int n_min, int n_max,
68 char *buf, const int buf_size,
69 const char *desc1, const char *desc2
71 static int req_check_len(int len, int n_min, int n_max);
72 static int check_end(const char *str, const char *end);
73 static int join(char buf[], size_t buf_size, const char *name,
74 const char *tail, const char *desc);
75 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
76 int *pkey_type, long *pkeylen,
77 char **palgnam, ENGINE *keygen_engine);
78 static CONF *req_conf = NULL;
79 static CONF *addext_conf = NULL;
82 typedef enum OPTION_choice {
83 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
84 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
85 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
86 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
87 OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
88 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
89 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
90 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
91 OPT_REQEXTS, OPT_PRECERT, OPT_MD,
95 const OPTIONS req_options[] = {
96 {"help", OPT_HELP, '-', "Display this summary"},
97 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
98 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
99 {"in", OPT_IN, '<', "Input file"},
100 {"out", OPT_OUT, '>', "Output file"},
101 {"key", OPT_KEY, 's', "Private key to use"},
102 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
103 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
104 {"new", OPT_NEW, '-', "New request"},
105 {"config", OPT_CONFIG, '<', "Request template file"},
106 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
107 {"passin", OPT_PASSIN, 's', "Private key password source"},
108 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
110 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
111 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
112 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
113 {"batch", OPT_BATCH, '-',
114 "Do not ask anything during request generation"},
115 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
116 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
117 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
118 {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
119 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
120 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
121 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
122 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
123 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
124 {"text", OPT_TEXT, '-', "Text form of request"},
125 {"x509", OPT_X509, '-',
126 "Output a x509 structure instead of a cert request"},
127 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
128 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
129 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
130 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
131 "Enable support for multivalued RDNs"},
132 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
133 {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"},
134 {"addext", OPT_ADDEXT, 's',
135 "Additional cert extension key=value pair (may be given more than once)"},
136 {"extensions", OPT_EXTENSIONS, 's',
137 "Cert extension section (override value in config file)"},
138 {"reqexts", OPT_REQEXTS, 's',
139 "Request extension section (override value in config file)"},
140 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
141 {"", OPT_MD, '-', "Any supported digest"},
142 #ifndef OPENSSL_NO_ENGINE
143 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
144 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
145 "Specify engine to be used for key generation operations"},
150 int req_main(int argc, char **argv)
152 ASN1_INTEGER *serial = NULL;
153 BIO *in = NULL, *out = NULL;
154 ENGINE *e = NULL, *gen_eng = NULL;
155 EVP_PKEY *pkey = NULL;
156 EVP_PKEY_CTX *genctx = NULL;
157 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
159 X509_REQ *req = NULL;
160 const EVP_CIPHER *cipher = NULL;
161 const EVP_MD *md_alg = NULL, *digest = NULL;
162 BIO *addext_bio = NULL;
163 char *extensions = NULL, *infile = NULL;
164 char *outfile = NULL, *keyfile = NULL;
165 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
166 char *passin = NULL, *passout = NULL;
167 char *nofree_passin = NULL, *nofree_passout = NULL;
168 char *req_exts = NULL, *subj = NULL;
169 char *template = default_config_file, *keyout = NULL;
170 const char *keyalg = NULL;
172 int ret = 1, x509 = 0, days = 0, i = 0, newreq = 0, verbose = 0;
173 int pkey_type = -1, private = 0;
174 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
175 int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
176 int nodes = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
178 unsigned long chtype = MBSTRING_ASC, reqflag = 0;
180 #ifndef OPENSSL_NO_DES
181 cipher = EVP_des_ede3_cbc();
184 prog = opt_init(argc, argv, req_options);
185 while ((o = opt_next()) != OPT_EOF) {
190 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
193 opt_help(req_options);
197 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
201 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
205 e = setup_engine(opt_arg(), 0);
207 case OPT_KEYGEN_ENGINE:
208 #ifndef OPENSSL_NO_ENGINE
209 gen_eng = ENGINE_by_id(opt_arg());
210 if (gen_eng == NULL) {
211 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
226 template = opt_arg();
229 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
242 passargin = opt_arg();
245 passargout = opt_arg();
257 pkeyopts = sk_OPENSSL_STRING_new_null();
258 if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
263 sigopts = sk_OPENSSL_STRING_new_null();
264 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
289 chtype = MBSTRING_UTF8;
292 if (!set_nameopt(opt_arg()))
296 if (!set_cert_ex(&reqflag, opt_arg()))
306 days = atoi(opt_arg());
309 if (serial != NULL) {
310 BIO_printf(bio_err, "Serial number supplied twice\n");
313 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
323 case OPT_MULTIVALUE_RDN:
327 if (addext_bio == NULL) {
328 addext_bio = BIO_new(BIO_s_mem());
330 if (addext_bio == NULL
331 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
335 extensions = opt_arg();
338 req_exts = opt_arg();
341 newreq = precert = 1;
344 if (!opt_md(opt_unknown(), &md_alg))
350 argc = opt_num_rest();
355 BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
356 if (x509 && infile == NULL)
359 /* TODO: simplify this as pkey is still always NULL here */
360 private = newreq && (pkey == NULL) ? 1 : 0;
362 if (!app_passwd(passargin, passargout, &passin, &passout)) {
363 BIO_printf(bio_err, "Error getting passwords\n");
368 BIO_printf(bio_err, "Using configuration from %s\n", template);
369 req_conf = app_load_config(template);
373 "Using additional configuration from command line\n");
374 addext_conf = app_load_config_bio(addext_bio, NULL);
376 if (template != default_config_file && !app_load_modules(req_conf))
379 if (req_conf != NULL) {
380 p = NCONF_get_string(req_conf, NULL, "oid_file");
386 oid_bio = BIO_new_file(p, "r");
387 if (oid_bio == NULL) {
389 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
390 ERR_print_errors(bio_err);
393 OBJ_create_objects(oid_bio);
398 if (!add_oid_section(req_conf))
401 if (md_alg == NULL) {
402 p = NCONF_get_string(req_conf, SECTION, "default_md");
406 if (!opt_md(p, &md_alg))
412 if (extensions == NULL) {
413 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
414 if (extensions == NULL)
417 if (extensions != NULL) {
418 /* Check syntax of file */
420 X509V3_set_ctx_test(&ctx);
421 X509V3_set_nconf(&ctx, req_conf);
422 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
424 "Error Loading extension section %s\n", extensions);
428 if (addext_conf != NULL) {
429 /* Check syntax of command line extensions */
431 X509V3_set_ctx_test(&ctx);
432 X509V3_set_nconf(&ctx, addext_conf);
433 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
434 BIO_printf(bio_err, "Error Loading command line extensions\n");
439 if (passin == NULL) {
440 passin = nofree_passin =
441 NCONF_get_string(req_conf, SECTION, "input_password");
446 if (passout == NULL) {
447 passout = nofree_passout =
448 NCONF_get_string(req_conf, SECTION, "output_password");
453 p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
457 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
458 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
462 if (chtype != MBSTRING_UTF8) {
463 p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
466 else if (strcmp(p, "yes") == 0)
467 chtype = MBSTRING_UTF8;
470 if (req_exts == NULL) {
471 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
472 if (req_exts == NULL)
475 if (req_exts != NULL) {
476 /* Check syntax of file */
478 X509V3_set_ctx_test(&ctx);
479 X509V3_set_nconf(&ctx, req_conf);
480 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
482 "Error Loading request extension section %s\n",
488 if (keyfile != NULL) {
489 pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
491 /* load_key() has already printed an appropriate message */
494 app_RAND_load_conf(req_conf, SECTION);
498 if (newreq && (pkey == NULL)) {
499 app_RAND_load_conf(req_conf, SECTION);
501 if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
502 newkey = DEFAULT_KEY_LENGTH;
505 if (keyalg != NULL) {
506 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
507 &keyalgstr, gen_eng);
512 if (newkey < MIN_KEY_LENGTH
513 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
514 BIO_printf(bio_err, "private key length is too short,\n");
515 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
516 MIN_KEY_LENGTH, newkey);
520 if (pkey_type == EVP_PKEY_RSA && newkey > OPENSSL_RSA_MAX_MODULUS_BITS)
522 "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
523 " Your key size is %ld! Larger key size may behave not as expected.\n",
524 OPENSSL_RSA_MAX_MODULUS_BITS, newkey);
526 #ifndef OPENSSL_NO_DSA
527 if (pkey_type == EVP_PKEY_DSA && newkey > OPENSSL_DSA_MAX_MODULUS_BITS)
529 "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
530 " Your key size is %ld! Larger key size may behave not as expected.\n",
531 OPENSSL_DSA_MAX_MODULUS_BITS, newkey);
534 if (genctx == NULL) {
535 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
536 &keyalgstr, gen_eng);
541 if (pkeyopts != NULL) {
543 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
544 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
545 if (pkey_ctrl_string(genctx, genopt) <= 0) {
546 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
547 ERR_print_errors(bio_err);
553 if (pkey_type == EVP_PKEY_EC) {
554 BIO_printf(bio_err, "Generating an EC private key\n");
556 BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
560 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
561 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
563 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
564 BIO_puts(bio_err, "Error Generating Key\n");
568 EVP_PKEY_CTX_free(genctx);
571 if (keyout == NULL) {
572 keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
578 BIO_printf(bio_err, "writing new private key to stdout\n");
580 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
581 out = bio_open_owner(keyout, outformat, private);
585 p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
588 p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
592 if ((p != NULL) && (strcmp(p, "no") == 0))
600 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
601 NULL, 0, NULL, passout)) {
602 if ((ERR_GET_REASON(ERR_peek_error()) ==
603 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
612 BIO_printf(bio_err, "-----\n");
616 in = bio_open_default(infile, 'r', informat);
620 if (informat == FORMAT_ASN1)
621 req = d2i_X509_REQ_bio(in, NULL);
623 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
625 BIO_printf(bio_err, "unable to load X509 request\n");
630 if (newreq || x509) {
632 BIO_printf(bio_err, "you need to specify a private key\n");
637 req = X509_REQ_new();
642 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
643 subj = NULL; /* done processing '-subj' option */
645 BIO_printf(bio_err, "problems making Certificate Request\n");
652 if ((x509ss = X509_new()) == NULL)
655 /* Set version to V3 */
656 if ((extensions != NULL || addext_conf != NULL)
657 && !X509_set_version(x509ss, 2))
659 if (serial != NULL) {
660 if (!X509_set_serialNumber(x509ss, serial))
663 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
667 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
670 /* set default days if it's not specified */
673 if (!set_cert_times(x509ss, NULL, NULL, days))
675 if (!X509_set_subject_name
676 (x509ss, X509_REQ_get_subject_name(req)))
678 tmppkey = X509_REQ_get0_pubkey(req);
679 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
682 /* Set up V3 context struct */
684 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
685 X509V3_set_nconf(&ext_ctx, req_conf);
688 if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
689 &ext_ctx, extensions,
691 BIO_printf(bio_err, "Error Loading extension section %s\n",
695 if (addext_conf != NULL
696 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
698 BIO_printf(bio_err, "Error Loading command line extensions\n");
702 /* If a pre-cert was requested, we need to add a poison extension */
704 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
706 BIO_printf(bio_err, "Error adding poison extension\n");
711 i = do_X509_sign(x509ss, pkey, digest, sigopts);
713 ERR_print_errors(bio_err);
719 /* Set up V3 context struct */
721 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
722 X509V3_set_nconf(&ext_ctx, req_conf);
726 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
728 BIO_printf(bio_err, "Error Loading extension section %s\n",
732 if (addext_conf != NULL
733 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
735 BIO_printf(bio_err, "Error Loading command line extensions\n");
738 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
740 ERR_print_errors(bio_err);
747 BIO_printf(bio_err, "Cannot modify certificate subject\n");
753 BIO_printf(bio_err, "Modifying Request's Subject\n");
754 print_name(bio_err, "old subject=",
755 X509_REQ_get_subject_name(req), get_nameopt());
758 if (build_subject(req, subj, chtype, multirdn) == 0) {
759 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
765 print_name(bio_err, "new subject=",
766 X509_REQ_get_subject_name(req), get_nameopt());
770 if (verify && !x509) {
771 EVP_PKEY *tpubkey = pkey;
773 if (tpubkey == NULL) {
774 tpubkey = X509_REQ_get0_pubkey(req);
779 i = X509_REQ_verify(req, tpubkey);
784 BIO_printf(bio_err, "verify failure\n");
785 ERR_print_errors(bio_err);
786 } else { /* if (i > 0) */
787 BIO_printf(bio_err, "verify OK\n");
791 if (noout && !text && !modulus && !subject && !pubkey) {
796 out = bio_open_default(outfile,
797 keyout != NULL && outfile != NULL &&
798 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
804 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
806 if (tpubkey == NULL) {
807 BIO_printf(bio_err, "Error getting public key\n");
808 ERR_print_errors(bio_err);
811 PEM_write_bio_PUBKEY(out, tpubkey);
816 X509_print_ex(out, x509ss, get_nameopt(), reqflag);
818 X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
823 print_name(out, "subject=", X509_get_subject_name(x509ss),
826 print_name(out, "subject=", X509_REQ_get_subject_name(req),
834 tpubkey = X509_get0_pubkey(x509ss);
836 tpubkey = X509_REQ_get0_pubkey(req);
837 if (tpubkey == NULL) {
838 fprintf(stdout, "Modulus=unavailable\n");
841 fprintf(stdout, "Modulus=");
842 #ifndef OPENSSL_NO_RSA
843 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
845 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
849 fprintf(stdout, "Wrong Algorithm type");
850 fprintf(stdout, "\n");
853 if (!noout && !x509) {
854 if (outformat == FORMAT_ASN1)
855 i = i2d_X509_REQ_bio(out, req);
857 i = PEM_write_bio_X509_REQ_NEW(out, req);
859 i = PEM_write_bio_X509_REQ(out, req);
861 BIO_printf(bio_err, "unable to write X509 request\n");
865 if (!noout && x509 && (x509ss != NULL)) {
866 if (outformat == FORMAT_ASN1)
867 i = i2d_X509_bio(out, x509ss);
869 i = PEM_write_bio_X509(out, x509ss);
871 BIO_printf(bio_err, "unable to write X509 certificate\n");
878 ERR_print_errors(bio_err);
880 NCONF_free(req_conf);
881 BIO_free(addext_bio);
885 EVP_PKEY_CTX_free(genctx);
886 sk_OPENSSL_STRING_free(pkeyopts);
887 sk_OPENSSL_STRING_free(sigopts);
888 #ifndef OPENSSL_NO_ENGINE
889 ENGINE_free(gen_eng);
891 OPENSSL_free(keyalgstr);
894 ASN1_INTEGER_free(serial);
896 if (passin != nofree_passin)
897 OPENSSL_free(passin);
898 if (passout != nofree_passout)
899 OPENSSL_free(passout);
903 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
904 int attribs, unsigned long chtype)
908 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
909 char *tmp, *dn_sect, *attr_sect;
911 tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
914 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
917 dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
918 if (dn_sect == NULL) {
919 BIO_printf(bio_err, "unable to find '%s' in config\n",
923 dn_sk = NCONF_get_section(req_conf, dn_sect);
925 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
929 attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
930 if (attr_sect == NULL) {
934 attr_sk = NCONF_get_section(req_conf, attr_sect);
935 if (attr_sk == NULL) {
936 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
941 /* setup version number */
942 if (!X509_REQ_set_version(req, 0L))
943 goto err; /* version 1 */
946 i = build_subject(req, subj, chtype, multirdn);
948 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
950 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
955 if (!X509_REQ_set_pubkey(req, pkey))
964 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
965 * where characters may be escaped by \
967 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
972 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
975 if (!X509_REQ_set_subject_name(req, n)) {
983 static int prompt_info(X509_REQ *req,
984 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
985 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
986 int attribs, unsigned long chtype)
997 subj = X509_REQ_get_subject_name(req);
1001 "You are about to be asked to enter information that will be incorporated\n");
1002 BIO_printf(bio_err, "into your certificate request.\n");
1004 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1006 "There are quite a few fields but you can leave some blank\n");
1008 "For some fields there will be a default value,\n");
1010 "If you enter '.', the field will be left blank.\n");
1011 BIO_printf(bio_err, "-----\n");
1014 if (sk_CONF_VALUE_num(dn_sk)) {
1019 if (sk_CONF_VALUE_num(dn_sk) <= i)
1022 v = sk_CONF_VALUE_value(dn_sk, i);
1025 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1026 !check_end(type, "_default") || !check_end(type, "_value"))
1029 * Skip past any leading X. X: X, etc to allow for multiple
1032 for (p = v->name; *p; p++)
1033 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1045 /* If OBJ not recognised ignore it */
1046 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1048 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1050 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1055 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1057 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1062 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1064 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1070 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1072 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1077 if (!add_DN_object(subj, v->value, def, value, nid,
1078 n_min, n_max, chtype, mval))
1081 if (X509_NAME_entry_count(subj) == 0) {
1083 "error, no objects specified in config file\n");
1088 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1091 "\nPlease enter the following 'extra' attributes\n");
1093 "to be sent with your certificate request\n");
1100 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1103 v = sk_CONF_VALUE_value(attr_sk, i);
1105 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1108 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1110 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1116 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1118 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1124 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1126 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1131 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1133 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1138 if (!add_attribute_object(req,
1139 v->value, def, value, nid, n_min,
1145 BIO_printf(bio_err, "No template, please set one up.\n");
1153 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1154 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1155 unsigned long chtype)
1157 int i, spec_char, plus_char;
1163 subj = X509_REQ_get_subject_name(req);
1165 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1167 v = sk_CONF_VALUE_value(dn_sk, i);
1171 * Skip past any leading X. X: X, etc to allow for multiple instances
1173 for (p = v->name; *p; p++) {
1174 #ifndef CHARSET_EBCDIC
1175 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1177 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1178 || (*p == os_toascii['.']));
1187 #ifndef CHARSET_EBCDIC
1188 plus_char = (*type == '+');
1190 plus_char = (*type == os_toascii['+']);
1198 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1199 (unsigned char *)v->value, -1, -1,
1205 if (!X509_NAME_entry_count(subj)) {
1206 BIO_printf(bio_err, "error, no objects specified in config file\n");
1210 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1211 v = sk_CONF_VALUE_value(attr_sk, i);
1212 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1213 (unsigned char *)v->value, -1))
1220 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1221 char *value, int nid, int n_min, int n_max,
1222 unsigned long chtype, int mval)
1227 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1228 "DN value", "DN default");
1229 if ((ret == 0) || (ret == 1))
1233 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1234 (unsigned char *)buf, -1, -1, mval))
1240 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1241 char *value, int nid, int n_min,
1242 int n_max, unsigned long chtype)
1247 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1248 "Attribute value", "Attribute default");
1249 if ((ret == 0) || (ret == 1))
1253 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1254 (unsigned char *)buf, -1)) {
1255 BIO_printf(bio_err, "Error adding attribute\n");
1256 ERR_print_errors(bio_err);
1264 static int build_data(char *text, const char *def,
1265 char *value, int n_min, int n_max,
1266 char *buf, const int buf_size,
1267 const char *desc1, const char *desc2
1273 BIO_printf(bio_err, "%s [%s]:", text, def);
1274 (void)BIO_flush(bio_err);
1275 if (value != NULL) {
1276 if (!join(buf, buf_size, value, "\n", desc1))
1278 BIO_printf(bio_err, "%s\n", value);
1282 if (!fgets(buf, buf_size, stdin))
1292 if (buf[0] == '\n') {
1293 if ((def == NULL) || (def[0] == '\0'))
1295 if (!join(buf, buf_size, def, "\n", desc2))
1297 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1302 if (buf[i - 1] != '\n') {
1303 BIO_printf(bio_err, "weird input :-(\n");
1307 #ifdef CHARSET_EBCDIC
1308 ebcdic2ascii(buf, buf, i);
1310 if (!req_check_len(i, n_min, n_max)) {
1318 static int req_check_len(int len, int n_min, int n_max)
1320 if ((n_min > 0) && (len < n_min)) {
1322 "string is too short, it needs to be at least %d bytes long\n",
1326 if ((n_max >= 0) && (len > n_max)) {
1328 "string is too long, it needs to be no more than %d bytes long\n",
1335 /* Check if the end of a string matches 'end' */
1336 static int check_end(const char *str, const char *end)
1345 tmp = str + slen - elen;
1346 return strcmp(tmp, end);
1350 * Merge the two strings together into the result buffer checking for
1351 * overflow and producing an error message if there is.
1353 static int join(char buf[], size_t buf_size, const char *name,
1354 const char *tail, const char *desc)
1356 const size_t name_len = strlen(name), tail_len = strlen(tail);
1358 if (name_len + tail_len + 1 > buf_size) {
1359 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1362 memcpy(buf, name, name_len);
1363 memcpy(buf + name_len, tail, tail_len + 1);
1367 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1368 int *pkey_type, long *pkeylen,
1369 char **palgnam, ENGINE *keygen_engine)
1371 EVP_PKEY_CTX *gctx = NULL;
1372 EVP_PKEY *param = NULL;
1375 const char *paramfile = NULL;
1378 *pkey_type = EVP_PKEY_RSA;
1380 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1381 *pkey_type = EVP_PKEY_RSA;
1382 keylen = atol(gstr);
1384 } else if (strncmp(gstr, "param:", 6) == 0) {
1385 paramfile = gstr + 6;
1387 const char *p = strchr(gstr, ':');
1390 const EVP_PKEY_ASN1_METHOD *ameth;
1397 * The lookup of a the string will cover all engines so keep a note
1398 * of the implementation.
1401 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1403 if (ameth == NULL) {
1404 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1408 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1409 #ifndef OPENSSL_NO_ENGINE
1410 ENGINE_finish(tmpeng);
1412 if (*pkey_type == EVP_PKEY_RSA) {
1414 keylen = atol(p + 1);
1419 } else if (p != NULL) {
1424 if (paramfile != NULL) {
1425 pbio = BIO_new_file(paramfile, "r");
1427 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1430 param = PEM_read_bio_Parameters(pbio, NULL);
1432 if (param == NULL) {
1435 (void)BIO_reset(pbio);
1436 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1438 param = X509_get_pubkey(x);
1445 if (param == NULL) {
1446 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1449 if (*pkey_type == -1) {
1450 *pkey_type = EVP_PKEY_id(param);
1451 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1452 BIO_printf(bio_err, "Key Type does not match parameters\n");
1453 EVP_PKEY_free(param);
1458 if (palgnam != NULL) {
1459 const EVP_PKEY_ASN1_METHOD *ameth;
1463 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1464 if (ameth == NULL) {
1465 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1468 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1469 *palgnam = OPENSSL_strdup(anam);
1470 #ifndef OPENSSL_NO_ENGINE
1471 ENGINE_finish(tmpeng);
1475 if (param != NULL) {
1476 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1477 *pkeylen = EVP_PKEY_bits(param);
1478 EVP_PKEY_free(param);
1480 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1484 BIO_puts(bio_err, "Error allocating keygen context\n");
1485 ERR_print_errors(bio_err);
1489 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1490 BIO_puts(bio_err, "Error initializing keygen context\n");
1491 ERR_print_errors(bio_err);
1492 EVP_PKEY_CTX_free(gctx);
1495 #ifndef OPENSSL_NO_RSA
1496 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1497 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1498 BIO_puts(bio_err, "Error setting RSA keysize\n");
1499 ERR_print_errors(bio_err);
1500 EVP_PKEY_CTX_free(gctx);
1509 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1512 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1514 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1523 BIO_write(b, &c, 1);
1528 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1529 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1531 EVP_PKEY_CTX *pkctx = NULL;
1536 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1538 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1539 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1540 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1541 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1542 ERR_print_errors(bio_err);
1549 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1550 STACK_OF(OPENSSL_STRING) *sigopts)
1553 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1555 rv = do_sign_init(mctx, pkey, md, sigopts);
1557 rv = X509_sign_ctx(x, mctx);
1558 EVP_MD_CTX_free(mctx);
1559 return rv > 0 ? 1 : 0;
1562 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1563 STACK_OF(OPENSSL_STRING) *sigopts)
1566 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1567 rv = do_sign_init(mctx, pkey, md, sigopts);
1569 rv = X509_REQ_sign_ctx(x, mctx);
1570 EVP_MD_CTX_free(mctx);
1571 return rv > 0 ? 1 : 0;
1574 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1575 STACK_OF(OPENSSL_STRING) *sigopts)
1578 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1579 rv = do_sign_init(mctx, pkey, md, sigopts);
1581 rv = X509_CRL_sign_ctx(x, mctx);
1582 EVP_MD_CTX_free(mctx);
1583 return rv > 0 ? 1 : 0;