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
10 /* The PPKI stuff has been donated by Jeff Barber <jeffb@issl.atl.hp.com> */
16 #include <sys/types.h>
17 #include <openssl/conf.h>
18 #include <openssl/bio.h>
19 #include <openssl/err.h>
20 #include <openssl/bn.h>
21 #include <openssl/txt_db.h>
22 #include <openssl/evp.h>
23 #include <openssl/x509.h>
24 #include <openssl/x509v3.h>
25 #include <openssl/objects.h>
26 #include <openssl/ocsp.h>
27 #include <openssl/pem.h>
30 # ifdef OPENSSL_SYS_VMS
36 # elif !defined(OPENSSL_SYS_VXWORKS) && !defined(OPENSSL_SYS_WINDOWS)
37 # include <sys/file.h>
53 #define BASE_SECTION "ca"
55 #define ENV_DEFAULT_CA "default_ca"
57 #define STRING_MASK "string_mask"
58 #define UTF8_IN "utf8"
60 #define ENV_NEW_CERTS_DIR "new_certs_dir"
61 #define ENV_CERTIFICATE "certificate"
62 #define ENV_SERIAL "serial"
63 #define ENV_CRLNUMBER "crlnumber"
64 #define ENV_PRIVATE_KEY "private_key"
65 #define ENV_DEFAULT_DAYS "default_days"
66 #define ENV_DEFAULT_STARTDATE "default_startdate"
67 #define ENV_DEFAULT_ENDDATE "default_enddate"
68 #define ENV_DEFAULT_CRL_DAYS "default_crl_days"
69 #define ENV_DEFAULT_CRL_HOURS "default_crl_hours"
70 #define ENV_DEFAULT_MD "default_md"
71 #define ENV_DEFAULT_EMAIL_DN "email_in_dn"
72 #define ENV_PRESERVE "preserve"
73 #define ENV_POLICY "policy"
74 #define ENV_EXTENSIONS "x509_extensions"
75 #define ENV_CRLEXT "crl_extensions"
76 #define ENV_MSIE_HACK "msie_hack"
77 #define ENV_NAMEOPT "name_opt"
78 #define ENV_CERTOPT "cert_opt"
79 #define ENV_EXTCOPY "copy_extensions"
80 #define ENV_UNIQUE_SUBJECT "unique_subject"
82 #define ENV_DATABASE "database"
84 /* Additional revocation information types */
86 #define REV_NONE 0 /* No addditional information */
87 #define REV_CRL_REASON 1 /* Value is CRL reason code */
88 #define REV_HOLD 2 /* Value is hold instruction */
89 #define REV_KEY_COMPROMISE 3 /* Value is cert key compromise time */
90 #define REV_CA_COMPROMISE 4 /* Value is CA key compromise time */
92 static void lookup_fail(const char *name, const char *tag);
93 static int certify(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509,
94 const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
95 STACK_OF(CONF_VALUE) *policy, CA_DB *db,
96 BIGNUM *serial, char *subj, unsigned long chtype,
97 int multirdn, int email_dn, char *startdate, char *enddate,
98 long days, int batch, char *ext_sect, CONF *conf,
99 int verbose, unsigned long certopt, unsigned long nameopt,
100 int default_op, int ext_copy, int selfsign);
101 static int certify_cert(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509,
102 const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
103 STACK_OF(CONF_VALUE) *policy, CA_DB *db,
104 BIGNUM *serial, char *subj, unsigned long chtype,
105 int multirdn, int email_dn, char *startdate,
106 char *enddate, long days, int batch, char *ext_sect,
107 CONF *conf, int verbose, unsigned long certopt,
108 unsigned long nameopt, int default_op, int ext_copy);
109 static int certify_spkac(X509 **xret, char *infile, EVP_PKEY *pkey,
110 X509 *x509, const EVP_MD *dgst,
111 STACK_OF(OPENSSL_STRING) *sigopts,
112 STACK_OF(CONF_VALUE) *policy, CA_DB *db,
113 BIGNUM *serial, char *subj, unsigned long chtype,
114 int multirdn, int email_dn, char *startdate,
115 char *enddate, long days, char *ext_sect, CONF *conf,
116 int verbose, unsigned long certopt,
117 unsigned long nameopt, int default_op, int ext_copy);
118 static void write_new_certificate(BIO *bp, X509 *x, int output_der,
120 static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509,
121 const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
122 STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial,
123 char *subj, unsigned long chtype, int multirdn,
124 int email_dn, char *startdate, char *enddate, long days,
125 int batch, int verbose, X509_REQ *req, char *ext_sect,
126 CONF *conf, unsigned long certopt, unsigned long nameopt,
127 int default_op, int ext_copy, int selfsign);
128 static int do_revoke(X509 *x509, CA_DB *db, int ext, char *extval);
129 static int get_certificate_status(const char *ser_status, CA_DB *db);
130 static int do_updatedb(CA_DB *db);
131 static int check_time_format(const char *str);
132 char *make_revocation_str(int rev_type, char *rev_arg);
133 int make_revoked(X509_REVOKED *rev, const char *str);
134 static int old_entry_print(ASN1_OBJECT *obj, ASN1_STRING *str);
136 static CONF *conf = NULL;
137 static CONF *extconf = NULL;
138 static char *section = NULL;
139 static int preserve = 0;
140 static int msie_hack = 0;
142 typedef enum OPTION_choice {
143 OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
144 OPT_ENGINE, OPT_VERBOSE, OPT_CONFIG, OPT_NAME, OPT_SUBJ, OPT_UTF8,
145 OPT_CREATE_SERIAL, OPT_MULTIVALUE_RDN, OPT_STARTDATE, OPT_ENDDATE,
146 OPT_DAYS, OPT_MD, OPT_POLICY, OPT_KEYFILE, OPT_KEYFORM, OPT_PASSIN,
147 OPT_KEY, OPT_CERT, OPT_SELFSIGN, OPT_IN, OPT_OUT, OPT_OUTDIR,
148 OPT_SIGOPT, OPT_NOTEXT, OPT_BATCH, OPT_PRESERVEDN, OPT_NOEMAILDN,
149 OPT_GENCRL, OPT_MSIE_HACK, OPT_CRLDAYS, OPT_CRLHOURS, OPT_CRLSEC,
150 OPT_INFILES, OPT_SS_CERT, OPT_SPKAC, OPT_REVOKE, OPT_VALID,
151 OPT_EXTENSIONS, OPT_EXTFILE, OPT_STATUS, OPT_UPDATEDB, OPT_CRLEXTS,
152 OPT_CRL_REASON, OPT_CRL_HOLD, OPT_CRL_COMPROMISE,
153 OPT_CRL_CA_COMPROMISE
156 OPTIONS ca_options[] = {
157 {"help", OPT_HELP, '-', "Display this summary"},
158 {"verbose", OPT_VERBOSE, '-', "Verbose output during processing"},
159 {"config", OPT_CONFIG, 's', "A config file"},
160 {"name", OPT_NAME, 's', "The particular CA definition to use"},
161 {"subj", OPT_SUBJ, 's', "Use arg instead of request's subject"},
162 {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
163 {"create_serial", OPT_CREATE_SERIAL, '-',
164 "If reading serial fails, create a new random serial"},
165 {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
166 "Enable support for multivalued RDNs"},
167 {"startdate", OPT_STARTDATE, 's', "Cert notBefore, YYMMDDHHMMSSZ"},
168 {"enddate", OPT_ENDDATE, 's',
169 "YYMMDDHHMMSSZ cert notAfter (overrides -days)"},
170 {"days", OPT_DAYS, 'p', "Number of days to certify the cert for"},
171 {"md", OPT_MD, 's', "md to use; one of md2, md5, sha or sha1"},
172 {"policy", OPT_POLICY, 's', "The CA 'policy' to support"},
173 {"keyfile", OPT_KEYFILE, 's', "Private key"},
174 {"keyform", OPT_KEYFORM, 'f', "Private key file format (PEM or ENGINE)"},
175 {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
176 {"key", OPT_KEY, 's', "Key to decode the private key if it is encrypted"},
177 {"cert", OPT_CERT, '<', "The CA cert"},
178 {"selfsign", OPT_SELFSIGN, '-',
179 "Sign a cert with the key associated with it"},
180 {"in", OPT_IN, '<', "The input PEM encoded cert request(s)"},
181 {"out", OPT_OUT, '>', "Where to put the output file(s)"},
182 {"outdir", OPT_OUTDIR, '/', "Where to put output cert"},
183 {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
184 {"notext", OPT_NOTEXT, '-', "Do not print the generated certificate"},
185 {"batch", OPT_BATCH, '-', "Don't ask questions"},
186 {"preserveDN", OPT_PRESERVEDN, '-', "Don't re-order the DN"},
187 {"noemailDN", OPT_NOEMAILDN, '-', "Don't add the EMAIL field to the DN"},
188 {"gencrl", OPT_GENCRL, '-', "Generate a new CRL"},
189 {"msie_hack", OPT_MSIE_HACK, '-',
190 "msie modifications to handle all those universal strings"},
191 {"crldays", OPT_CRLDAYS, 'p', "Days until the next CRL is due"},
192 {"crlhours", OPT_CRLHOURS, 'p', "Hours until the next CRL is due"},
193 {"crlsec", OPT_CRLSEC, 'p', "Seconds until the next CRL is due"},
194 {"infiles", OPT_INFILES, '-', "The last argument, requests to process"},
195 {"ss_cert", OPT_SS_CERT, '<', "File contains a self signed cert to sign"},
196 {"spkac", OPT_SPKAC, '<',
197 "File contains DN and signed public key and challenge"},
198 {"revoke", OPT_REVOKE, '<', "Revoke a cert (given in file)"},
199 {"valid", OPT_VALID, 's'},
200 {"extensions", OPT_EXTENSIONS, 's',
201 "Extension section (override value in config file)"},
202 {"extfile", OPT_EXTFILE, '<',
203 "Configuration file with X509v3 extensions to add"},
204 {"status", OPT_STATUS, 's', "Shows cert status given the serial number"},
205 {"updatedb", OPT_UPDATEDB, '-', "Updates db for expired cert"},
206 {"crlexts", OPT_CRLEXTS, 's',
207 "CRL extension section (override value in config file)"},
208 {"crl_reason", OPT_CRL_REASON, 's', "revocation reason"},
209 {"crl_hold", OPT_CRL_HOLD, 's',
210 "the hold instruction, an OID. Sets revocation reason to certificateHold"},
211 {"crl_compromise", OPT_CRL_COMPROMISE, 's',
212 "sets compromise time to val and the revocation reason to keyCompromise"},
213 {"crl_CA_compromise", OPT_CRL_CA_COMPROMISE, 's',
214 "sets compromise time to val and the revocation reason to CACompromise"},
215 #ifndef OPENSSL_NO_ENGINE
216 {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
221 int ca_main(int argc, char **argv)
224 BIGNUM *crlnumber = NULL, *serial = NULL;
225 EVP_PKEY *pkey = NULL;
226 BIO *in = NULL, *out = NULL, *Sout = NULL, *Cout = NULL;
227 ASN1_INTEGER *tmpser;
231 STACK_OF(CONF_VALUE) *attribs = NULL;
232 STACK_OF(OPENSSL_STRING) *sigopts = NULL;
233 STACK_OF(X509) *cert_sk = NULL;
234 X509_CRL *crl = NULL;
235 const EVP_MD *dgst = NULL;
236 char *configfile = default_config_file;
237 char *md = NULL, *policy = NULL, *keyfile = NULL;
238 char *certfile = NULL, *crl_ext = NULL, *crlnumberfile = NULL;
239 char *infile = NULL, *spkac_file = NULL, *ss_cert_file = NULL;
240 char *extensions = NULL, *extfile = NULL, *key = NULL, *passinarg = NULL;
241 char *outdir = NULL, *outfile = NULL, *rev_arg = NULL, *ser_status = NULL;
242 char *serialfile = NULL, *startdate = NULL, *subj = NULL;
243 char *prog, *enddate = NULL, *tmp_email_dn = NULL;
244 char *dbfile = NULL, *f, *randfile = NULL, *tofree = NULL;
248 int create_ser = 0, free_key = 0, total = 0, total_done = 0;
249 int batch = 0, default_op = 1, doupdatedb = 0, ext_copy = EXT_COPY_NONE;
250 int keyformat = FORMAT_PEM, multirdn = 0, notext = 0, output_der = 0;
251 int ret = 1, email_dn = 1, req = 0, verbose = 0, gencrl = 0, dorevoke = 0;
252 int i, j, rev_type = REV_NONE, selfsign = 0;
253 long crldays = 0, crlhours = 0, crlsec = 0, days = 0;
254 unsigned long chtype = MBSTRING_ASC, nameopt = 0, certopt = 0;
255 X509 *x509 = NULL, *x509p = NULL, *x = NULL;
256 X509_REVOKED *r = NULL;
259 prog = opt_init(argc, argv, ca_options);
260 while ((o = opt_next()) != OPT_EOF) {
265 BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
268 opt_help(ca_options);
282 configfile = opt_arg();
292 chtype = MBSTRING_UTF8;
294 case OPT_CREATE_SERIAL:
297 case OPT_MULTIVALUE_RDN:
301 startdate = opt_arg();
307 days = atoi(opt_arg());
319 if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat))
323 passinarg = opt_arg();
329 certfile = opt_arg();
339 sigopts = sk_OPENSSL_STRING_new_null();
341 || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
363 crldays = atol(opt_arg());
366 crlhours = atol(opt_arg());
369 crlsec = atol(opt_arg());
375 ss_cert_file = opt_arg();
379 spkac_file = opt_arg();
391 extensions = opt_arg();
397 ser_status = opt_arg();
407 rev_type = REV_CRL_REASON;
413 case OPT_CRL_COMPROMISE:
415 rev_type = REV_KEY_COMPROMISE;
417 case OPT_CRL_CA_COMPROMISE:
419 rev_type = REV_CA_COMPROMISE;
422 e = setup_engine(opt_arg(), 0);
427 argc = opt_num_rest();
430 BIO_printf(bio_err, "Using configuration from %s\n", configfile);
432 if ((conf = app_load_config(configfile)) == NULL)
434 if (configfile != default_config_file && !app_load_modules(conf))
437 /* Lets get the config section we are using */
438 if (section == NULL) {
439 section = NCONF_get_string(conf, BASE_SECTION, ENV_DEFAULT_CA);
440 if (section == NULL) {
441 lookup_fail(BASE_SECTION, ENV_DEFAULT_CA);
447 p = NCONF_get_string(conf, NULL, "oid_file");
453 oid_bio = BIO_new_file(p, "r");
454 if (oid_bio == NULL) {
456 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
457 ERR_print_errors(bio_err);
461 OBJ_create_objects(oid_bio);
465 if (!add_oid_section(conf)) {
466 ERR_print_errors(bio_err);
471 randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE");
472 if (randfile == NULL)
474 app_RAND_load_file(randfile, 0);
476 f = NCONF_get_string(conf, section, STRING_MASK);
480 if (f && !ASN1_STRING_set_default_mask_asc(f)) {
481 BIO_printf(bio_err, "Invalid global string mask setting %s\n", f);
485 if (chtype != MBSTRING_UTF8) {
486 f = NCONF_get_string(conf, section, UTF8_IN);
489 else if (strcmp(f, "yes") == 0)
490 chtype = MBSTRING_UTF8;
493 db_attr.unique_subject = 1;
494 p = NCONF_get_string(conf, section, ENV_UNIQUE_SUBJECT);
496 db_attr.unique_subject = parse_yesno(p, 1);
500 /*****************************************************************/
501 /* report status of cert with serial number given on command line */
503 if ((dbfile = NCONF_get_string(conf, section, ENV_DATABASE)) == NULL) {
504 lookup_fail(section, ENV_DATABASE);
507 db = load_index(dbfile, &db_attr);
511 if (!index_index(db))
514 if (get_certificate_status(ser_status, db) != 1)
515 BIO_printf(bio_err, "Error verifying serial %s!\n", ser_status);
519 /*****************************************************************/
520 /* we definitely need a private key, so let's get it */
522 if ((keyfile == NULL) && ((keyfile = NCONF_get_string(conf,
526 lookup_fail(section, ENV_PRIVATE_KEY);
531 if (!app_passwd(passinarg, NULL, &key, NULL)) {
532 BIO_printf(bio_err, "Error getting password\n");
536 pkey = load_key(keyfile, keyformat, 0, key, e, "CA private key");
538 OPENSSL_cleanse(key, strlen(key));
540 /* load_key() has already printed an appropriate message */
544 /*****************************************************************/
545 /* we need a certificate */
546 if (!selfsign || spkac_file || ss_cert_file || gencrl) {
547 if ((certfile == NULL)
548 && ((certfile = NCONF_get_string(conf,
550 ENV_CERTIFICATE)) == NULL)) {
551 lookup_fail(section, ENV_CERTIFICATE);
554 x509 = load_cert(certfile, FORMAT_PEM, "CA certificate");
558 if (!X509_check_private_key(x509, pkey)) {
560 "CA certificate and CA private key do not match\n");
567 f = NCONF_get_string(conf, BASE_SECTION, ENV_PRESERVE);
570 if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
572 f = NCONF_get_string(conf, BASE_SECTION, ENV_MSIE_HACK);
575 if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
578 f = NCONF_get_string(conf, section, ENV_NAMEOPT);
581 if (!set_name_ex(&nameopt, f)) {
582 BIO_printf(bio_err, "Invalid name options: \"%s\"\n", f);
587 nameopt = XN_FLAG_ONELINE;
591 f = NCONF_get_string(conf, section, ENV_CERTOPT);
594 if (!set_cert_ex(&certopt, f)) {
595 BIO_printf(bio_err, "Invalid certificate options: \"%s\"\n", f);
602 f = NCONF_get_string(conf, section, ENV_EXTCOPY);
605 if (!set_ext_copy(&ext_copy, f)) {
606 BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n", f);
612 /*****************************************************************/
613 /* lookup where to write new certificates */
614 if ((outdir == NULL) && (req)) {
616 if ((outdir = NCONF_get_string(conf, section, ENV_NEW_CERTS_DIR))
619 "there needs to be defined a directory for new certificate to be placed in\n");
622 #ifndef OPENSSL_SYS_VMS
624 * outdir is a directory spec, but access() for VMS demands a
625 * filename. We could use the DEC C routine to convert the
626 * directory syntax to Unixly, and give that to app_isdir,
627 * but for now the fopen will catch the error if it's not a
630 if (app_isdir(outdir) <= 0) {
631 BIO_printf(bio_err, "%s: %s is not a directory\n", prog, outdir);
638 /*****************************************************************/
639 /* we need to load the database file */
640 if ((dbfile = NCONF_get_string(conf, section, ENV_DATABASE)) == NULL) {
641 lookup_fail(section, ENV_DATABASE);
644 db = load_index(dbfile, &db_attr);
648 /* Lets check some fields */
649 for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
650 pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
651 if ((pp[DB_type][0] != DB_TYPE_REV) && (pp[DB_rev_date][0] != '\0')) {
653 "entry %d: not revoked yet, but has a revocation date\n",
657 if ((pp[DB_type][0] == DB_TYPE_REV) &&
658 !make_revoked(NULL, pp[DB_rev_date])) {
659 BIO_printf(bio_err, " in entry %d\n", i + 1);
662 if (!check_time_format((char *)pp[DB_exp_date])) {
663 BIO_printf(bio_err, "entry %d: invalid expiry date\n", i + 1);
672 if ((j & 1) || (j < 2)) {
673 BIO_printf(bio_err, "entry %d: bad serial number length (%d)\n",
678 if (!isxdigit(_UC(*p))) {
680 "entry %d: bad char 0%o '%c' in serial number\n",
687 TXT_DB_write(bio_out, db->db);
688 BIO_printf(bio_err, "%d entries loaded from the database\n",
689 sk_OPENSSL_PSTRING_num(db->db->data));
690 BIO_printf(bio_err, "generating index\n");
693 if (!index_index(db))
696 /*****************************************************************/
697 /* Update the db file for expired certificates */
700 BIO_printf(bio_err, "Updating %s ...\n", dbfile);
704 BIO_printf(bio_err, "Malloc failure\n");
708 BIO_printf(bio_err, "No entries found to mark expired\n");
710 if (!save_index(dbfile, "new", db))
713 if (!rotate_index(dbfile, "new", "old"))
718 "Done. %d entries marked as expired\n", i);
722 /*****************************************************************/
723 /* Read extensions config file */
725 if ((extconf = app_load_config(extfile)) == NULL) {
731 BIO_printf(bio_err, "Successfully loaded extensions file %s\n",
734 /* We can have sections in the ext file */
737 NCONF_get_string(extconf, "default", "extensions")))
738 extensions = "default";
741 /*****************************************************************/
743 /* FIXME: Is it really always text? */
744 Sout = bio_open_default(outfile, 'w', FORMAT_TEXT);
749 if ((md == NULL) && ((md = NCONF_get_string(conf,
751 ENV_DEFAULT_MD)) == NULL)) {
752 lookup_fail(section, ENV_DEFAULT_MD);
756 if (strcmp(md, "default") == 0) {
758 if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) <= 0) {
759 BIO_puts(bio_err, "no default digest\n");
762 md = (char *)OBJ_nid2sn(def_nid);
765 if (!opt_md(md, &dgst)) {
770 if ((email_dn == 1) && ((tmp_email_dn = NCONF_get_string(conf,
772 ENV_DEFAULT_EMAIL_DN))
774 if (strcmp(tmp_email_dn, "no") == 0)
778 BIO_printf(bio_err, "message digest is %s\n",
779 OBJ_nid2ln(EVP_MD_type(dgst)));
780 if ((policy == NULL) && ((policy = NCONF_get_string(conf,
784 lookup_fail(section, ENV_POLICY);
788 BIO_printf(bio_err, "policy is %s\n", policy);
790 if ((serialfile = NCONF_get_string(conf, section, ENV_SERIAL))
792 lookup_fail(section, ENV_SERIAL);
798 * no '-extfile' option, so we look for extensions in the main
802 extensions = NCONF_get_string(conf, section, ENV_EXTENSIONS);
807 /* Check syntax of file */
809 X509V3_set_ctx_test(&ctx);
810 X509V3_set_nconf(&ctx, conf);
811 if (!X509V3_EXT_add_nconf(conf, &ctx, extensions, NULL)) {
813 "Error Loading extension section %s\n",
821 if (startdate == NULL) {
822 startdate = NCONF_get_string(conf, section,
823 ENV_DEFAULT_STARTDATE);
824 if (startdate == NULL)
827 if (startdate && !ASN1_TIME_set_string(NULL, startdate)) {
829 "start date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n");
832 if (startdate == NULL)
835 if (enddate == NULL) {
836 enddate = NCONF_get_string(conf, section, ENV_DEFAULT_ENDDATE);
840 if (enddate && !ASN1_TIME_set_string(NULL, enddate)) {
842 "end date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n");
847 if (!NCONF_get_number(conf, section, ENV_DEFAULT_DAYS, &days))
850 if (!enddate && (days == 0)) {
852 "cannot lookup how many days to certify for\n");
856 if ((serial = load_serial(serialfile, create_ser, NULL)) == NULL) {
857 BIO_printf(bio_err, "error while loading serial number\n");
861 if (BN_is_zero(serial))
862 BIO_printf(bio_err, "next serial number is 00\n");
864 if ((f = BN_bn2hex(serial)) == NULL)
866 BIO_printf(bio_err, "next serial number is %s\n", f);
871 if ((attribs = NCONF_get_section(conf, policy)) == NULL) {
872 BIO_printf(bio_err, "unable to find 'section' for %s\n", policy);
876 if ((cert_sk = sk_X509_new_null()) == NULL) {
877 BIO_printf(bio_err, "Memory allocation failure\n");
880 if (spkac_file != NULL) {
882 j = certify_spkac(&x, spkac_file, pkey, x509, dgst, sigopts,
883 attribs, db, serial, subj, chtype, multirdn,
884 email_dn, startdate, enddate, days, extensions,
885 conf, verbose, certopt, nameopt, default_op,
891 BIO_printf(bio_err, "\n");
892 if (!BN_add_word(serial, 1))
894 if (!sk_X509_push(cert_sk, x)) {
895 BIO_printf(bio_err, "Memory allocation failure\n");
904 if (ss_cert_file != NULL) {
906 j = certify_cert(&x, ss_cert_file, pkey, x509, dgst, sigopts,
908 db, serial, subj, chtype, multirdn, email_dn,
909 startdate, enddate, days, batch, extensions,
910 conf, verbose, certopt, nameopt, default_op,
916 BIO_printf(bio_err, "\n");
917 if (!BN_add_word(serial, 1))
919 if (!sk_X509_push(cert_sk, x)) {
920 BIO_printf(bio_err, "Memory allocation failure\n");
925 if (infile != NULL) {
927 j = certify(&x, infile, pkey, x509p, dgst, sigopts, attribs, db,
928 serial, subj, chtype, multirdn, email_dn, startdate,
929 enddate, days, batch, extensions, conf, verbose,
930 certopt, nameopt, default_op, ext_copy, selfsign);
935 BIO_printf(bio_err, "\n");
936 if (!BN_add_word(serial, 1))
938 if (!sk_X509_push(cert_sk, x)) {
939 BIO_printf(bio_err, "Memory allocation failure\n");
944 for (i = 0; i < argc; i++) {
946 j = certify(&x, argv[i], pkey, x509p, dgst, sigopts, attribs, db,
947 serial, subj, chtype, multirdn, email_dn, startdate,
948 enddate, days, batch, extensions, conf, verbose,
949 certopt, nameopt, default_op, ext_copy, selfsign);
954 BIO_printf(bio_err, "\n");
955 if (!BN_add_word(serial, 1))
957 if (!sk_X509_push(cert_sk, x)) {
958 BIO_printf(bio_err, "Memory allocation failure\n");
964 * we have a stack of newly certified certificates and a data base
965 * and serial number that need updating
968 if (sk_X509_num(cert_sk) > 0) {
971 "\n%d out of %d certificate requests certified, commit? [y/n]",
973 (void)BIO_flush(bio_err);
975 if (!fgets(buf[0], 10, stdin)) {
977 "CERTIFICATION CANCELED: I/O error\n");
981 if ((buf[0][0] != 'y') && (buf[0][0] != 'Y')) {
982 BIO_printf(bio_err, "CERTIFICATION CANCELED\n");
988 BIO_printf(bio_err, "Write out database with %d new entries\n",
989 sk_X509_num(cert_sk));
991 if (!save_serial(serialfile, "new", serial, NULL))
994 if (!save_index(dbfile, "new", db))
999 BIO_printf(bio_err, "writing new certificates\n");
1000 for (i = 0; i < sk_X509_num(cert_sk); i++) {
1001 ASN1_INTEGER *serialNumber = X509_get_serialNumber(x);
1005 x = sk_X509_value(cert_sk, i);
1007 j = ASN1_STRING_length(serialNumber);
1008 p = (const char *)ASN1_STRING_data(serialNumber);
1010 if (strlen(outdir) >= (size_t)(j ? BSIZE - j * 2 - 6 : BSIZE - 8)) {
1011 BIO_printf(bio_err, "certificate file name too long\n");
1015 strcpy(buf[2], outdir);
1017 #ifndef OPENSSL_SYS_VMS
1018 OPENSSL_strlcat(buf[2], "/", sizeof(buf[2]));
1021 n = (char *)&(buf[2][strlen(buf[2])]);
1023 for (k = 0; k < j; k++) {
1024 if (n >= &(buf[2][sizeof(buf[2])]))
1027 &buf[2][0] + sizeof(buf[2]) - n,
1028 "%02X", (unsigned char)*(p++));
1041 BIO_printf(bio_err, "writing %s\n", buf[2]);
1043 Cout = BIO_new_file(buf[2], "w");
1048 write_new_certificate(Cout, x, 0, notext);
1049 write_new_certificate(Sout, x, output_der, notext);
1052 if (sk_X509_num(cert_sk)) {
1053 /* Rename the database and the serial file */
1054 if (!rotate_serial(serialfile, "new", "old"))
1057 if (!rotate_index(dbfile, "new", "old"))
1060 BIO_printf(bio_err, "Data Base Updated\n");
1064 /*****************************************************************/
1068 crl_ext = NCONF_get_string(conf, section, ENV_CRLEXT);
1073 /* Check syntax of file */
1075 X509V3_set_ctx_test(&ctx);
1076 X509V3_set_nconf(&ctx, conf);
1077 if (!X509V3_EXT_add_nconf(conf, &ctx, crl_ext, NULL)) {
1079 "Error Loading CRL extension section %s\n",
1086 if ((crlnumberfile = NCONF_get_string(conf, section, ENV_CRLNUMBER))
1088 if ((crlnumber = load_serial(crlnumberfile, 0, NULL)) == NULL) {
1089 BIO_printf(bio_err, "error while loading CRL number\n");
1093 if (!crldays && !crlhours && !crlsec) {
1094 if (!NCONF_get_number(conf, section,
1095 ENV_DEFAULT_CRL_DAYS, &crldays))
1097 if (!NCONF_get_number(conf, section,
1098 ENV_DEFAULT_CRL_HOURS, &crlhours))
1102 if ((crldays == 0) && (crlhours == 0) && (crlsec == 0)) {
1104 "cannot lookup how long until the next CRL is issued\n");
1109 BIO_printf(bio_err, "making CRL\n");
1110 if ((crl = X509_CRL_new()) == NULL)
1112 if (!X509_CRL_set_issuer_name(crl, X509_get_subject_name(x509)))
1115 tmptm = ASN1_TIME_new();
1118 X509_gmtime_adj(tmptm, 0);
1119 X509_CRL_set_lastUpdate(crl, tmptm);
1120 if (!X509_time_adj_ex(tmptm, crldays, crlhours * 60 * 60 + crlsec,
1122 BIO_puts(bio_err, "error setting CRL nextUpdate\n");
1125 X509_CRL_set_nextUpdate(crl, tmptm);
1127 ASN1_TIME_free(tmptm);
1129 for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
1130 pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
1131 if (pp[DB_type][0] == DB_TYPE_REV) {
1132 if ((r = X509_REVOKED_new()) == NULL)
1134 j = make_revoked(r, pp[DB_rev_date]);
1139 if (!BN_hex2bn(&serial, pp[DB_serial]))
1141 tmpser = BN_to_ASN1_INTEGER(serial, NULL);
1146 X509_REVOKED_set_serialNumber(r, tmpser);
1147 ASN1_INTEGER_free(tmpser);
1148 X509_CRL_add0_revoked(crl, r);
1153 * sort the data so it will be written in serial number order
1157 /* we now have a CRL */
1159 BIO_printf(bio_err, "signing CRL\n");
1161 /* Add any extensions asked for */
1163 if (crl_ext || crlnumberfile != NULL) {
1165 X509V3_set_ctx(&crlctx, x509, NULL, NULL, crl, 0);
1166 X509V3_set_nconf(&crlctx, conf);
1169 if (!X509V3_EXT_CRL_add_nconf(conf, &crlctx, crl_ext, crl))
1171 if (crlnumberfile != NULL) {
1172 tmpser = BN_to_ASN1_INTEGER(crlnumber, NULL);
1175 X509_CRL_add1_ext_i2d(crl, NID_crl_number, tmpser, 0, 0);
1176 ASN1_INTEGER_free(tmpser);
1178 if (!BN_add_word(crlnumber, 1))
1182 if (crl_ext || crl_v2) {
1183 if (!X509_CRL_set_version(crl, 1))
1184 goto end; /* version 2 CRL */
1187 /* we have a CRL number that need updating */
1188 if (crlnumberfile != NULL)
1189 if (!save_serial(crlnumberfile, "new", crlnumber, NULL))
1195 if (!do_X509_CRL_sign(crl, pkey, dgst, sigopts))
1198 PEM_write_bio_X509_CRL(Sout, crl);
1200 if (crlnumberfile != NULL) /* Rename the crlnumber file */
1201 if (!rotate_serial(crlnumberfile, "new", "old"))
1205 /*****************************************************************/
1207 if (infile == NULL) {
1208 BIO_printf(bio_err, "no input files\n");
1212 revcert = load_cert(infile, FORMAT_PEM, infile);
1213 if (revcert == NULL)
1217 j = do_revoke(revcert, db, rev_type, rev_arg);
1222 if (!save_index(dbfile, "new", db))
1225 if (!rotate_index(dbfile, "new", "old"))
1228 BIO_printf(bio_err, "Data Base Updated\n");
1231 /*****************************************************************/
1234 OPENSSL_free(tofree);
1239 sk_X509_pop_free(cert_sk, X509_free);
1242 ERR_print_errors(bio_err);
1243 app_RAND_write_file(randfile);
1249 sk_OPENSSL_STRING_free(sigopts);
1250 EVP_PKEY_free(pkey);
1254 NCONF_free(extconf);
1258 static void lookup_fail(const char *name, const char *tag)
1260 BIO_printf(bio_err, "variable lookup failed for %s::%s\n", name, tag);
1263 static int certify(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509,
1264 const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
1265 STACK_OF(CONF_VALUE) *policy, CA_DB *db,
1266 BIGNUM *serial, char *subj, unsigned long chtype,
1267 int multirdn, int email_dn, char *startdate, char *enddate,
1268 long days, int batch, char *ext_sect, CONF *lconf,
1269 int verbose, unsigned long certopt, unsigned long nameopt,
1270 int default_op, int ext_copy, int selfsign)
1272 X509_REQ *req = NULL;
1274 EVP_PKEY *pktmp = NULL;
1277 in = BIO_new_file(infile, "r");
1279 ERR_print_errors(bio_err);
1282 if ((req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL)) == NULL) {
1283 BIO_printf(bio_err, "Error reading certificate request in %s\n",
1288 X509_REQ_print(bio_err, req);
1290 BIO_printf(bio_err, "Check that the request matches the signature\n");
1292 if (selfsign && !X509_REQ_check_private_key(req, pkey)) {
1294 "Certificate request and CA private key do not match\n");
1298 if ((pktmp = X509_REQ_get0_pubkey(req)) == NULL) {
1299 BIO_printf(bio_err, "error unpacking public key\n");
1302 i = X509_REQ_verify(req, pktmp);
1306 BIO_printf(bio_err, "Signature verification problems....\n");
1307 ERR_print_errors(bio_err);
1313 "Signature did not match the certificate request\n");
1314 ERR_print_errors(bio_err);
1317 BIO_printf(bio_err, "Signature ok\n");
1319 ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj,
1320 chtype, multirdn, email_dn, startdate, enddate, days, batch,
1321 verbose, req, ext_sect, lconf, certopt, nameopt, default_op,
1322 ext_copy, selfsign);
1330 static int certify_cert(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509,
1331 const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
1332 STACK_OF(CONF_VALUE) *policy, CA_DB *db,
1333 BIGNUM *serial, char *subj, unsigned long chtype,
1334 int multirdn, int email_dn, char *startdate,
1335 char *enddate, long days, int batch, char *ext_sect,
1336 CONF *lconf, int verbose, unsigned long certopt,
1337 unsigned long nameopt, int default_op, int ext_copy)
1340 X509_REQ *rreq = NULL;
1341 EVP_PKEY *pktmp = NULL;
1344 if ((req = load_cert(infile, FORMAT_PEM, infile)) == NULL)
1347 X509_print(bio_err, req);
1349 BIO_printf(bio_err, "Check that the request matches the signature\n");
1351 if ((pktmp = X509_get0_pubkey(req)) == NULL) {
1352 BIO_printf(bio_err, "error unpacking public key\n");
1355 i = X509_verify(req, pktmp);
1358 BIO_printf(bio_err, "Signature verification problems....\n");
1363 BIO_printf(bio_err, "Signature did not match the certificate\n");
1366 BIO_printf(bio_err, "Signature ok\n");
1368 if ((rreq = X509_to_X509_REQ(req, NULL, NULL)) == NULL)
1371 ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj,
1372 chtype, multirdn, email_dn, startdate, enddate, days, batch,
1373 verbose, rreq, ext_sect, lconf, certopt, nameopt, default_op,
1377 X509_REQ_free(rreq);
1382 static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509,
1383 const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
1384 STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial,
1385 char *subj, unsigned long chtype, int multirdn,
1386 int email_dn, char *startdate, char *enddate, long days,
1387 int batch, int verbose, X509_REQ *req, char *ext_sect,
1388 CONF *lconf, unsigned long certopt, unsigned long nameopt,
1389 int default_op, int ext_copy, int selfsign)
1391 X509_NAME *name = NULL, *CAname = NULL, *subject = NULL, *dn_subject =
1393 ASN1_UTCTIME *tm, *tmptm;
1394 ASN1_STRING *str, *str2;
1397 X509_NAME_ENTRY *ne;
1398 X509_NAME_ENTRY *tne, *push;
1400 int ok = -1, i, j, last, nid;
1403 OPENSSL_STRING row[DB_NUMBER];
1404 OPENSSL_STRING *irow = NULL;
1405 OPENSSL_STRING *rrow = NULL;
1408 tmptm = ASN1_UTCTIME_new();
1409 if (tmptm == NULL) {
1410 BIO_printf(bio_err, "malloc error\n");
1414 for (i = 0; i < DB_NUMBER; i++)
1418 X509_NAME *n = parse_name(subj, chtype, multirdn);
1421 ERR_print_errors(bio_err);
1424 X509_REQ_set_subject_name(req, n);
1430 "The Subject's Distinguished Name is as follows\n");
1432 name = X509_REQ_get_subject_name(req);
1433 for (i = 0; i < X509_NAME_entry_count(name); i++) {
1434 ne = X509_NAME_get_entry(name, i);
1435 str = X509_NAME_ENTRY_get_data(ne);
1436 obj = X509_NAME_ENTRY_get_object(ne);
1439 /* assume all type should be strings */
1440 nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(ne));
1442 if (str->type == V_ASN1_UNIVERSALSTRING)
1443 ASN1_UNIVERSALSTRING_to_string(str);
1445 if ((str->type == V_ASN1_IA5STRING) &&
1446 (nid != NID_pkcs9_emailAddress))
1447 str->type = V_ASN1_T61STRING;
1449 if ((nid == NID_pkcs9_emailAddress) &&
1450 (str->type == V_ASN1_PRINTABLESTRING))
1451 str->type = V_ASN1_IA5STRING;
1454 /* If no EMAIL is wanted in the subject */
1455 if ((OBJ_obj2nid(obj) == NID_pkcs9_emailAddress) && (!email_dn))
1458 /* check some things */
1459 if ((OBJ_obj2nid(obj) == NID_pkcs9_emailAddress) &&
1460 (str->type != V_ASN1_IA5STRING)) {
1462 "\nemailAddress type needs to be of type IA5STRING\n");
1465 if ((str->type != V_ASN1_BMPSTRING)
1466 && (str->type != V_ASN1_UTF8STRING)) {
1467 j = ASN1_PRINTABLE_type(str->data, str->length);
1468 if (((j == V_ASN1_T61STRING) &&
1469 (str->type != V_ASN1_T61STRING)) ||
1470 ((j == V_ASN1_IA5STRING) &&
1471 (str->type == V_ASN1_PRINTABLESTRING))) {
1473 "\nThe string contains characters that are illegal for the ASN.1 type\n");
1479 old_entry_print(obj, str);
1482 /* Ok, now we check the 'policy' stuff. */
1483 if ((subject = X509_NAME_new()) == NULL) {
1484 BIO_printf(bio_err, "Memory allocation failure\n");
1488 /* take a copy of the issuer name before we mess with it. */
1490 CAname = X509_NAME_dup(name);
1492 CAname = X509_NAME_dup(X509_get_subject_name(x509));
1497 for (i = 0; i < sk_CONF_VALUE_num(policy); i++) {
1498 cv = sk_CONF_VALUE_value(policy, i); /* get the object id */
1499 if ((j = OBJ_txt2nid(cv->name)) == NID_undef) {
1501 "%s:unknown object type in 'policy' configuration\n",
1505 obj = OBJ_nid2obj(j);
1509 /* lookup the object in the supplied name list */
1510 j = X509_NAME_get_index_by_OBJ(name, obj, last);
1516 tne = X509_NAME_get_entry(name, j);
1520 /* depending on the 'policy', decide what to do. */
1522 if (strcmp(cv->value, "optional") == 0) {
1525 } else if (strcmp(cv->value, "supplied") == 0) {
1528 "The %s field needed to be supplied and was missing\n",
1533 } else if (strcmp(cv->value, "match") == 0) {
1538 "The mandatory %s field was missing\n",
1546 j = X509_NAME_get_index_by_OBJ(CAname, obj, last2);
1547 if ((j < 0) && (last2 == -1)) {
1549 "The %s field does not exist in the CA certificate,\nthe 'policy' is misconfigured\n",
1554 push = X509_NAME_get_entry(CAname, j);
1555 str = X509_NAME_ENTRY_get_data(tne);
1556 str2 = X509_NAME_ENTRY_get_data(push);
1558 if (ASN1_STRING_cmp(str, str2) != 0)
1563 "The %s field needed to be the same in the\nCA certificate (%s) and the request (%s)\n",
1565 ((str2 == NULL) ? "NULL" : (char *)str2->data),
1566 ((str == NULL) ? "NULL" : (char *)str->data));
1571 "%s:invalid type in 'policy' configuration\n",
1577 if (!X509_NAME_add_entry(subject, push, -1, 0)) {
1578 X509_NAME_ENTRY_free(push);
1579 BIO_printf(bio_err, "Memory allocation failure\n");
1589 X509_NAME_free(subject);
1590 /* subject=X509_NAME_dup(X509_REQ_get_subject_name(req)); */
1591 subject = X509_NAME_dup(name);
1592 if (subject == NULL)
1598 "The subject name appears to be ok, checking data base for clashes\n");
1600 /* Build the correct Subject if no e-mail is wanted in the subject */
1602 * and add it later on because of the method extensions are added
1607 dn_subject = subject;
1609 X509_NAME_ENTRY *tmpne;
1611 * Its best to dup the subject DN and then delete any email addresses
1612 * because this retains its structure.
1614 if ((dn_subject = X509_NAME_dup(subject)) == NULL) {
1615 BIO_printf(bio_err, "Memory allocation failure\n");
1618 while ((i = X509_NAME_get_index_by_NID(dn_subject,
1619 NID_pkcs9_emailAddress,
1621 tmpne = X509_NAME_get_entry(dn_subject, i);
1622 X509_NAME_delete_entry(dn_subject, i);
1623 X509_NAME_ENTRY_free(tmpne);
1627 if (BN_is_zero(serial))
1628 row[DB_serial] = OPENSSL_strdup("00");
1630 row[DB_serial] = BN_bn2hex(serial);
1631 if (row[DB_serial] == NULL) {
1632 BIO_printf(bio_err, "Memory allocation failure\n");
1636 if (db->attributes.unique_subject) {
1637 OPENSSL_STRING *crow = row;
1639 rrow = TXT_DB_get_by_index(db->db, DB_name, crow);
1642 "ERROR:There is already a certificate for %s\n",
1647 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1650 "ERROR:Serial number %s has already been issued,\n",
1653 " check the database/serial_file for corruption\n");
1658 BIO_printf(bio_err, "The matching entry has the following details\n");
1659 if (rrow[DB_type][0] == 'E')
1661 else if (rrow[DB_type][0] == 'R')
1663 else if (rrow[DB_type][0] == 'V')
1666 p = "\ninvalid type, Data base error\n";
1667 BIO_printf(bio_err, "Type :%s\n", p);;
1668 if (rrow[DB_type][0] == 'R') {
1669 p = rrow[DB_exp_date];
1672 BIO_printf(bio_err, "Was revoked on:%s\n", p);
1674 p = rrow[DB_exp_date];
1677 BIO_printf(bio_err, "Expires on :%s\n", p);
1678 p = rrow[DB_serial];
1681 BIO_printf(bio_err, "Serial Number :%s\n", p);
1685 BIO_printf(bio_err, "File name :%s\n", p);
1689 BIO_printf(bio_err, "Subject Name :%s\n", p);
1690 ok = -1; /* This is now a 'bad' error. */
1694 /* We are now totally happy, lets make and sign the certificate */
1697 "Everything appears to be ok, creating and signing the certificate\n");
1699 if ((ret = X509_new()) == NULL)
1703 /* Make it an X509 v3 certificate. */
1704 if (!X509_set_version(ret, 2))
1708 if (BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(ret)) == NULL)
1711 if (!X509_set_issuer_name(ret, subject))
1714 if (!X509_set_issuer_name(ret, X509_get_subject_name(x509)))
1718 if (strcmp(startdate, "today") == 0)
1719 X509_gmtime_adj(X509_get_notBefore(ret), 0);
1721 ASN1_TIME_set_string(X509_get_notBefore(ret), startdate);
1723 if (enddate == NULL)
1724 X509_time_adj_ex(X509_get_notAfter(ret), days, 0, NULL);
1727 ASN1_TIME_set_string(X509_get_notAfter(ret), enddate);
1728 ASN1_TIME_diff(&tdays, NULL, NULL, X509_get_notAfter(ret));
1732 if (!X509_set_subject_name(ret, subject))
1735 pktmp = X509_REQ_get0_pubkey(req);
1736 i = X509_set_pubkey(ret, pktmp);
1740 /* Lets add the extensions, if there are any */
1743 X509_set_version(ret, 2);
1745 /* Initialize the context structure */
1747 X509V3_set_ctx(&ctx, ret, ret, req, NULL, 0);
1749 X509V3_set_ctx(&ctx, x509, ret, req, NULL, 0);
1753 BIO_printf(bio_err, "Extra configuration file found\n");
1755 /* Use the extconf configuration db LHASH */
1756 X509V3_set_nconf(&ctx, extconf);
1758 /* Test the structure (needed?) */
1759 /* X509V3_set_ctx_test(&ctx); */
1761 /* Adds exts contained in the configuration file */
1762 if (!X509V3_EXT_add_nconf(extconf, &ctx, ext_sect, ret)) {
1764 "ERROR: adding extensions in section %s\n",
1766 ERR_print_errors(bio_err);
1771 "Successfully added extensions from file.\n");
1772 } else if (ext_sect) {
1773 /* We found extensions to be set from config file */
1774 X509V3_set_nconf(&ctx, lconf);
1776 if (!X509V3_EXT_add_nconf(lconf, &ctx, ext_sect, ret)) {
1778 "ERROR: adding extensions in section %s\n",
1780 ERR_print_errors(bio_err);
1786 "Successfully added extensions from config\n");
1790 /* Copy extensions from request (if any) */
1792 if (!copy_extensions(ret, req, ext_copy)) {
1793 BIO_printf(bio_err, "ERROR: adding extensions from request\n");
1794 ERR_print_errors(bio_err);
1798 /* Set the right value for the noemailDN option */
1799 if (email_dn == 0) {
1800 if (!X509_set_subject_name(ret, dn_subject))
1805 BIO_printf(bio_err, "Certificate Details:\n");
1807 * Never print signature details because signature not present
1809 certopt |= X509_FLAG_NO_SIGDUMP | X509_FLAG_NO_SIGNAME;
1810 X509_print_ex(bio_err, ret, nameopt, certopt);
1813 BIO_printf(bio_err, "Certificate is to be certified until ");
1814 ASN1_TIME_print(bio_err, X509_get_notAfter(ret));
1816 BIO_printf(bio_err, " (%ld days)", days);
1817 BIO_printf(bio_err, "\n");
1821 BIO_printf(bio_err, "Sign the certificate? [y/n]:");
1822 (void)BIO_flush(bio_err);
1824 if (!fgets(buf, sizeof(buf) - 1, stdin)) {
1826 "CERTIFICATE WILL NOT BE CERTIFIED: I/O error\n");
1830 if (!((buf[0] == 'y') || (buf[0] == 'Y'))) {
1831 BIO_printf(bio_err, "CERTIFICATE WILL NOT BE CERTIFIED\n");
1837 pktmp = X509_get0_pubkey(ret);
1838 if (EVP_PKEY_missing_parameters(pktmp) &&
1839 !EVP_PKEY_missing_parameters(pkey))
1840 EVP_PKEY_copy_parameters(pktmp, pkey);
1842 if (!do_X509_sign(ret, pkey, dgst, sigopts))
1845 /* We now just add it to the database */
1846 row[DB_type] = OPENSSL_strdup("V");
1847 tm = X509_get_notAfter(ret);
1848 row[DB_exp_date] = app_malloc(tm->length + 1, "row expdate");
1849 memcpy(row[DB_exp_date], tm->data, tm->length);
1850 row[DB_exp_date][tm->length] = '\0';
1851 row[DB_rev_date] = NULL;
1852 row[DB_file] = OPENSSL_strdup("unknown");
1853 row[DB_name] = X509_NAME_oneline(X509_get_subject_name(ret), NULL, 0);
1855 if ((row[DB_type] == NULL) || (row[DB_exp_date] == NULL) ||
1856 (row[DB_file] == NULL) || (row[DB_name] == NULL)) {
1857 BIO_printf(bio_err, "Memory allocation failure\n");
1861 irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row space");
1862 for (i = 0; i < DB_NUMBER; i++) {
1866 irow[DB_NUMBER] = NULL;
1868 if (!TXT_DB_insert(db->db, irow)) {
1869 BIO_printf(bio_err, "failed to update database\n");
1870 BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error);
1875 for (i = 0; i < DB_NUMBER; i++)
1876 OPENSSL_free(row[i]);
1878 X509_NAME_free(CAname);
1879 X509_NAME_free(subject);
1880 if (dn_subject != subject)
1881 X509_NAME_free(dn_subject);
1882 ASN1_UTCTIME_free(tmptm);
1890 static void write_new_certificate(BIO *bp, X509 *x, int output_der,
1895 (void)i2d_X509_bio(bp, x);
1900 PEM_write_bio_X509(bp, x);
1903 static int certify_spkac(X509 **xret, char *infile, EVP_PKEY *pkey,
1904 X509 *x509, const EVP_MD *dgst,
1905 STACK_OF(OPENSSL_STRING) *sigopts,
1906 STACK_OF(CONF_VALUE) *policy, CA_DB *db,
1907 BIGNUM *serial, char *subj, unsigned long chtype,
1908 int multirdn, int email_dn, char *startdate,
1909 char *enddate, long days, char *ext_sect,
1910 CONF *lconf, int verbose, unsigned long certopt,
1911 unsigned long nameopt, int default_op, int ext_copy)
1913 STACK_OF(CONF_VALUE) *sk = NULL;
1914 LHASH_OF(CONF_VALUE) *parms = NULL;
1915 X509_REQ *req = NULL;
1916 CONF_VALUE *cv = NULL;
1917 NETSCAPE_SPKI *spki = NULL;
1919 EVP_PKEY *pktmp = NULL;
1920 X509_NAME *n = NULL;
1921 X509_NAME_ENTRY *ne = NULL;
1927 * Load input file into a hash table. (This is just an easy
1928 * way to read and parse the file, then put it into a convenient
1931 parms = CONF_load(NULL, infile, &errline);
1932 if (parms == NULL) {
1933 BIO_printf(bio_err, "error on line %ld of %s\n", errline, infile);
1934 ERR_print_errors(bio_err);
1938 sk = CONF_get_section(parms, "default");
1939 if (sk_CONF_VALUE_num(sk) == 0) {
1940 BIO_printf(bio_err, "no name/value pairs found in %s\n", infile);
1946 * Now create a dummy X509 request structure. We don't actually
1947 * have an X509 request, but we have many of the components
1948 * (a public key, various DN components). The idea is that we
1949 * put these components into the right X509 request structure
1950 * and we can use the same code as if you had a real X509 request.
1952 req = X509_REQ_new();
1954 ERR_print_errors(bio_err);
1959 * Build up the subject name set.
1961 n = X509_REQ_get_subject_name(req);
1964 if (sk_CONF_VALUE_num(sk) <= i)
1967 cv = sk_CONF_VALUE_value(sk, i);
1970 * Skip past any leading X. X: X, etc to allow for multiple instances
1972 for (buf = cv->name; *buf; buf++)
1973 if ((*buf == ':') || (*buf == ',') || (*buf == '.')) {
1981 if ((nid = OBJ_txt2nid(type)) == NID_undef) {
1982 if (strcmp(type, "SPKAC") == 0) {
1983 spki = NETSCAPE_SPKI_b64_decode(cv->value, -1);
1986 "unable to load Netscape SPKAC structure\n");
1987 ERR_print_errors(bio_err);
1994 if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
1995 (unsigned char *)buf, -1, -1, 0))
1999 BIO_printf(bio_err, "Netscape SPKAC structure not found in %s\n",
2005 * Now extract the key from the SPKI structure.
2009 "Check that the SPKAC request matches the signature\n");
2011 if ((pktmp = NETSCAPE_SPKI_get_pubkey(spki)) == NULL) {
2012 BIO_printf(bio_err, "error unpacking SPKAC public key\n");
2016 j = NETSCAPE_SPKI_verify(spki, pktmp);
2018 EVP_PKEY_free(pktmp);
2020 "signature verification failed on SPKAC public key\n");
2023 BIO_printf(bio_err, "Signature ok\n");
2025 X509_REQ_set_pubkey(req, pktmp);
2026 EVP_PKEY_free(pktmp);
2027 ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj,
2028 chtype, multirdn, email_dn, startdate, enddate, days, 1,
2029 verbose, req, ext_sect, lconf, certopt, nameopt, default_op,
2034 NETSCAPE_SPKI_free(spki);
2035 X509_NAME_ENTRY_free(ne);
2040 static int check_time_format(const char *str)
2042 return ASN1_TIME_set_string(NULL, str);
2045 static int do_revoke(X509 *x509, CA_DB *db, int type, char *value)
2047 ASN1_UTCTIME *tm = NULL;
2048 char *row[DB_NUMBER], **rrow, **irow;
2049 char *rev_str = NULL;
2053 for (i = 0; i < DB_NUMBER; i++)
2055 row[DB_name] = X509_NAME_oneline(X509_get_subject_name(x509), NULL, 0);
2056 bn = ASN1_INTEGER_to_BN(X509_get_serialNumber(x509), NULL);
2060 row[DB_serial] = OPENSSL_strdup("00");
2062 row[DB_serial] = BN_bn2hex(bn);
2064 if ((row[DB_name] == NULL) || (row[DB_serial] == NULL)) {
2065 BIO_printf(bio_err, "Memory allocation failure\n");
2069 * We have to lookup by serial number because name lookup skips revoked
2072 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
2075 "Adding Entry with serial number %s to DB for %s\n",
2076 row[DB_serial], row[DB_name]);
2078 /* We now just add it to the database */
2079 row[DB_type] = OPENSSL_strdup("V");
2080 tm = X509_get_notAfter(x509);
2081 row[DB_exp_date] = app_malloc(tm->length + 1, "row exp_data");
2082 memcpy(row[DB_exp_date], tm->data, tm->length);
2083 row[DB_exp_date][tm->length] = '\0';
2084 row[DB_rev_date] = NULL;
2085 row[DB_file] = OPENSSL_strdup("unknown");
2087 irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row ptr");
2088 for (i = 0; i < DB_NUMBER; i++) {
2092 irow[DB_NUMBER] = NULL;
2094 if (!TXT_DB_insert(db->db, irow)) {
2095 BIO_printf(bio_err, "failed to update database\n");
2096 BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error);
2100 /* Revoke Certificate */
2104 ok = do_revoke(x509, db, type, value);
2108 } else if (index_name_cmp_noconst(row, rrow)) {
2109 BIO_printf(bio_err, "ERROR:name does not match %s\n", row[DB_name]);
2111 } else if (type == -1) {
2112 BIO_printf(bio_err, "ERROR:Already present, serial number %s\n",
2115 } else if (rrow[DB_type][0] == 'R') {
2116 BIO_printf(bio_err, "ERROR:Already revoked, serial number %s\n",
2120 BIO_printf(bio_err, "Revoking Certificate %s.\n", rrow[DB_serial]);
2121 rev_str = make_revocation_str(type, value);
2123 BIO_printf(bio_err, "Error in revocation arguments\n");
2126 rrow[DB_type][0] = 'R';
2127 rrow[DB_type][1] = '\0';
2128 rrow[DB_rev_date] = rev_str;
2132 for (i = 0; i < DB_NUMBER; i++) {
2133 OPENSSL_free(row[i]);
2138 static int get_certificate_status(const char *serial, CA_DB *db)
2140 char *row[DB_NUMBER], **rrow;
2143 /* Free Resources */
2144 for (i = 0; i < DB_NUMBER; i++)
2147 /* Malloc needed char spaces */
2148 row[DB_serial] = app_malloc(strlen(serial) + 2, "row serial#");
2150 if (strlen(serial) % 2) {
2152 * Set the first char to 0
2154 row[DB_serial][0] = '0';
2156 /* Copy String from serial to row[DB_serial] */
2157 memcpy(row[DB_serial] + 1, serial, strlen(serial));
2158 row[DB_serial][strlen(serial) + 1] = '\0';
2160 /* Copy String from serial to row[DB_serial] */
2161 memcpy(row[DB_serial], serial, strlen(serial));
2162 row[DB_serial][strlen(serial)] = '\0';
2165 /* Make it Upper Case */
2166 for (i = 0; row[DB_serial][i] != '\0'; i++)
2167 row[DB_serial][i] = toupper((unsigned char)row[DB_serial][i]);
2171 /* Search for the certificate */
2172 rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
2174 BIO_printf(bio_err, "Serial %s not present in db.\n", row[DB_serial]);
2177 } else if (rrow[DB_type][0] == 'V') {
2178 BIO_printf(bio_err, "%s=Valid (%c)\n",
2179 row[DB_serial], rrow[DB_type][0]);
2181 } else if (rrow[DB_type][0] == 'R') {
2182 BIO_printf(bio_err, "%s=Revoked (%c)\n",
2183 row[DB_serial], rrow[DB_type][0]);
2185 } else if (rrow[DB_type][0] == 'E') {
2186 BIO_printf(bio_err, "%s=Expired (%c)\n",
2187 row[DB_serial], rrow[DB_type][0]);
2189 } else if (rrow[DB_type][0] == 'S') {
2190 BIO_printf(bio_err, "%s=Suspended (%c)\n",
2191 row[DB_serial], rrow[DB_type][0]);
2194 BIO_printf(bio_err, "%s=Unknown (%c).\n",
2195 row[DB_serial], rrow[DB_type][0]);
2199 for (i = 0; i < DB_NUMBER; i++) {
2200 OPENSSL_free(row[i]);
2205 static int do_updatedb(CA_DB *db)
2207 ASN1_UTCTIME *a_tm = NULL;
2209 int db_y2k, a_y2k; /* flags = 1 if y >= 2000 */
2210 char **rrow, *a_tm_s;
2212 a_tm = ASN1_UTCTIME_new();
2216 /* get actual time and make a string */
2217 a_tm = X509_gmtime_adj(a_tm, 0);
2218 a_tm_s = (char *)app_malloc(a_tm->length + 1, "time string");
2220 memcpy(a_tm_s, a_tm->data, a_tm->length);
2221 a_tm_s[a_tm->length] = '\0';
2223 if (strncmp(a_tm_s, "49", 2) <= 0)
2228 for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
2229 rrow = sk_OPENSSL_PSTRING_value(db->db->data, i);
2231 if (rrow[DB_type][0] == 'V') {
2232 /* ignore entries that are not valid */
2233 if (strncmp(rrow[DB_exp_date], "49", 2) <= 0)
2238 if (db_y2k == a_y2k) {
2239 /* all on the same y2k side */
2240 if (strcmp(rrow[DB_exp_date], a_tm_s) <= 0) {
2241 rrow[DB_type][0] = 'E';
2242 rrow[DB_type][1] = '\0';
2245 BIO_printf(bio_err, "%s=Expired\n", rrow[DB_serial]);
2247 } else if (db_y2k < a_y2k) {
2248 rrow[DB_type][0] = 'E';
2249 rrow[DB_type][1] = '\0';
2252 BIO_printf(bio_err, "%s=Expired\n", rrow[DB_serial]);
2258 ASN1_UTCTIME_free(a_tm);
2259 OPENSSL_free(a_tm_s);
2263 static const char *crl_reasons[] = {
2264 /* CRL reason strings */
2268 "affiliationChanged",
2270 "cessationOfOperation",
2273 /* Additional pseudo reasons */
2279 #define NUM_REASONS OSSL_NELEM(crl_reasons)
2282 * Given revocation information convert to a DB string. The format of the
2283 * string is: revtime[,reason,extra]. Where 'revtime' is the revocation time
2284 * (the current time). 'reason' is the optional CRL reason and 'extra' is any
2285 * additional argument
2288 char *make_revocation_str(int rev_type, char *rev_arg)
2290 char *other = NULL, *str;
2291 const char *reason = NULL;
2293 ASN1_UTCTIME *revtm = NULL;
2299 case REV_CRL_REASON:
2300 for (i = 0; i < 8; i++) {
2301 if (strcasecmp(rev_arg, crl_reasons[i]) == 0) {
2302 reason = crl_reasons[i];
2306 if (reason == NULL) {
2307 BIO_printf(bio_err, "Unknown CRL reason %s\n", rev_arg);
2313 /* Argument is an OID */
2315 otmp = OBJ_txt2obj(rev_arg, 0);
2316 ASN1_OBJECT_free(otmp);
2319 BIO_printf(bio_err, "Invalid object identifier %s\n", rev_arg);
2323 reason = "holdInstruction";
2327 case REV_KEY_COMPROMISE:
2328 case REV_CA_COMPROMISE:
2330 /* Argument is the key compromise time */
2331 if (!ASN1_GENERALIZEDTIME_set_string(NULL, rev_arg)) {
2333 "Invalid time format %s. Need YYYYMMDDHHMMSSZ\n",
2338 if (rev_type == REV_KEY_COMPROMISE)
2341 reason = "CAkeyTime";
2347 revtm = X509_gmtime_adj(NULL, 0);
2352 i = revtm->length + 1;
2355 i += strlen(reason) + 1;
2357 i += strlen(other) + 1;
2359 str = app_malloc(i, "revocation reason");
2360 OPENSSL_strlcpy(str, (char *)revtm->data, i);
2362 OPENSSL_strlcat(str, ",", i);
2363 OPENSSL_strlcat(str, reason, i);
2366 OPENSSL_strlcat(str, ",", i);
2367 OPENSSL_strlcat(str, other, i);
2369 ASN1_UTCTIME_free(revtm);
2374 * Convert revocation field to X509_REVOKED entry
2378 * 2 OK and some extensions added (i.e. V2 CRL)
2381 int make_revoked(X509_REVOKED *rev, const char *str)
2384 int reason_code = -1;
2386 ASN1_OBJECT *hold = NULL;
2387 ASN1_GENERALIZEDTIME *comp_time = NULL;
2388 ASN1_ENUMERATED *rtmp = NULL;
2390 ASN1_TIME *revDate = NULL;
2392 i = unpack_revinfo(&revDate, &reason_code, &hold, &comp_time, str);
2397 if (rev && !X509_REVOKED_set_revocationDate(rev, revDate))
2400 if (rev && (reason_code != OCSP_REVOKED_STATUS_NOSTATUS)) {
2401 rtmp = ASN1_ENUMERATED_new();
2402 if (rtmp == NULL || !ASN1_ENUMERATED_set(rtmp, reason_code))
2404 if (!X509_REVOKED_add1_ext_i2d(rev, NID_crl_reason, rtmp, 0, 0))
2408 if (rev && comp_time) {
2409 if (!X509_REVOKED_add1_ext_i2d
2410 (rev, NID_invalidity_date, comp_time, 0, 0))
2414 if (!X509_REVOKED_add1_ext_i2d
2415 (rev, NID_hold_instruction_code, hold, 0, 0))
2419 if (reason_code != OCSP_REVOKED_STATUS_NOSTATUS)
2427 ASN1_OBJECT_free(hold);
2428 ASN1_GENERALIZEDTIME_free(comp_time);
2429 ASN1_ENUMERATED_free(rtmp);
2430 ASN1_TIME_free(revDate);
2435 static int old_entry_print(ASN1_OBJECT *obj, ASN1_STRING *str)
2437 char buf[25], *pbuf, *p;
2439 j = i2a_ASN1_OBJECT(bio_err, obj);
2441 for (j = 22 - j; j > 0; j--)
2445 BIO_puts(bio_err, buf);
2447 if (str->type == V_ASN1_PRINTABLESTRING)
2448 BIO_printf(bio_err, "PRINTABLE:'");
2449 else if (str->type == V_ASN1_T61STRING)
2450 BIO_printf(bio_err, "T61STRING:'");
2451 else if (str->type == V_ASN1_IA5STRING)
2452 BIO_printf(bio_err, "IA5STRING:'");
2453 else if (str->type == V_ASN1_UNIVERSALSTRING)
2454 BIO_printf(bio_err, "UNIVERSALSTRING:'");
2456 BIO_printf(bio_err, "ASN.1 %2d:'", str->type);
2458 p = (char *)str->data;
2459 for (j = str->length; j > 0; j--) {
2460 if ((*p >= ' ') && (*p <= '~'))
2461 BIO_printf(bio_err, "%c", *p);
2463 BIO_printf(bio_err, "\\0x%02X", *p);
2464 else if ((unsigned char)*p == 0xf7)
2465 BIO_printf(bio_err, "^?");
2467 BIO_printf(bio_err, "^%c", *p + '@');
2470 BIO_printf(bio_err, "'\n");
2474 int unpack_revinfo(ASN1_TIME **prevtm, int *preason, ASN1_OBJECT **phold,
2475 ASN1_GENERALIZEDTIME **pinvtm, const char *str)
2478 char *rtime_str, *reason_str = NULL, *arg_str = NULL, *p;
2479 int reason_code = -1;
2482 ASN1_OBJECT *hold = NULL;
2483 ASN1_GENERALIZEDTIME *comp_time = NULL;
2485 tmp = OPENSSL_strdup(str);
2487 BIO_printf(bio_err, "memory allocation failure\n");
2491 p = strchr(tmp, ',');
2507 *prevtm = ASN1_UTCTIME_new();
2508 if (*prevtm == NULL) {
2509 BIO_printf(bio_err, "memory allocation failure\n");
2512 if (!ASN1_UTCTIME_set_string(*prevtm, rtime_str)) {
2513 BIO_printf(bio_err, "invalid revocation date %s\n", rtime_str);
2518 for (i = 0; i < NUM_REASONS; i++) {
2519 if (strcasecmp(reason_str, crl_reasons[i]) == 0) {
2524 if (reason_code == OCSP_REVOKED_STATUS_NOSTATUS) {
2525 BIO_printf(bio_err, "invalid reason code %s\n", reason_str);
2529 if (reason_code == 7)
2530 reason_code = OCSP_REVOKED_STATUS_REMOVEFROMCRL;
2531 else if (reason_code == 8) { /* Hold instruction */
2533 BIO_printf(bio_err, "missing hold instruction\n");
2536 reason_code = OCSP_REVOKED_STATUS_CERTIFICATEHOLD;
2537 hold = OBJ_txt2obj(arg_str, 0);
2540 BIO_printf(bio_err, "invalid object identifier %s\n",
2547 ASN1_OBJECT_free(hold);
2548 } else if ((reason_code == 9) || (reason_code == 10)) {
2550 BIO_printf(bio_err, "missing compromised time\n");
2553 comp_time = ASN1_GENERALIZEDTIME_new();
2554 if (comp_time == NULL) {
2555 BIO_printf(bio_err, "memory allocation failure\n");
2558 if (!ASN1_GENERALIZEDTIME_set_string(comp_time, arg_str)) {
2559 BIO_printf(bio_err, "invalid compromised time %s\n", arg_str);
2562 if (reason_code == 9)
2563 reason_code = OCSP_REVOKED_STATUS_KEYCOMPROMISE;
2565 reason_code = OCSP_REVOKED_STATUS_CACOMPROMISE;
2570 *preason = reason_code;
2572 *pinvtm = comp_time;
2581 ASN1_GENERALIZEDTIME_free(comp_time);