2 * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (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/lhash.h>
28 #ifndef OPENSSL_NO_RSA
29 # include <openssl/rsa.h>
31 #ifndef OPENSSL_NO_DSA
32 # include <openssl/dsa.h>
37 #define BITS "default_bits"
38 #define KEYFILE "default_keyfile"
39 #define PROMPT "prompt"
40 #define DISTINGUISHED_NAME "distinguished_name"
41 #define ATTRIBUTES "attributes"
42 #define V3_EXTENSIONS "x509_extensions"
43 #define REQ_EXTENSIONS "req_extensions"
44 #define STRING_MASK "string_mask"
45 #define UTF8_IN "utf8"
47 #define DEFAULT_KEY_LENGTH 2048
48 #define MIN_KEY_LENGTH 512
50 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
51 int attribs, unsigned long chtype);
52 static int build_subject(X509_REQ *req, const char *subj, unsigned long chtype,
54 static int prompt_info(X509_REQ *req,
55 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
56 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
57 int attribs, unsigned long chtype);
58 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
59 STACK_OF(CONF_VALUE) *attr, int attribs,
60 unsigned long chtype);
61 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
62 char *value, int nid, int n_min, int n_max,
63 unsigned long chtype);
64 static int add_DN_object(X509_NAME *n, char *text, const char *def,
65 char *value, int nid, int n_min, int n_max,
66 unsigned long chtype, int mval);
67 static int genpkey_cb(EVP_PKEY_CTX *ctx);
68 static int build_data(char *text, const char *def,
69 char *value, int n_min, int n_max,
70 char *buf, const int buf_size,
71 const char *desc1, const char *desc2
73 static int req_check_len(int len, int n_min, int n_max);
74 static int check_end(const char *str, const char *end);
75 static int join(char buf[], size_t buf_size, const char *name,
76 const char *tail, const char *desc);
77 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
78 int *pkey_type, long *pkeylen,
79 char **palgnam, ENGINE *keygen_engine);
80 static CONF *req_conf = NULL;
81 static CONF *addext_conf = NULL;
84 typedef enum OPTION_choice {
85 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
86 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
87 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
88 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY,
89 OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
90 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
91 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
92 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_ADDEXT, OPT_EXTENSIONS,
93 OPT_REQEXTS, OPT_PRECERT, OPT_MD, OPT_SM2ID, OPT_SM2HEXID,
97 const OPTIONS req_options[] = {
98 OPT_SECTION("General"),
99 {"help", OPT_HELP, '-', "Display this summary"},
100 #ifndef OPENSSL_NO_ENGINE
101 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
102 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
103 "Specify engine to be used for key generation operations"},
105 {"in", OPT_IN, '<', "Input file"},
106 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
107 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
109 OPT_SECTION("Certificate"),
110 {"new", OPT_NEW, '-', "New request"},
111 {"config", OPT_CONFIG, '<', "Request template file"},
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 an 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 {"addext", OPT_ADDEXT, 's',
126 "Additional cert extension key=value pair (may be given more than once)"},
127 {"extensions", OPT_EXTENSIONS, 's',
128 "Cert extension section (override value in config file)"},
129 {"reqexts", OPT_REQEXTS, 's',
130 "Request extension section (override value in config file)"},
131 {"precert", OPT_PRECERT, '-', "Add a poison extension (implies -new)"},
133 OPT_SECTION("Keys and Signing"),
134 {"key", OPT_KEY, 's', "Private key to use"},
135 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
136 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
137 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
138 {"passin", OPT_PASSIN, 's', "Private key password source"},
139 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
140 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
141 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
142 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
143 {"", OPT_MD, '-', "Any supported digest"},
144 #ifndef OPENSSL_NO_SM2
145 {"sm2-id", OPT_SM2ID, 's',
146 "Specify an ID string to verify an SM2 certificate request"},
147 {"sm2-hex-id", OPT_SM2HEXID, 's',
148 "Specify a hex ID string to verify an SM2 certificate request"},
151 OPT_SECTION("Output"),
152 {"out", OPT_OUT, '>', "Output file"},
153 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
154 {"batch", OPT_BATCH, '-',
155 "Do not ask anything during request generation"},
156 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
157 {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
158 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
159 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
160 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
168 * An LHASH of strings, where each string is an extension name.
170 static unsigned long ext_name_hash(const OPENSSL_STRING *a)
172 return OPENSSL_LH_strhash((const char *)a);
175 static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b)
177 return strcmp((const char *)a, (const char *)b);
180 static void exts_cleanup(OPENSSL_STRING *x)
182 OPENSSL_free((char *)x);
186 * Is the |kv| key already duplicated? This is remarkably tricky to get
187 * right. Return 0 if unique, -1 on runtime error; 1 if found or a syntax
190 static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv)
196 /* Skip leading whitespace, make a copy. */
197 while (*kv && isspace(*kv))
200 if ((p = strchr(kv, '=')) == NULL)
203 if ((kv = OPENSSL_strdup(kv)) == NULL)
206 /* Skip trailing space before the equal sign. */
207 for (p = kv + off; p > kv; --p)
216 /* Finally have a clean "key"; see if it's there [by attempt to add it]. */
217 p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING*)kv);
221 } else if (lh_OPENSSL_STRING_error(addexts)) {
229 int req_main(int argc, char **argv)
231 ASN1_INTEGER *serial = NULL;
232 BIO *in = NULL, *out = NULL;
233 ENGINE *e = NULL, *gen_eng = NULL;
234 EVP_PKEY *pkey = NULL;
235 EVP_PKEY_CTX *genctx = NULL;
236 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
237 LHASH_OF(OPENSSL_STRING) *addexts = NULL;
239 X509_REQ *req = NULL;
240 const EVP_CIPHER *cipher = NULL;
241 const EVP_MD *md_alg = NULL, *digest = NULL;
242 BIO *addext_bio = NULL;
243 char *extensions = NULL, *infile = NULL;
244 char *outfile = NULL, *keyfile = NULL;
245 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
246 char *passin = NULL, *passout = NULL;
247 char *nofree_passin = NULL, *nofree_passout = NULL;
248 char *req_exts = NULL, *subj = NULL;
249 char *template = default_config_file, *keyout = NULL;
250 const char *keyalg = NULL;
252 int ret = 1, x509 = 0, days = 0, i = 0, newreq = 0, verbose = 0;
253 int pkey_type = -1, private = 0;
254 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
255 int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
256 int nodes = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0;
258 unsigned long chtype = MBSTRING_ASC, reqflag = 0;
259 unsigned char *sm2_id = NULL;
260 size_t sm2_idlen = 0;
263 #ifndef OPENSSL_NO_DES
264 cipher = EVP_des_ede3_cbc();
267 prog = opt_init(argc, argv, req_options);
268 while ((o = opt_next()) != OPT_EOF) {
273 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
276 opt_help(req_options);
280 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
284 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
288 e = setup_engine(opt_arg(), 0);
290 case OPT_KEYGEN_ENGINE:
291 #ifndef OPENSSL_NO_ENGINE
292 gen_eng = ENGINE_by_id(opt_arg());
293 if (gen_eng == NULL) {
294 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
309 template = opt_arg();
312 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
325 passargin = opt_arg();
328 passargout = opt_arg();
339 if (pkeyopts == NULL)
340 pkeyopts = sk_OPENSSL_STRING_new_null();
342 || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
347 sigopts = sk_OPENSSL_STRING_new_null();
348 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
373 chtype = MBSTRING_UTF8;
376 if (!set_nameopt(opt_arg()))
380 if (!set_cert_ex(&reqflag, opt_arg()))
390 days = atoi(opt_arg());
393 if (serial != NULL) {
394 BIO_printf(bio_err, "Serial number supplied twice\n");
397 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
407 case OPT_MULTIVALUE_RDN:
412 if (addexts == NULL) {
413 addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp);
414 addext_bio = BIO_new(BIO_s_mem());
415 if (addexts == NULL || addext_bio == NULL)
418 i = duplicated(addexts, p);
421 if (i < 0 || BIO_printf(addext_bio, "%s\n", opt_arg()) < 0)
425 extensions = opt_arg();
428 req_exts = opt_arg();
431 newreq = precert = 1;
434 if (!opt_md(opt_unknown(), &md_alg))
439 if (sm2_id != NULL) {
441 "Use one of the options 'sm2-hex-id' or 'sm2-id'\n");
444 sm2_id = (unsigned char *)opt_arg();
445 sm2_idlen = strlen((const char *)sm2_id);
448 if (sm2_id != NULL) {
450 "Use one of the options 'sm2-hex-id' or 'sm2-id'\n");
453 /* try to parse the input as hex string first */
455 sm2_id = OPENSSL_hexstr2buf(opt_arg(), (long *)&sm2_idlen);
456 if (sm2_id == NULL) {
457 BIO_printf(bio_err, "Invalid hex string input\n");
463 argc = opt_num_rest();
468 BIO_printf(bio_err, "Ignoring -days; not generating a certificate\n");
469 if (x509 && infile == NULL)
472 /* TODO: simplify this as pkey is still always NULL here */
473 private = newreq && (pkey == NULL) ? 1 : 0;
475 if (!app_passwd(passargin, passargout, &passin, &passout)) {
476 BIO_printf(bio_err, "Error getting passwords\n");
481 BIO_printf(bio_err, "Using configuration from %s\n", template);
482 if ((req_conf = app_load_config(template)) == NULL)
487 "Using additional configuration from command line\n");
488 if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL)
491 if (template != default_config_file && !app_load_modules(req_conf))
494 if (req_conf != NULL) {
495 p = NCONF_get_string(req_conf, NULL, "oid_file");
501 oid_bio = BIO_new_file(p, "r");
502 if (oid_bio == NULL) {
504 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
505 ERR_print_errors(bio_err);
508 OBJ_create_objects(oid_bio);
513 if (!add_oid_section(req_conf))
516 if (md_alg == NULL) {
517 p = NCONF_get_string(req_conf, SECTION, "default_md");
521 if (!opt_md(p, &md_alg))
527 if (extensions == NULL) {
528 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
529 if (extensions == NULL)
532 if (extensions != NULL) {
533 /* Check syntax of file */
535 X509V3_set_ctx_test(&ctx);
536 X509V3_set_nconf(&ctx, req_conf);
537 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
539 "Error Loading extension section %s\n", extensions);
543 if (addext_conf != NULL) {
544 /* Check syntax of command line extensions */
546 X509V3_set_ctx_test(&ctx);
547 X509V3_set_nconf(&ctx, addext_conf);
548 if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) {
549 BIO_printf(bio_err, "Error Loading command line extensions\n");
554 if (passin == NULL) {
555 passin = nofree_passin =
556 NCONF_get_string(req_conf, SECTION, "input_password");
561 if (passout == NULL) {
562 passout = nofree_passout =
563 NCONF_get_string(req_conf, SECTION, "output_password");
568 p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
572 if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) {
573 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
577 if (chtype != MBSTRING_UTF8) {
578 p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
581 else if (strcmp(p, "yes") == 0)
582 chtype = MBSTRING_UTF8;
585 if (req_exts == NULL) {
586 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
587 if (req_exts == NULL)
590 if (req_exts != NULL) {
591 /* Check syntax of file */
593 X509V3_set_ctx_test(&ctx);
594 X509V3_set_nconf(&ctx, req_conf);
595 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
597 "Error Loading request extension section %s\n",
603 if (keyfile != NULL) {
604 pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
606 /* load_key() has already printed an appropriate message */
609 app_RAND_load_conf(req_conf, SECTION);
613 if (newreq && (pkey == NULL)) {
614 app_RAND_load_conf(req_conf, SECTION);
616 if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
617 newkey = DEFAULT_KEY_LENGTH;
620 if (keyalg != NULL) {
621 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
622 &keyalgstr, gen_eng);
627 if (newkey < MIN_KEY_LENGTH
628 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
629 BIO_printf(bio_err, "private key length is too short,\n");
630 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
631 MIN_KEY_LENGTH, newkey);
635 if (pkey_type == EVP_PKEY_RSA && newkey > OPENSSL_RSA_MAX_MODULUS_BITS)
637 "Warning: It is not recommended to use more than %d bit for RSA keys.\n"
638 " Your key size is %ld! Larger key size may behave not as expected.\n",
639 OPENSSL_RSA_MAX_MODULUS_BITS, newkey);
641 #ifndef OPENSSL_NO_DSA
642 if (pkey_type == EVP_PKEY_DSA && newkey > OPENSSL_DSA_MAX_MODULUS_BITS)
644 "Warning: It is not recommended to use more than %d bit for DSA keys.\n"
645 " Your key size is %ld! Larger key size may behave not as expected.\n",
646 OPENSSL_DSA_MAX_MODULUS_BITS, newkey);
649 if (genctx == NULL) {
650 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
651 &keyalgstr, gen_eng);
656 if (pkeyopts != NULL) {
658 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
659 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
660 if (pkey_ctrl_string(genctx, genopt) <= 0) {
661 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
662 ERR_print_errors(bio_err);
668 if (pkey_type == EVP_PKEY_EC) {
669 BIO_printf(bio_err, "Generating an EC private key\n");
671 BIO_printf(bio_err, "Generating a %s private key\n", keyalgstr);
674 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
675 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
677 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
678 BIO_puts(bio_err, "Error Generating Key\n");
682 EVP_PKEY_CTX_free(genctx);
685 if (keyout == NULL) {
686 keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
692 BIO_printf(bio_err, "writing new private key to stdout\n");
694 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
695 out = bio_open_owner(keyout, outformat, private);
699 p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
702 p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
706 if ((p != NULL) && (strcmp(p, "no") == 0))
714 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
715 NULL, 0, NULL, passout)) {
716 if ((ERR_GET_REASON(ERR_peek_error()) ==
717 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
726 BIO_printf(bio_err, "-----\n");
730 in = bio_open_default(infile, 'r', informat);
734 if (informat == FORMAT_ASN1)
735 req = d2i_X509_REQ_bio(in, NULL);
737 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
739 BIO_printf(bio_err, "unable to load X509 request\n");
744 if (newreq || x509) {
746 BIO_printf(bio_err, "you need to specify a private key\n");
751 req = X509_REQ_new();
756 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
757 subj = NULL; /* done processing '-subj' option */
759 BIO_printf(bio_err, "problems making Certificate Request\n");
766 if ((x509ss = X509_new()) == NULL)
769 /* Set version to V3 */
770 if ((extensions != NULL || addext_conf != NULL)
771 && !X509_set_version(x509ss, 2))
773 if (serial != NULL) {
774 if (!X509_set_serialNumber(x509ss, serial))
777 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
781 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
784 /* set default days if it's not specified */
787 if (!set_cert_times(x509ss, NULL, NULL, days))
789 if (!X509_set_subject_name
790 (x509ss, X509_REQ_get_subject_name(req)))
792 tmppkey = X509_REQ_get0_pubkey(req);
793 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
796 /* Set up V3 context struct */
798 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
799 X509V3_set_nconf(&ext_ctx, req_conf);
802 if (extensions != NULL && !X509V3_EXT_add_nconf(req_conf,
803 &ext_ctx, extensions,
805 BIO_printf(bio_err, "Error Loading extension section %s\n",
809 if (addext_conf != NULL
810 && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default",
812 BIO_printf(bio_err, "Error Loading command line extensions\n");
816 /* If a pre-cert was requested, we need to add a poison extension */
818 if (X509_add1_ext_i2d(x509ss, NID_ct_precert_poison, NULL, 1, 0)
820 BIO_printf(bio_err, "Error adding poison extension\n");
825 i = do_X509_sign(x509ss, pkey, digest, sigopts);
827 ERR_print_errors(bio_err);
833 /* Set up V3 context struct */
835 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
836 X509V3_set_nconf(&ext_ctx, req_conf);
840 && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx,
842 BIO_printf(bio_err, "Error Loading extension section %s\n",
846 if (addext_conf != NULL
847 && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default",
849 BIO_printf(bio_err, "Error Loading command line extensions\n");
852 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
854 ERR_print_errors(bio_err);
861 BIO_printf(bio_err, "Cannot modify certificate subject\n");
867 BIO_printf(bio_err, "Modifying Request's Subject\n");
868 print_name(bio_err, "old subject=",
869 X509_REQ_get_subject_name(req), get_nameopt());
872 if (build_subject(req, subj, chtype, multirdn) == 0) {
873 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
879 print_name(bio_err, "new subject=",
880 X509_REQ_get_subject_name(req), get_nameopt());
884 if (verify && !x509) {
885 EVP_PKEY *tpubkey = pkey;
887 if (tpubkey == NULL) {
888 tpubkey = X509_REQ_get0_pubkey(req);
893 if (sm2_id != NULL) {
894 #ifndef OPENSSL_NO_SM2
895 ASN1_OCTET_STRING *v;
897 v = ASN1_OCTET_STRING_new();
899 BIO_printf(bio_err, "error: SM2 ID allocation failed\n");
903 if (!ASN1_OCTET_STRING_set(v, sm2_id, sm2_idlen)) {
904 BIO_printf(bio_err, "error: setting SM2 ID failed\n");
905 ASN1_OCTET_STRING_free(v);
909 X509_REQ_set0_sm2_id(req, v);
913 i = X509_REQ_verify(req, tpubkey);
918 BIO_printf(bio_err, "verify failure\n");
919 ERR_print_errors(bio_err);
920 } else { /* if (i > 0) */
921 BIO_printf(bio_err, "verify OK\n");
925 if (noout && !text && !modulus && !subject && !pubkey) {
930 out = bio_open_default(outfile,
931 keyout != NULL && outfile != NULL &&
932 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
938 EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req);
940 if (tpubkey == NULL) {
941 BIO_printf(bio_err, "Error getting public key\n");
942 ERR_print_errors(bio_err);
945 PEM_write_bio_PUBKEY(out, tpubkey);
950 ret = X509_print_ex(out, x509ss, get_nameopt(), reqflag);
952 ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag);
956 BIO_printf(bio_err, "Error printing certificate\n");
958 BIO_printf(bio_err, "Error printing certificate request\n");
960 ERR_print_errors(bio_err);
967 print_name(out, "subject=", X509_get_subject_name(x509ss),
970 print_name(out, "subject=", X509_REQ_get_subject_name(req),
978 tpubkey = X509_get0_pubkey(x509ss);
980 tpubkey = X509_REQ_get0_pubkey(req);
981 if (tpubkey == NULL) {
982 fprintf(stdout, "Modulus=unavailable\n");
985 fprintf(stdout, "Modulus=");
986 #ifndef OPENSSL_NO_RSA
987 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
989 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
993 fprintf(stdout, "Wrong Algorithm type");
994 fprintf(stdout, "\n");
997 if (!noout && !x509) {
998 if (outformat == FORMAT_ASN1)
999 i = i2d_X509_REQ_bio(out, req);
1001 i = PEM_write_bio_X509_REQ_NEW(out, req);
1003 i = PEM_write_bio_X509_REQ(out, req);
1005 BIO_printf(bio_err, "unable to write X509 request\n");
1009 if (!noout && x509 && (x509ss != NULL)) {
1010 if (outformat == FORMAT_ASN1)
1011 i = i2d_X509_bio(out, x509ss);
1013 i = PEM_write_bio_X509(out, x509ss);
1015 BIO_printf(bio_err, "unable to write X509 certificate\n");
1022 OPENSSL_free(sm2_id);
1024 ERR_print_errors(bio_err);
1026 NCONF_free(req_conf);
1027 NCONF_free(addext_conf);
1028 BIO_free(addext_bio);
1031 EVP_PKEY_free(pkey);
1032 EVP_PKEY_CTX_free(genctx);
1033 sk_OPENSSL_STRING_free(pkeyopts);
1034 sk_OPENSSL_STRING_free(sigopts);
1035 lh_OPENSSL_STRING_doall(addexts, exts_cleanup);
1036 lh_OPENSSL_STRING_free(addexts);
1037 #ifndef OPENSSL_NO_ENGINE
1038 ENGINE_free(gen_eng);
1040 OPENSSL_free(keyalgstr);
1043 ASN1_INTEGER_free(serial);
1045 if (passin != nofree_passin)
1046 OPENSSL_free(passin);
1047 if (passout != nofree_passout)
1048 OPENSSL_free(passout);
1052 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1053 int attribs, unsigned long chtype)
1057 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1058 char *tmp, *dn_sect, *attr_sect;
1060 tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
1063 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
1066 dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
1067 if (dn_sect == NULL) {
1068 BIO_printf(bio_err, "unable to find '%s' in config\n",
1069 DISTINGUISHED_NAME);
1072 dn_sk = NCONF_get_section(req_conf, dn_sect);
1073 if (dn_sk == NULL) {
1074 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
1078 attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
1079 if (attr_sect == NULL) {
1083 attr_sk = NCONF_get_section(req_conf, attr_sect);
1084 if (attr_sk == NULL) {
1085 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
1090 /* setup version number */
1091 if (!X509_REQ_set_version(req, 0L))
1092 goto err; /* version 1 */
1095 i = build_subject(req, subj, chtype, multirdn);
1097 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1099 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
1104 if (!X509_REQ_set_pubkey(req, pkey))
1113 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1114 * where characters may be escaped by \
1116 static int build_subject(X509_REQ *req, const char *subject, unsigned long chtype,
1121 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
1124 if (!X509_REQ_set_subject_name(req, n)) {
1132 static int prompt_info(X509_REQ *req,
1133 STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect,
1134 STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect,
1135 int attribs, unsigned long chtype)
1146 subj = X509_REQ_get_subject_name(req);
1150 "You are about to be asked to enter information that will be incorporated\n");
1151 BIO_printf(bio_err, "into your certificate request.\n");
1153 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
1155 "There are quite a few fields but you can leave some blank\n");
1157 "For some fields there will be a default value,\n");
1159 "If you enter '.', the field will be left blank.\n");
1160 BIO_printf(bio_err, "-----\n");
1163 if (sk_CONF_VALUE_num(dn_sk)) {
1168 if (sk_CONF_VALUE_num(dn_sk) <= i)
1171 v = sk_CONF_VALUE_value(dn_sk, i);
1174 if (!check_end(type, "_min") || !check_end(type, "_max") ||
1175 !check_end(type, "_default") || !check_end(type, "_value"))
1178 * Skip past any leading X. X: X, etc to allow for multiple
1181 for (p = v->name; *p; p++)
1182 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1194 /* If OBJ not recognised ignore it */
1195 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1197 if (!join(buf, sizeof(buf), v->name, "_default", "Name"))
1199 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1204 if (!join(buf, sizeof(buf), v->name, "_value", "Name"))
1206 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
1211 if (!join(buf, sizeof(buf), v->name, "_min", "Name"))
1213 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
1219 if (!join(buf, sizeof(buf), v->name, "_max", "Name"))
1221 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
1226 if (!add_DN_object(subj, v->value, def, value, nid,
1227 n_min, n_max, chtype, mval))
1230 if (X509_NAME_entry_count(subj) == 0) {
1232 "error, no objects specified in config file\n");
1237 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1240 "\nPlease enter the following 'extra' attributes\n");
1242 "to be sent with your certificate request\n");
1249 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1252 v = sk_CONF_VALUE_value(attr_sk, i);
1254 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1257 if (!join(buf, sizeof(buf), type, "_default", "Name"))
1259 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1265 if (!join(buf, sizeof(buf), type, "_value", "Name"))
1267 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1273 if (!join(buf, sizeof(buf), type,"_min", "Name"))
1275 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1280 if (!join(buf, sizeof(buf), type, "_max", "Name"))
1282 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1287 if (!add_attribute_object(req,
1288 v->value, def, value, nid, n_min,
1294 BIO_printf(bio_err, "No template, please set one up.\n");
1302 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1303 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1304 unsigned long chtype)
1306 int i, spec_char, plus_char;
1312 subj = X509_REQ_get_subject_name(req);
1314 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1316 v = sk_CONF_VALUE_value(dn_sk, i);
1320 * Skip past any leading X. X: X, etc to allow for multiple instances
1322 for (p = v->name; *p; p++) {
1323 #ifndef CHARSET_EBCDIC
1324 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1326 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1327 || (*p == os_toascii['.']));
1336 #ifndef CHARSET_EBCDIC
1337 plus_char = (*type == '+');
1339 plus_char = (*type == os_toascii['+']);
1347 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1348 (unsigned char *)v->value, -1, -1,
1354 if (!X509_NAME_entry_count(subj)) {
1355 BIO_printf(bio_err, "error, no objects specified in config file\n");
1359 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1360 v = sk_CONF_VALUE_value(attr_sk, i);
1361 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1362 (unsigned char *)v->value, -1))
1369 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1370 char *value, int nid, int n_min, int n_max,
1371 unsigned long chtype, int mval)
1376 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1377 "DN value", "DN default");
1378 if ((ret == 0) || (ret == 1))
1382 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1383 (unsigned char *)buf, -1, -1, mval))
1389 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1390 char *value, int nid, int n_min,
1391 int n_max, unsigned long chtype)
1396 ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf),
1397 "Attribute value", "Attribute default");
1398 if ((ret == 0) || (ret == 1))
1402 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1403 (unsigned char *)buf, -1)) {
1404 BIO_printf(bio_err, "Error adding attribute\n");
1405 ERR_print_errors(bio_err);
1413 static int build_data(char *text, const char *def,
1414 char *value, int n_min, int n_max,
1415 char *buf, const int buf_size,
1416 const char *desc1, const char *desc2
1422 BIO_printf(bio_err, "%s [%s]:", text, def);
1423 (void)BIO_flush(bio_err);
1424 if (value != NULL) {
1425 if (!join(buf, buf_size, value, "\n", desc1))
1427 BIO_printf(bio_err, "%s\n", value);
1431 if (!fgets(buf, buf_size, stdin))
1441 if (buf[0] == '\n') {
1442 if ((def == NULL) || (def[0] == '\0'))
1444 if (!join(buf, buf_size, def, "\n", desc2))
1446 } else if ((buf[0] == '.') && (buf[1] == '\n')) {
1451 if (buf[i - 1] != '\n') {
1452 BIO_printf(bio_err, "weird input :-(\n");
1456 #ifdef CHARSET_EBCDIC
1457 ebcdic2ascii(buf, buf, i);
1459 if (!req_check_len(i, n_min, n_max)) {
1467 static int req_check_len(int len, int n_min, int n_max)
1469 if ((n_min > 0) && (len < n_min)) {
1471 "string is too short, it needs to be at least %d bytes long\n",
1475 if ((n_max >= 0) && (len > n_max)) {
1477 "string is too long, it needs to be no more than %d bytes long\n",
1484 /* Check if the end of a string matches 'end' */
1485 static int check_end(const char *str, const char *end)
1494 tmp = str + slen - elen;
1495 return strcmp(tmp, end);
1499 * Merge the two strings together into the result buffer checking for
1500 * overflow and producing an error message if there is.
1502 static int join(char buf[], size_t buf_size, const char *name,
1503 const char *tail, const char *desc)
1505 const size_t name_len = strlen(name), tail_len = strlen(tail);
1507 if (name_len + tail_len + 1 > buf_size) {
1508 BIO_printf(bio_err, "%s '%s' too long\n", desc, name);
1511 memcpy(buf, name, name_len);
1512 memcpy(buf + name_len, tail, tail_len + 1);
1516 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1517 int *pkey_type, long *pkeylen,
1518 char **palgnam, ENGINE *keygen_engine)
1520 EVP_PKEY_CTX *gctx = NULL;
1521 EVP_PKEY *param = NULL;
1524 const char *paramfile = NULL;
1527 *pkey_type = EVP_PKEY_RSA;
1529 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1530 *pkey_type = EVP_PKEY_RSA;
1531 keylen = atol(gstr);
1533 } else if (strncmp(gstr, "param:", 6) == 0) {
1534 paramfile = gstr + 6;
1536 const char *p = strchr(gstr, ':');
1539 const EVP_PKEY_ASN1_METHOD *ameth;
1546 * The lookup of a the string will cover all engines so keep a note
1547 * of the implementation.
1550 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1552 if (ameth == NULL) {
1553 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1557 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1558 #ifndef OPENSSL_NO_ENGINE
1559 ENGINE_finish(tmpeng);
1561 if (*pkey_type == EVP_PKEY_RSA) {
1563 keylen = atol(p + 1);
1568 } else if (p != NULL) {
1573 if (paramfile != NULL) {
1574 pbio = BIO_new_file(paramfile, "r");
1576 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1579 param = PEM_read_bio_Parameters(pbio, NULL);
1581 if (param == NULL) {
1584 (void)BIO_reset(pbio);
1585 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1587 param = X509_get_pubkey(x);
1594 if (param == NULL) {
1595 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1598 if (*pkey_type == -1) {
1599 *pkey_type = EVP_PKEY_id(param);
1600 } else if (*pkey_type != EVP_PKEY_base_id(param)) {
1601 BIO_printf(bio_err, "Key Type does not match parameters\n");
1602 EVP_PKEY_free(param);
1607 if (palgnam != NULL) {
1608 const EVP_PKEY_ASN1_METHOD *ameth;
1612 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1613 if (ameth == NULL) {
1614 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1617 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1618 *palgnam = OPENSSL_strdup(anam);
1619 #ifndef OPENSSL_NO_ENGINE
1620 ENGINE_finish(tmpeng);
1624 if (param != NULL) {
1625 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1626 *pkeylen = EVP_PKEY_bits(param);
1627 EVP_PKEY_free(param);
1629 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1633 BIO_puts(bio_err, "Error allocating keygen context\n");
1634 ERR_print_errors(bio_err);
1638 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1639 BIO_puts(bio_err, "Error initializing keygen context\n");
1640 ERR_print_errors(bio_err);
1641 EVP_PKEY_CTX_free(gctx);
1644 #ifndef OPENSSL_NO_RSA
1645 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1646 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1647 BIO_puts(bio_err, "Error setting RSA keysize\n");
1648 ERR_print_errors(bio_err);
1649 EVP_PKEY_CTX_free(gctx);
1658 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1661 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1663 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1672 BIO_write(b, &c, 1);
1677 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1678 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1680 EVP_PKEY_CTX *pkctx = NULL;
1681 EVP_PKEY_CTX *pctx = NULL;
1682 int i, def_nid, ret = 0;
1686 if (EVP_PKEY_id(pkey) == EVP_PKEY_SM2) {
1687 pctx = EVP_PKEY_CTX_new(pkey, NULL);
1689 BIO_printf(bio_err, "memory allocation failure.\n");
1692 /* set SM2 ID from sig options before calling the real init routine */
1693 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1694 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1695 if (pkey_ctrl_string(pctx, sigopt) <= 0) {
1696 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1697 ERR_print_errors(bio_err);
1701 EVP_MD_CTX_set_pkey_ctx(ctx, pctx);
1704 * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is mandatory
1705 * for this algorithm.
1707 if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) == 2
1708 && def_nid == NID_undef) {
1709 /* The signing algorithm requires there to be no digest */
1712 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1714 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1715 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1716 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1717 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1718 ERR_print_errors(bio_err);
1726 EVP_PKEY_CTX_free(pctx);
1730 static void do_sign_cleanup(EVP_MD_CTX *ctx, EVP_PKEY *pkey)
1733 * With SM2, do_sign_init() attached an EVP_PKEY_CTX to the EVP_MD_CTX,
1734 * and we have to free it explicitly.
1736 if (EVP_PKEY_id(pkey) == EVP_PKEY_SM2) {
1737 EVP_PKEY_CTX *pctx = EVP_MD_CTX_pkey_ctx(ctx);
1739 EVP_MD_CTX_set_pkey_ctx(ctx, NULL);
1740 EVP_PKEY_CTX_free(pctx);
1744 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1745 STACK_OF(OPENSSL_STRING) *sigopts)
1748 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1750 if (do_sign_init(mctx, pkey, md, sigopts) > 0) {
1751 rv = (X509_sign_ctx(x, mctx) > 0);
1752 do_sign_cleanup(mctx, pkey);
1754 EVP_MD_CTX_free(mctx);
1758 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1759 STACK_OF(OPENSSL_STRING) *sigopts)
1762 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1764 if (do_sign_init(mctx, pkey, md, sigopts) > 0) {
1765 rv = (X509_REQ_sign_ctx(x, mctx) > 0);
1766 do_sign_cleanup(mctx, pkey);
1768 EVP_MD_CTX_free(mctx);
1772 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1773 STACK_OF(OPENSSL_STRING) *sigopts)
1776 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1778 if (do_sign_init(mctx, pkey, md, sigopts) > 0) {
1779 rv = (X509_CRL_sign_ctx(x, mctx) > 0);
1780 do_sign_cleanup(mctx, pkey);
1782 EVP_MD_CTX_free(mctx);