2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
15 #include <openssl/bio.h>
16 #include <openssl/evp.h>
17 #include <openssl/conf.h>
18 #include <openssl/err.h>
19 #include <openssl/asn1.h>
20 #include <openssl/x509.h>
21 #include <openssl/x509v3.h>
22 #include <openssl/objects.h>
23 #include <openssl/pem.h>
24 #include <openssl/bn.h>
25 #ifndef OPENSSL_NO_RSA
26 # include <openssl/rsa.h>
28 #ifndef OPENSSL_NO_DSA
29 # include <openssl/dsa.h>
34 #define BITS "default_bits"
35 #define KEYFILE "default_keyfile"
36 #define PROMPT "prompt"
37 #define DISTINGUISHED_NAME "distinguished_name"
38 #define ATTRIBUTES "attributes"
39 #define V3_EXTENSIONS "x509_extensions"
40 #define REQ_EXTENSIONS "req_extensions"
41 #define STRING_MASK "string_mask"
42 #define UTF8_IN "utf8"
44 #define DEFAULT_KEY_LENGTH 2048
45 #define MIN_KEY_LENGTH 512
47 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *dn, int mutlirdn,
48 int attribs, unsigned long chtype);
49 static int build_subject(X509_REQ *req, char *subj, unsigned long chtype,
51 static int prompt_info(X509_REQ *req,
52 STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
53 STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect,
54 int attribs, unsigned long chtype);
55 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
56 STACK_OF(CONF_VALUE) *attr, int attribs,
57 unsigned long chtype);
58 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
59 char *value, int nid, int n_min, int n_max,
60 unsigned long chtype);
61 static int add_DN_object(X509_NAME *n, char *text, const char *def,
62 char *value, int nid, int n_min, int n_max,
63 unsigned long chtype, int mval);
64 static int genpkey_cb(EVP_PKEY_CTX *ctx);
65 static int req_check_len(int len, int n_min, int n_max);
66 static int check_end(const char *str, const char *end);
67 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
68 int *pkey_type, long *pkeylen,
69 char **palgnam, ENGINE *keygen_engine);
70 static CONF *req_conf = NULL;
73 typedef enum OPTION_choice {
74 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
75 OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY,
76 OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT,
77 OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_RAND, OPT_NEWKEY,
78 OPT_PKEYOPT, OPT_SIGOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS,
79 OPT_VERIFY, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8,
80 OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509,
81 OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_EXTENSIONS,
85 OPTIONS req_options[] = {
86 {"help", OPT_HELP, '-', "Display this summary"},
87 {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
88 {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
89 {"in", OPT_IN, '<', "Input file"},
90 {"out", OPT_OUT, '>', "Output file"},
91 {"key", OPT_KEY, 's', "Private key to use"},
92 {"keyform", OPT_KEYFORM, 'f', "Key file format"},
93 {"pubkey", OPT_PUBKEY, '-', "Output public key"},
94 {"new", OPT_NEW, '-', "New request"},
95 {"config", OPT_CONFIG, '<', "Request template file"},
96 {"keyout", OPT_KEYOUT, '>', "File to send the key to"},
97 {"passin", OPT_PASSIN, 's', "Private key password source"},
98 {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"},
99 {"rand", OPT_RAND, 's',
100 "Load the file(s) into the random number generator"},
101 {"newkey", OPT_NEWKEY, 's', "Specify as type:bits"},
102 {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"},
103 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
104 {"batch", OPT_BATCH, '-',
105 "Do not ask anything during request generation"},
106 {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"},
107 {"modulus", OPT_MODULUS, '-', "RSA modulus"},
108 {"verify", OPT_VERIFY, '-', "Verify signature on REQ"},
109 {"nodes", OPT_NODES, '-', "Don't encrypt the output key"},
110 {"noout", OPT_NOOUT, '-', "Do not output REQ"},
111 {"verbose", OPT_VERBOSE, '-', "Verbose output"},
112 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
113 {"nameopt", OPT_NAMEOPT, 's', "Various certificate name options"},
114 {"reqopt", OPT_REQOPT, 's', "Various request text options"},
115 {"text", OPT_TEXT, '-', "Text form of request"},
116 {"x509", OPT_X509, '-',
117 "Output a x509 structure instead of a cert request"},
118 {OPT_MORE_STR, 1, 1, "(Required by some CA's)"},
119 {"subj", OPT_SUBJ, 's', "Set or modify request subject"},
120 {"subject", OPT_SUBJECT, '-', "Output the request's subject"},
121 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
122 "Enable support for multivalued RDNs"},
123 {"days", OPT_DAYS, 'p', "Number of days cert is valid for"},
124 {"set_serial", OPT_SET_SERIAL, 'p', "Serial number to use"},
125 {"extensions", OPT_EXTENSIONS, 's',
126 "Cert extension section (override value in config file)"},
127 {"reqexts", OPT_REQEXTS, 's',
128 "Request extension section (override value in config file)"},
129 {"", OPT_MD, '-', "Any supported digest"},
130 #ifndef OPENSSL_NO_ENGINE
131 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
132 {"keygen_engine", OPT_KEYGEN_ENGINE, 's',
133 "Specify engine to be used for key generation operations"},
138 int req_main(int argc, char **argv)
140 ASN1_INTEGER *serial = NULL;
141 BIO *in = NULL, *out = NULL;
142 ENGINE *e = NULL, *gen_eng = NULL;
143 EVP_PKEY *pkey = NULL;
144 EVP_PKEY_CTX *genctx = NULL;
145 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
147 X509_REQ *req = NULL;
148 const EVP_CIPHER *cipher = NULL;
149 const EVP_MD *md_alg = NULL, *digest = NULL;
150 char *extensions = NULL, *infile = NULL;
151 char *outfile = NULL, *keyfile = NULL, *inrand = NULL;
152 char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL;
153 char *passin = NULL, *passout = NULL;
154 char *nofree_passin = NULL, *nofree_passout = NULL;
155 char *req_exts = NULL, *subj = NULL;
156 char *template = default_config_file, *keyout = NULL;
157 const char *keyalg = NULL;
159 int ret = 1, x509 = 0, days = 30, i = 0, newreq = 0, verbose = 0;
160 int pkey_type = -1, private = 0;
161 int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyform = FORMAT_PEM;
162 int modulus = 0, multirdn = 0, verify = 0, noout = 0, text = 0;
163 int nodes = 0, newhdr = 0, subject = 0, pubkey = 0;
165 unsigned long chtype = MBSTRING_ASC, nmflag = 0, reqflag = 0;
168 #ifndef OPENSSL_NO_DES
169 cipher = EVP_des_ede3_cbc();
172 prog = opt_init(argc, argv, req_options);
173 while ((o = opt_next()) != OPT_EOF) {
178 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
181 opt_help(req_options);
185 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
189 if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
193 e = setup_engine(opt_arg(), 0);
195 case OPT_KEYGEN_ENGINE:
196 #ifndef OPENSSL_NO_ENGINE
197 gen_eng = ENGINE_by_id(opt_arg());
198 if (gen_eng == NULL) {
199 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
214 template = opt_arg();
217 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform))
230 passargin = opt_arg();
233 passargout = opt_arg();
244 pkeyopts = sk_OPENSSL_STRING_new_null();
245 if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg()))
250 sigopts = sk_OPENSSL_STRING_new_null();
251 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
276 chtype = MBSTRING_UTF8;
280 if (!set_name_ex(&nmflag, opt_arg()))
284 if (!set_cert_ex(&reqflag, opt_arg()))
294 days = atoi(opt_arg());
297 serial = s2i_ASN1_INTEGER(NULL, opt_arg());
307 case OPT_MULTIVALUE_RDN:
311 extensions = opt_arg();
314 req_exts = opt_arg();
317 if (!opt_md(opt_unknown(), &md_alg))
323 argc = opt_num_rest();
328 nmflag = XN_FLAG_ONELINE;
330 /* TODO: simplify this as pkey is still always NULL here */
331 private = newreq && (pkey == NULL) ? 1 : 0;
333 if (!app_passwd(passargin, passargout, &passin, &passout)) {
334 BIO_printf(bio_err, "Error getting passwords\n");
339 BIO_printf(bio_err, "Using configuration from %s\n", template);
340 req_conf = app_load_config(template);
341 if (template != default_config_file && !app_load_modules(req_conf))
344 if (req_conf != NULL) {
345 p = NCONF_get_string(req_conf, NULL, "oid_file");
351 oid_bio = BIO_new_file(p, "r");
352 if (oid_bio == NULL) {
354 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
355 ERR_print_errors(bio_err);
358 OBJ_create_objects(oid_bio);
363 if (!add_oid_section(req_conf))
366 if (md_alg == NULL) {
367 p = NCONF_get_string(req_conf, SECTION, "default_md");
371 if (!opt_md(p, &md_alg))
378 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
383 /* Check syntax of file */
385 X509V3_set_ctx_test(&ctx);
386 X509V3_set_nconf(&ctx, req_conf);
387 if (!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
389 "Error Loading extension section %s\n", extensions);
394 if (passin == NULL) {
395 passin = nofree_passin =
396 NCONF_get_string(req_conf, SECTION, "input_password");
401 if (passout == NULL) {
402 passout = nofree_passout =
403 NCONF_get_string(req_conf, SECTION, "output_password");
408 p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
412 if (p && !ASN1_STRING_set_default_mask_asc(p)) {
413 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
417 if (chtype != MBSTRING_UTF8) {
418 p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
421 else if (strcmp(p, "yes") == 0)
422 chtype = MBSTRING_UTF8;
426 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
431 /* Check syntax of file */
433 X509V3_set_ctx_test(&ctx);
434 X509V3_set_nconf(&ctx, req_conf);
435 if (!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
437 "Error Loading request extension section %s\n",
443 if (keyfile != NULL) {
444 pkey = load_key(keyfile, keyform, 0, passin, e, "Private Key");
446 /* load_key() has already printed an appropriate message */
449 char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
450 if (randfile == NULL)
452 app_RAND_load_file(randfile, 0);
456 if (newreq && (pkey == NULL)) {
457 char *randfile = NCONF_get_string(req_conf, SECTION, "RANDFILE");
458 if (randfile == NULL)
460 app_RAND_load_file(randfile, 0);
462 app_RAND_load_files(inrand);
464 if (!NCONF_get_number(req_conf, SECTION, BITS, &newkey)) {
465 newkey = DEFAULT_KEY_LENGTH;
469 genctx = set_keygen_ctx(keyalg, &pkey_type, &newkey,
470 &keyalgstr, gen_eng);
475 if (newkey < MIN_KEY_LENGTH
476 && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA)) {
477 BIO_printf(bio_err, "private key length is too short,\n");
478 BIO_printf(bio_err, "it needs to be at least %d bits, not %ld\n",
479 MIN_KEY_LENGTH, newkey);
484 genctx = set_keygen_ctx(NULL, &pkey_type, &newkey,
485 &keyalgstr, gen_eng);
492 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) {
493 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
494 if (pkey_ctrl_string(genctx, genopt) <= 0) {
495 BIO_printf(bio_err, "parameter error \"%s\"\n", genopt);
496 ERR_print_errors(bio_err);
502 BIO_printf(bio_err, "Generating a %ld bit %s private key\n",
505 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
506 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
508 if (EVP_PKEY_keygen(genctx, &pkey) <= 0) {
509 BIO_puts(bio_err, "Error Generating Key\n");
513 EVP_PKEY_CTX_free(genctx);
516 app_RAND_write_file(randfile);
518 if (keyout == NULL) {
519 keyout = NCONF_get_string(req_conf, SECTION, KEYFILE);
525 BIO_printf(bio_err, "writing new private key to stdout\n");
527 BIO_printf(bio_err, "writing new private key to '%s'\n", keyout);
528 out = bio_open_owner(keyout, outformat, private);
532 p = NCONF_get_string(req_conf, SECTION, "encrypt_rsa_key");
535 p = NCONF_get_string(req_conf, SECTION, "encrypt_key");
539 if ((p != NULL) && (strcmp(p, "no") == 0))
547 if (!PEM_write_bio_PrivateKey(out, pkey, cipher,
548 NULL, 0, NULL, passout)) {
549 if ((ERR_GET_REASON(ERR_peek_error()) ==
550 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) {
559 BIO_printf(bio_err, "-----\n");
563 in = bio_open_default(infile, 'r', informat);
567 if (informat == FORMAT_ASN1)
568 req = d2i_X509_REQ_bio(in, NULL);
570 req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
572 BIO_printf(bio_err, "unable to load X509 request\n");
577 if (newreq || x509) {
579 BIO_printf(bio_err, "you need to specify a private key\n");
584 req = X509_REQ_new();
589 i = make_REQ(req, pkey, subj, multirdn, !x509, chtype);
590 subj = NULL; /* done processing '-subj' option */
592 BIO_printf(bio_err, "problems making Certificate Request\n");
599 if ((x509ss = X509_new()) == NULL)
602 /* Set version to V3 */
603 if (extensions && !X509_set_version(x509ss, 2))
606 if (!X509_set_serialNumber(x509ss, serial))
609 if (!rand_serial(NULL, X509_get_serialNumber(x509ss)))
613 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req)))
615 if (!X509_gmtime_adj(X509_get_notBefore(x509ss), 0))
617 if (!X509_time_adj_ex(X509_get_notAfter(x509ss), days, 0, NULL))
619 if (!X509_set_subject_name
620 (x509ss, X509_REQ_get_subject_name(req)))
622 tmppkey = X509_REQ_get0_pubkey(req);
623 if (!tmppkey || !X509_set_pubkey(x509ss, tmppkey))
626 /* Set up V3 context struct */
628 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
629 X509V3_set_nconf(&ext_ctx, req_conf);
632 if (extensions && !X509V3_EXT_add_nconf(req_conf,
633 &ext_ctx, extensions,
635 BIO_printf(bio_err, "Error Loading extension section %s\n",
640 i = do_X509_sign(x509ss, pkey, digest, sigopts);
642 ERR_print_errors(bio_err);
648 /* Set up V3 context struct */
650 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
651 X509V3_set_nconf(&ext_ctx, req_conf);
654 if (req_exts && !X509V3_EXT_REQ_add_nconf(req_conf,
657 BIO_printf(bio_err, "Error Loading extension section %s\n",
661 i = do_X509_REQ_sign(req, pkey, digest, sigopts);
663 ERR_print_errors(bio_err);
670 BIO_printf(bio_err, "Cannot modify certificate subject\n");
676 BIO_printf(bio_err, "Modifying Request's Subject\n");
677 print_name(bio_err, "old subject=",
678 X509_REQ_get_subject_name(req), nmflag);
681 if (build_subject(req, subj, chtype, multirdn) == 0) {
682 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
688 print_name(bio_err, "new subject=",
689 X509_REQ_get_subject_name(req), nmflag);
693 if (verify && !x509) {
694 EVP_PKEY *tpubkey = pkey;
696 if (tpubkey == NULL) {
697 tpubkey = X509_REQ_get0_pubkey(req);
702 i = X509_REQ_verify(req, tpubkey);
707 BIO_printf(bio_err, "verify failure\n");
708 ERR_print_errors(bio_err);
709 } else /* if (i > 0) */
710 BIO_printf(bio_err, "verify OK\n");
713 if (noout && !text && !modulus && !subject && !pubkey) {
718 out = bio_open_default(outfile,
719 keyout != NULL && outfile != NULL &&
720 strcmp(keyout, outfile) == 0 ? 'a' : 'w',
727 tpubkey = X509_REQ_get_pubkey(req);
728 if (tpubkey == NULL) {
729 BIO_printf(bio_err, "Error getting public key\n");
730 ERR_print_errors(bio_err);
733 PEM_write_bio_PUBKEY(out, tpubkey);
734 EVP_PKEY_free(tpubkey);
739 X509_print_ex(out, x509ss, nmflag, reqflag);
741 X509_REQ_print_ex(out, req, nmflag, reqflag);
746 print_name(out, "subject=", X509_get_subject_name(x509ss),
749 print_name(out, "subject=", X509_REQ_get_subject_name(req),
757 tpubkey = X509_get_pubkey(x509ss);
759 tpubkey = X509_REQ_get_pubkey(req);
760 if (tpubkey == NULL) {
761 fprintf(stdout, "Modulus=unavailable\n");
764 fprintf(stdout, "Modulus=");
765 #ifndef OPENSSL_NO_RSA
766 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA) {
768 RSA_get0_key(EVP_PKEY_get0_RSA(tpubkey), &n, NULL, NULL);
772 fprintf(stdout, "Wrong Algorithm type");
773 EVP_PKEY_free(tpubkey);
774 fprintf(stdout, "\n");
777 if (!noout && !x509) {
778 if (outformat == FORMAT_ASN1)
779 i = i2d_X509_REQ_bio(out, req);
781 i = PEM_write_bio_X509_REQ_NEW(out, req);
783 i = PEM_write_bio_X509_REQ(out, req);
785 BIO_printf(bio_err, "unable to write X509 request\n");
789 if (!noout && x509 && (x509ss != NULL)) {
790 if (outformat == FORMAT_ASN1)
791 i = i2d_X509_bio(out, x509ss);
793 i = PEM_write_bio_X509(out, x509ss);
795 BIO_printf(bio_err, "unable to write X509 certificate\n");
802 ERR_print_errors(bio_err);
804 NCONF_free(req_conf);
808 EVP_PKEY_CTX_free(genctx);
809 sk_OPENSSL_STRING_free(pkeyopts);
810 sk_OPENSSL_STRING_free(sigopts);
811 #ifndef OPENSSL_NO_ENGINE
812 ENGINE_free(gen_eng);
814 OPENSSL_free(keyalgstr);
817 ASN1_INTEGER_free(serial);
818 if (passin != nofree_passin)
819 OPENSSL_free(passin);
820 if (passout != nofree_passout)
821 OPENSSL_free(passout);
825 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
826 int attribs, unsigned long chtype)
830 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
831 char *tmp, *dn_sect, *attr_sect;
833 tmp = NCONF_get_string(req_conf, SECTION, PROMPT);
836 if ((tmp != NULL) && strcmp(tmp, "no") == 0)
839 dn_sect = NCONF_get_string(req_conf, SECTION, DISTINGUISHED_NAME);
840 if (dn_sect == NULL) {
841 BIO_printf(bio_err, "unable to find '%s' in config\n",
845 dn_sk = NCONF_get_section(req_conf, dn_sect);
847 BIO_printf(bio_err, "unable to get '%s' section\n", dn_sect);
851 attr_sect = NCONF_get_string(req_conf, SECTION, ATTRIBUTES);
852 if (attr_sect == NULL) {
856 attr_sk = NCONF_get_section(req_conf, attr_sect);
857 if (attr_sk == NULL) {
858 BIO_printf(bio_err, "unable to get '%s' section\n", attr_sect);
863 /* setup version number */
864 if (!X509_REQ_set_version(req, 0L))
865 goto err; /* version 1 */
868 i = build_subject(req, subj, chtype, multirdn);
870 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
872 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs,
877 if (!X509_REQ_set_pubkey(req, pkey))
886 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
887 * where characters may be escaped by \
889 static int build_subject(X509_REQ *req, char *subject, unsigned long chtype,
894 if ((n = parse_name(subject, chtype, multirdn)) == NULL)
897 if (!X509_REQ_set_subject_name(req, n)) {
905 static int prompt_info(X509_REQ *req,
906 STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
907 STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect,
908 int attribs, unsigned long chtype)
919 subj = X509_REQ_get_subject_name(req);
923 "You are about to be asked to enter information that will be incorporated\n");
924 BIO_printf(bio_err, "into your certificate request.\n");
926 "What you are about to enter is what is called a Distinguished Name or a DN.\n");
928 "There are quite a few fields but you can leave some blank\n");
930 "For some fields there will be a default value,\n");
932 "If you enter '.', the field will be left blank.\n");
933 BIO_printf(bio_err, "-----\n");
936 if (sk_CONF_VALUE_num(dn_sk)) {
940 if (sk_CONF_VALUE_num(dn_sk) <= i)
943 v = sk_CONF_VALUE_value(dn_sk, i);
946 if (!check_end(type, "_min") || !check_end(type, "_max") ||
947 !check_end(type, "_default") || !check_end(type, "_value"))
950 * Skip past any leading X. X: X, etc to allow for multiple
953 for (p = v->name; *p; p++)
954 if ((*p == ':') || (*p == ',') || (*p == '.')) {
965 /* If OBJ not recognised ignore it */
966 if ((nid = OBJ_txt2nid(type)) == NID_undef)
968 if (BIO_snprintf(buf, sizeof buf, "%s_default", v->name)
969 >= (int)sizeof(buf)) {
970 BIO_printf(bio_err, "Name '%s' too long\n", v->name);
974 if ((def = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
979 BIO_snprintf(buf, sizeof buf, "%s_value", v->name);
980 if ((value = NCONF_get_string(req_conf, dn_sect, buf)) == NULL) {
985 BIO_snprintf(buf, sizeof buf, "%s_min", v->name);
986 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_min)) {
991 BIO_snprintf(buf, sizeof buf, "%s_max", v->name);
992 if (!NCONF_get_number(req_conf, dn_sect, buf, &n_max)) {
997 if (!add_DN_object(subj, v->value, def, value, nid,
998 n_min, n_max, chtype, mval))
1001 if (X509_NAME_entry_count(subj) == 0) {
1003 "error, no objects specified in config file\n");
1008 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0)
1011 "\nPlease enter the following 'extra' attributes\n");
1013 "to be sent with your certificate request\n");
1019 if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i))
1022 v = sk_CONF_VALUE_value(attr_sk, i);
1024 if ((nid = OBJ_txt2nid(type)) == NID_undef)
1027 if (BIO_snprintf(buf, sizeof buf, "%s_default", type)
1028 >= (int)sizeof(buf)) {
1029 BIO_printf(bio_err, "Name '%s' too long\n", v->name);
1033 if ((def = NCONF_get_string(req_conf, attr_sect, buf))
1039 BIO_snprintf(buf, sizeof buf, "%s_value", type);
1040 if ((value = NCONF_get_string(req_conf, attr_sect, buf))
1046 BIO_snprintf(buf, sizeof buf, "%s_min", type);
1047 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_min)) {
1052 BIO_snprintf(buf, sizeof buf, "%s_max", type);
1053 if (!NCONF_get_number(req_conf, attr_sect, buf, &n_max)) {
1058 if (!add_attribute_object(req,
1059 v->value, def, value, nid, n_min,
1065 BIO_printf(bio_err, "No template, please set one up.\n");
1073 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1074 STACK_OF(CONF_VALUE) *attr_sk, int attribs,
1075 unsigned long chtype)
1077 int i, spec_char, plus_char;
1083 subj = X509_REQ_get_subject_name(req);
1085 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
1087 v = sk_CONF_VALUE_value(dn_sk, i);
1091 * Skip past any leading X. X: X, etc to allow for multiple instances
1093 for (p = v->name; *p; p++) {
1094 #ifndef CHARSET_EBCDIC
1095 spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
1097 spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
1098 || (*p == os_toascii['.']));
1107 #ifndef CHARSET_EBCDIC
1108 plus_char = (*p == '+');
1110 plus_char = (*p == os_toascii['+']);
1117 if (!X509_NAME_add_entry_by_txt(subj, type, chtype,
1118 (unsigned char *)v->value, -1, -1,
1124 if (!X509_NAME_entry_count(subj)) {
1125 BIO_printf(bio_err, "error, no objects specified in config file\n");
1129 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
1130 v = sk_CONF_VALUE_value(attr_sk, i);
1131 if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1132 (unsigned char *)v->value, -1))
1139 static int add_DN_object(X509_NAME *n, char *text, const char *def,
1140 char *value, int nid, int n_min, int n_max,
1141 unsigned long chtype, int mval)
1147 BIO_printf(bio_err, "%s [%s]:", text, def);
1148 (void)BIO_flush(bio_err);
1149 if (value != NULL) {
1150 OPENSSL_strlcpy(buf, value, sizeof buf);
1151 OPENSSL_strlcat(buf, "\n", sizeof buf);
1152 BIO_printf(bio_err, "%s\n", value);
1156 if (!fgets(buf, sizeof buf, stdin))
1166 else if (buf[0] == '\n') {
1167 if ((def == NULL) || (def[0] == '\0'))
1169 OPENSSL_strlcpy(buf, def, sizeof buf);
1170 OPENSSL_strlcat(buf, "\n", sizeof buf);
1171 } else if ((buf[0] == '.') && (buf[1] == '\n'))
1175 if (buf[i - 1] != '\n') {
1176 BIO_printf(bio_err, "weird input :-(\n");
1180 #ifdef CHARSET_EBCDIC
1181 ebcdic2ascii(buf, buf, i);
1183 if (!req_check_len(i, n_min, n_max)) {
1189 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1190 (unsigned char *)buf, -1, -1, mval))
1197 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1198 char *value, int nid, int n_min,
1199 int n_max, unsigned long chtype)
1202 static char buf[1024];
1206 BIO_printf(bio_err, "%s [%s]:", text, def);
1207 (void)BIO_flush(bio_err);
1208 if (value != NULL) {
1209 OPENSSL_strlcpy(buf, value, sizeof buf);
1210 OPENSSL_strlcat(buf, "\n", sizeof buf);
1211 BIO_printf(bio_err, "%s\n", value);
1215 if (!fgets(buf, sizeof buf, stdin))
1225 else if (buf[0] == '\n') {
1226 if ((def == NULL) || (def[0] == '\0'))
1228 OPENSSL_strlcpy(buf, def, sizeof buf);
1229 OPENSSL_strlcat(buf, "\n", sizeof buf);
1230 } else if ((buf[0] == '.') && (buf[1] == '\n'))
1234 if (buf[i - 1] != '\n') {
1235 BIO_printf(bio_err, "weird input :-(\n");
1239 #ifdef CHARSET_EBCDIC
1240 ebcdic2ascii(buf, buf, i);
1242 if (!req_check_len(i, n_min, n_max)) {
1248 if (!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1249 (unsigned char *)buf, -1)) {
1250 BIO_printf(bio_err, "Error adding attribute\n");
1251 ERR_print_errors(bio_err);
1260 static int req_check_len(int len, int n_min, int n_max)
1262 if ((n_min > 0) && (len < n_min)) {
1264 "string is too short, it needs to be at least %d bytes long\n",
1268 if ((n_max >= 0) && (len > n_max)) {
1270 "string is too long, it needs to be less than %d bytes long\n",
1277 /* Check if the end of a string matches 'end' */
1278 static int check_end(const char *str, const char *end)
1286 tmp = str + slen - elen;
1287 return strcmp(tmp, end);
1290 static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr,
1291 int *pkey_type, long *pkeylen,
1292 char **palgnam, ENGINE *keygen_engine)
1294 EVP_PKEY_CTX *gctx = NULL;
1295 EVP_PKEY *param = NULL;
1298 const char *paramfile = NULL;
1301 *pkey_type = EVP_PKEY_RSA;
1303 } else if (gstr[0] >= '0' && gstr[0] <= '9') {
1304 *pkey_type = EVP_PKEY_RSA;
1305 keylen = atol(gstr);
1307 } else if (strncmp(gstr, "param:", 6) == 0)
1308 paramfile = gstr + 6;
1310 const char *p = strchr(gstr, ':');
1313 const EVP_PKEY_ASN1_METHOD *ameth;
1320 * The lookup of a the string will cover all engines so keep a note
1321 * of the implementation.
1324 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1327 BIO_printf(bio_err, "Unknown algorithm %.*s\n", len, gstr);
1331 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL, ameth);
1332 #ifndef OPENSSL_NO_ENGINE
1333 ENGINE_finish(tmpeng);
1335 if (*pkey_type == EVP_PKEY_RSA) {
1337 keylen = atol(p + 1);
1346 pbio = BIO_new_file(paramfile, "r");
1348 BIO_printf(bio_err, "Can't open parameter file %s\n", paramfile);
1351 param = PEM_read_bio_Parameters(pbio, NULL);
1355 (void)BIO_reset(pbio);
1356 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1358 param = X509_get_pubkey(x);
1366 BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile);
1369 if (*pkey_type == -1)
1370 *pkey_type = EVP_PKEY_id(param);
1371 else if (*pkey_type != EVP_PKEY_base_id(param)) {
1372 BIO_printf(bio_err, "Key Type does not match parameters\n");
1373 EVP_PKEY_free(param);
1379 const EVP_PKEY_ASN1_METHOD *ameth;
1382 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1384 BIO_puts(bio_err, "Internal error: can't find key algorithm\n");
1387 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1388 *palgnam = OPENSSL_strdup(anam);
1389 #ifndef OPENSSL_NO_ENGINE
1390 ENGINE_finish(tmpeng);
1395 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1396 *pkeylen = EVP_PKEY_bits(param);
1397 EVP_PKEY_free(param);
1399 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1402 BIO_puts(bio_err, "Error allocating keygen context\n");
1403 ERR_print_errors(bio_err);
1407 if (EVP_PKEY_keygen_init(gctx) <= 0) {
1408 BIO_puts(bio_err, "Error initializing keygen context\n");
1409 ERR_print_errors(bio_err);
1410 EVP_PKEY_CTX_free(gctx);
1413 #ifndef OPENSSL_NO_RSA
1414 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1)) {
1415 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0) {
1416 BIO_puts(bio_err, "Error setting RSA keysize\n");
1417 ERR_print_errors(bio_err);
1418 EVP_PKEY_CTX_free(gctx);
1427 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1430 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1432 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1441 BIO_write(b, &c, 1);
1446 static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1447 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1449 EVP_PKEY_CTX *pkctx = NULL;
1454 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1456 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) {
1457 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1458 if (pkey_ctrl_string(pkctx, sigopt) <= 0) {
1459 BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt);
1460 ERR_print_errors(bio_err);
1467 int do_X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1468 STACK_OF(OPENSSL_STRING) *sigopts)
1471 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1473 rv = do_sign_init(mctx, pkey, md, sigopts);
1475 rv = X509_sign_ctx(x, mctx);
1476 EVP_MD_CTX_free(mctx);
1477 return rv > 0 ? 1 : 0;
1480 int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1481 STACK_OF(OPENSSL_STRING) *sigopts)
1484 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1485 rv = do_sign_init(mctx, pkey, md, sigopts);
1487 rv = X509_REQ_sign_ctx(x, mctx);
1488 EVP_MD_CTX_free(mctx);
1489 return rv > 0 ? 1 : 0;
1492 int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1493 STACK_OF(OPENSSL_STRING) *sigopts)
1496 EVP_MD_CTX *mctx = EVP_MD_CTX_new();
1497 rv = do_sign_init(mctx, pkey, md, sigopts);
1499 rv = X509_CRL_sign_ctx(x, mctx);
1500 EVP_MD_CTX_free(mctx);
1501 return rv > 0 ? 1 : 0;