a2cd4d98ef2371bdc89cdbbb2a5f0453fef9d281
[openssl.git] / apps / ca.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
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
8  */
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <ctype.h>
13 #include <sys/types.h>
14 #include <openssl/conf.h>
15 #include <openssl/bio.h>
16 #include <openssl/err.h>
17 #include <openssl/bn.h>
18 #include <openssl/txt_db.h>
19 #include <openssl/evp.h>
20 #include <openssl/x509.h>
21 #include <openssl/x509v3.h>
22 #include <openssl/objects.h>
23 #include <openssl/ocsp.h>
24 #include <openssl/pem.h>
25
26 #ifndef W_OK
27 # ifdef OPENSSL_SYS_VMS
28 #  include <unistd.h>
29 # elif !defined(OPENSSL_SYS_VXWORKS) && !defined(OPENSSL_SYS_WINDOWS)
30 #  include <sys/file.h>
31 # endif
32 #endif
33
34 #include "apps.h"
35 #include "progs.h"
36
37 #ifndef W_OK
38 # define F_OK 0
39 # define W_OK 2
40 # define R_OK 4
41 #endif
42
43 #ifndef PATH_MAX
44 # define PATH_MAX 4096
45 #endif
46
47 #define BASE_SECTION            "ca"
48
49 #define ENV_DEFAULT_CA          "default_ca"
50
51 #define STRING_MASK             "string_mask"
52 #define UTF8_IN                 "utf8"
53
54 #define ENV_NEW_CERTS_DIR       "new_certs_dir"
55 #define ENV_CERTIFICATE         "certificate"
56 #define ENV_SERIAL              "serial"
57 #define ENV_RAND_SERIAL         "rand_serial"
58 #define ENV_CRLNUMBER           "crlnumber"
59 #define ENV_PRIVATE_KEY         "private_key"
60 #define ENV_DEFAULT_DAYS        "default_days"
61 #define ENV_DEFAULT_STARTDATE   "default_startdate"
62 #define ENV_DEFAULT_ENDDATE     "default_enddate"
63 #define ENV_DEFAULT_CRL_DAYS    "default_crl_days"
64 #define ENV_DEFAULT_CRL_HOURS   "default_crl_hours"
65 #define ENV_DEFAULT_MD          "default_md"
66 #define ENV_DEFAULT_EMAIL_DN    "email_in_dn"
67 #define ENV_PRESERVE            "preserve"
68 #define ENV_POLICY              "policy"
69 #define ENV_EXTENSIONS          "x509_extensions"
70 #define ENV_CRLEXT              "crl_extensions"
71 #define ENV_MSIE_HACK           "msie_hack"
72 #define ENV_NAMEOPT             "name_opt"
73 #define ENV_CERTOPT             "cert_opt"
74 #define ENV_EXTCOPY             "copy_extensions"
75 #define ENV_UNIQUE_SUBJECT      "unique_subject"
76
77 #define ENV_DATABASE            "database"
78
79 /* Additional revocation information types */
80 typedef enum {
81     REV_VALID             = -1, /* Valid (not-revoked) status */
82     REV_NONE              = 0, /* No additional information */
83     REV_CRL_REASON        = 1, /* Value is CRL reason code */
84     REV_HOLD              = 2, /* Value is hold instruction */
85     REV_KEY_COMPROMISE    = 3, /* Value is cert key compromise time */
86     REV_CA_COMPROMISE     = 4  /* Value is CA key compromise time */
87 } REVINFO_TYPE;
88
89 static char *lookup_conf(const CONF *conf, const char *group, const char *tag);
90
91 static int certify(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509,
92                    const EVP_MD *dgst,
93                    STACK_OF(OPENSSL_STRING) *sigopts,
94                    STACK_OF(OPENSSL_STRING) *vfyopts,
95                    STACK_OF(CONF_VALUE) *policy, CA_DB *db,
96                    BIGNUM *serial, const char *subj, unsigned long chtype,
97                    int multirdn, int email_dn, const char *startdate,
98                    const char *enddate,
99                    long days, int batch, const char *ext_sect, CONF *conf,
100                    int verbose, unsigned long certopt, unsigned long nameopt,
101                    int default_op, int ext_copy, int selfsign);
102 static int certify_cert(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509,
103                         const EVP_MD *dgst,
104                         STACK_OF(OPENSSL_STRING) *sigopts,
105                         STACK_OF(OPENSSL_STRING) *vfyopts,
106                         STACK_OF(CONF_VALUE) *policy, CA_DB *db,
107                         BIGNUM *serial, const char *subj, unsigned long chtype,
108                         int multirdn, int email_dn, const char *startdate,
109                         const char *enddate, long days, int batch, const char *ext_sect,
110                         CONF *conf, int verbose, unsigned long certopt,
111                         unsigned long nameopt, int default_op, int ext_copy);
112 static int certify_spkac(X509 **xret, const char *infile, EVP_PKEY *pkey,
113                          X509 *x509, const EVP_MD *dgst,
114                          STACK_OF(OPENSSL_STRING) *sigopts,
115                          STACK_OF(CONF_VALUE) *policy, CA_DB *db,
116                          BIGNUM *serial, const char *subj, unsigned long chtype,
117                          int multirdn, int email_dn, const char *startdate,
118                          const char *enddate, long days, const char *ext_sect, CONF *conf,
119                          int verbose, unsigned long certopt,
120                          unsigned long nameopt, int default_op, int ext_copy);
121 static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509,
122                    const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
123                    STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial,
124                    const char *subj, unsigned long chtype, int multirdn,
125                    int email_dn, const char *startdate, const char *enddate, long days,
126                    int batch, int verbose, X509_REQ *req, const char *ext_sect,
127                    CONF *conf, unsigned long certopt, unsigned long nameopt,
128                    int default_op, int ext_copy, int selfsign);
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 static int do_revoke(X509 *x509, CA_DB *db, REVINFO_TYPE rev_type,
133                      const char *extval);
134 static char *make_revocation_str(REVINFO_TYPE rev_type, const char *rev_arg);
135 static int make_revoked(X509_REVOKED *rev, const char *str);
136 static int old_entry_print(const ASN1_OBJECT *obj, const ASN1_STRING *str);
137 static void write_new_certificate(BIO *bp, X509 *x, int output_der, int notext);
138
139 static CONF *extconf = NULL;
140 static int preserve = 0;
141 static int msie_hack = 0;
142
143 typedef enum OPTION_choice {
144     OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
145     OPT_ENGINE, OPT_VERBOSE, OPT_CONFIG, OPT_NAME, OPT_SUBJ, OPT_UTF8,
146     OPT_CREATE_SERIAL, OPT_MULTIVALUE_RDN, OPT_STARTDATE, OPT_ENDDATE,
147     OPT_DAYS, OPT_MD, OPT_POLICY, OPT_KEYFILE, OPT_KEYFORM, OPT_PASSIN,
148     OPT_KEY, OPT_CERT, OPT_SELFSIGN, OPT_IN, OPT_OUT, OPT_OUTDIR, OPT_VFYOPT,
149     OPT_SIGOPT, OPT_NOTEXT, OPT_BATCH, OPT_PRESERVEDN, OPT_NOEMAILDN,
150     OPT_GENCRL, OPT_MSIE_HACK, OPT_CRLDAYS, OPT_CRLHOURS, OPT_CRLSEC,
151     OPT_INFILES, OPT_SS_CERT, OPT_SPKAC, OPT_REVOKE, OPT_VALID,
152     OPT_EXTENSIONS, OPT_EXTFILE, OPT_STATUS, OPT_UPDATEDB, OPT_CRLEXTS,
153     OPT_RAND_SERIAL,
154     OPT_R_ENUM, OPT_PROV_ENUM,
155     /* Do not change the order here; see related case statements below */
156     OPT_CRL_REASON, OPT_CRL_HOLD, OPT_CRL_COMPROMISE, OPT_CRL_CA_COMPROMISE
157 } OPTION_CHOICE;
158
159 const OPTIONS ca_options[] = {
160     {OPT_HELP_STR, 1, '-', "Usage: %s [options] [certreq...]\n"},
161
162     OPT_SECTION("General"),
163     {"help", OPT_HELP, '-', "Display this summary"},
164     {"verbose", OPT_VERBOSE, '-', "Verbose output during processing"},
165     {"outdir", OPT_OUTDIR, '/', "Where to put output cert"},
166     {"in", OPT_IN, '<', "The input PEM encoded cert request(s)"},
167     {"infiles", OPT_INFILES, '-', "The last argument, requests to process"},
168     {"out", OPT_OUT, '>', "Where to put the output file(s)"},
169     {"notext", OPT_NOTEXT, '-', "Do not print the generated certificate"},
170     {"batch", OPT_BATCH, '-', "Don't ask questions"},
171     {"msie_hack", OPT_MSIE_HACK, '-',
172      "msie modifications to handle all Universal Strings"},
173     {"ss_cert", OPT_SS_CERT, '<', "File contains a self signed cert to sign"},
174     {"spkac", OPT_SPKAC, '<',
175      "File contains DN and signed public key and challenge"},
176 #ifndef OPENSSL_NO_ENGINE
177     {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"},
178 #endif
179
180     OPT_SECTION("Configuration"),
181     {"config", OPT_CONFIG, 's', "A config file"},
182     {"name", OPT_NAME, 's', "The particular CA definition to use"},
183     {"section", OPT_NAME, 's', "An alias for -name"},
184     {"policy", OPT_POLICY, 's', "The CA 'policy' to support"},
185
186     OPT_SECTION("Certificate"),
187     {"subj", OPT_SUBJ, 's', "Use arg instead of request's subject"},
188     {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"},
189     {"create_serial", OPT_CREATE_SERIAL, '-',
190      "If reading serial fails, create a new random serial"},
191     {"rand_serial", OPT_RAND_SERIAL, '-',
192      "Always create a random serial; do not store it"},
193     {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-',
194      "Enable support for multivalued RDNs"},
195     {"startdate", OPT_STARTDATE, 's', "Cert notBefore, YYMMDDHHMMSSZ"},
196     {"enddate", OPT_ENDDATE, 's',
197      "YYMMDDHHMMSSZ cert notAfter (overrides -days)"},
198     {"days", OPT_DAYS, 'p', "Number of days to certify the cert for"},
199     {"extensions", OPT_EXTENSIONS, 's',
200      "Extension section (override value in config file)"},
201     {"extfile", OPT_EXTFILE, '<',
202      "Configuration file with X509v3 extensions to add"},
203     {"preserveDN", OPT_PRESERVEDN, '-', "Don't re-order the DN"},
204     {"noemailDN", OPT_NOEMAILDN, '-', "Don't add the EMAIL field to the DN"},
205
206     OPT_SECTION("Signing"),
207     {"md", OPT_MD, 's', "md to use; one of md2, md5, sha or sha1"},
208     {"keyfile", OPT_KEYFILE, 's', "Private key"},
209     {"keyform", OPT_KEYFORM, 'f', "Private key file format (PEM or ENGINE)"},
210     {"passin", OPT_PASSIN, 's', "Input file pass phrase source"},
211     {"key", OPT_KEY, 's', "Key to decode the private key if it is encrypted"},
212     {"cert", OPT_CERT, '<', "The CA cert"},
213     {"selfsign", OPT_SELFSIGN, '-',
214      "Sign a cert with the key associated with it"},
215     {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"},
216     {"vfyopt", OPT_SIGOPT, 's', "Verification parameter in n:v form"},
217
218     OPT_SECTION("Revocation"),
219     {"gencrl", OPT_GENCRL, '-', "Generate a new CRL"},
220     {"valid", OPT_VALID, 's',
221      "Add a Valid(not-revoked) DB entry about a cert (given in file)"},
222     {"status", OPT_STATUS, 's', "Shows cert status given the serial number"},
223     {"updatedb", OPT_UPDATEDB, '-', "Updates db for expired cert"},
224     {"crlexts", OPT_CRLEXTS, 's',
225      "CRL extension section (override value in config file)"},
226     {"crl_reason", OPT_CRL_REASON, 's', "revocation reason"},
227     {"crl_hold", OPT_CRL_HOLD, 's',
228      "the hold instruction, an OID. Sets revocation reason to certificateHold"},
229     {"crl_compromise", OPT_CRL_COMPROMISE, 's',
230      "sets compromise time to val and the revocation reason to keyCompromise"},
231     {"crl_CA_compromise", OPT_CRL_CA_COMPROMISE, 's',
232      "sets compromise time to val and the revocation reason to CACompromise"},
233     {"crldays", OPT_CRLDAYS, 'p', "Days until the next CRL is due"},
234     {"crlhours", OPT_CRLHOURS, 'p', "Hours until the next CRL is due"},
235     {"crlsec", OPT_CRLSEC, 'p', "Seconds until the next CRL is due"},
236     {"revoke", OPT_REVOKE, '<', "Revoke a cert (given in file)"},
237
238     OPT_R_OPTIONS,
239     OPT_PROV_OPTIONS,
240
241     OPT_PARAMETERS(),
242     {"certreq", 0, 0, "Certificate requests to be signed (optional)"},
243     {NULL}
244 };
245
246 int ca_main(int argc, char **argv)
247 {
248     CONF *conf = NULL;
249     ENGINE *e = NULL;
250     BIGNUM *crlnumber = NULL, *serial = NULL;
251     EVP_PKEY *pkey = NULL;
252     BIO *in = NULL, *out = NULL, *Sout = NULL;
253     ASN1_INTEGER *tmpser;
254     ASN1_TIME *tmptm;
255     CA_DB *db = NULL;
256     DB_ATTR db_attr;
257     STACK_OF(CONF_VALUE) *attribs = NULL;
258     STACK_OF(OPENSSL_STRING) *sigopts = NULL, *vfyopts = NULL;
259     STACK_OF(X509) *cert_sk = NULL;
260     X509_CRL *crl = NULL;
261     const EVP_MD *dgst = NULL;
262     char *configfile = default_config_file, *section = NULL;
263     char *md = NULL, *policy = NULL, *keyfile = NULL;
264     char *certfile = NULL, *crl_ext = NULL, *crlnumberfile = NULL, *key = NULL;
265     const char *infile = NULL, *spkac_file = NULL, *ss_cert_file = NULL;
266     const char *extensions = NULL, *extfile = NULL, *passinarg = NULL;
267     char *outdir = NULL, *outfile = NULL, *rev_arg = NULL, *ser_status = NULL;
268     const char *serialfile = NULL, *subj = NULL;
269     char *prog, *startdate = NULL, *enddate = NULL;
270     char *dbfile = NULL, *f;
271     char new_cert[PATH_MAX];
272     char tmp[10 + 1] = "\0";
273     char *const *pp;
274     const char *p;
275     size_t outdirlen = 0;
276     int create_ser = 0, free_key = 0, total = 0, total_done = 0;
277     int batch = 0, default_op = 1, doupdatedb = 0, ext_copy = EXT_COPY_NONE;
278     int keyformat = FORMAT_PEM, multirdn = 0, notext = 0, output_der = 0;
279     int ret = 1, email_dn = 1, req = 0, verbose = 0, gencrl = 0, dorevoke = 0;
280     int rand_ser = 0, i, j, selfsign = 0, def_nid, def_ret;
281     long crldays = 0, crlhours = 0, crlsec = 0, days = 0;
282     unsigned long chtype = MBSTRING_ASC, certopt = 0;
283     X509 *x509 = NULL, *x509p = NULL, *x = NULL;
284     REVINFO_TYPE rev_type = REV_NONE;
285     X509_REVOKED *r = NULL;
286     OPTION_CHOICE o;
287
288     prog = opt_init(argc, argv, ca_options);
289     while ((o = opt_next()) != OPT_EOF) {
290         switch (o) {
291         case OPT_EOF:
292         case OPT_ERR:
293 opthelp:
294             BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
295             goto end;
296         case OPT_HELP:
297             opt_help(ca_options);
298             ret = 0;
299             goto end;
300         case OPT_IN:
301             req = 1;
302             infile = opt_arg();
303             break;
304         case OPT_OUT:
305             outfile = opt_arg();
306             break;
307         case OPT_VERBOSE:
308             verbose = 1;
309             break;
310         case OPT_CONFIG:
311             configfile = opt_arg();
312             break;
313         case OPT_NAME:
314             section = opt_arg();
315             break;
316         case OPT_SUBJ:
317             subj = opt_arg();
318             /* preserve=1; */
319             break;
320         case OPT_UTF8:
321             chtype = MBSTRING_UTF8;
322             break;
323         case OPT_RAND_SERIAL:
324             rand_ser = 1;
325             break;
326         case OPT_CREATE_SERIAL:
327             create_ser = 1;
328             break;
329         case OPT_MULTIVALUE_RDN:
330             multirdn = 1;
331             break;
332         case OPT_STARTDATE:
333             startdate = opt_arg();
334             break;
335         case OPT_ENDDATE:
336             enddate = opt_arg();
337             break;
338         case OPT_DAYS:
339             days = atoi(opt_arg());
340             break;
341         case OPT_MD:
342             md = opt_arg();
343             break;
344         case OPT_POLICY:
345             policy = opt_arg();
346             break;
347         case OPT_KEYFILE:
348             keyfile = opt_arg();
349             break;
350         case OPT_KEYFORM:
351             if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat))
352                 goto opthelp;
353             break;
354         case OPT_PASSIN:
355             passinarg = opt_arg();
356             break;
357         case OPT_R_CASES:
358             if (!opt_rand(o))
359                 goto end;
360             break;
361         case OPT_PROV_CASES:
362             if (!opt_provider(o))
363                 goto end;
364             break;
365         case OPT_KEY:
366             key = opt_arg();
367             break;
368         case OPT_CERT:
369             certfile = opt_arg();
370             break;
371         case OPT_SELFSIGN:
372             selfsign = 1;
373             break;
374         case OPT_OUTDIR:
375             outdir = opt_arg();
376             break;
377         case OPT_SIGOPT:
378             if (sigopts == NULL)
379                 sigopts = sk_OPENSSL_STRING_new_null();
380             if (sigopts == NULL || !sk_OPENSSL_STRING_push(sigopts, opt_arg()))
381                 goto end;
382             break;
383         case OPT_VFYOPT:
384             if (vfyopts == NULL)
385                 vfyopts = sk_OPENSSL_STRING_new_null();
386             if (vfyopts == NULL || !sk_OPENSSL_STRING_push(vfyopts, opt_arg()))
387                 goto end;
388             break;
389         case OPT_NOTEXT:
390             notext = 1;
391             break;
392         case OPT_BATCH:
393             batch = 1;
394             break;
395         case OPT_PRESERVEDN:
396             preserve = 1;
397             break;
398         case OPT_NOEMAILDN:
399             email_dn = 0;
400             break;
401         case OPT_GENCRL:
402             gencrl = 1;
403             break;
404         case OPT_MSIE_HACK:
405             msie_hack = 1;
406             break;
407         case OPT_CRLDAYS:
408             crldays = atol(opt_arg());
409             break;
410         case OPT_CRLHOURS:
411             crlhours = atol(opt_arg());
412             break;
413         case OPT_CRLSEC:
414             crlsec = atol(opt_arg());
415             break;
416         case OPT_INFILES:
417             req = 1;
418             goto end_of_options;
419         case OPT_SS_CERT:
420             ss_cert_file = opt_arg();
421             req = 1;
422             break;
423         case OPT_SPKAC:
424             spkac_file = opt_arg();
425             req = 1;
426             break;
427         case OPT_REVOKE:
428             infile = opt_arg();
429             dorevoke = 1;
430             break;
431         case OPT_VALID:
432             infile = opt_arg();
433             dorevoke = 2;
434             break;
435         case OPT_EXTENSIONS:
436             extensions = opt_arg();
437             break;
438         case OPT_EXTFILE:
439             extfile = opt_arg();
440             break;
441         case OPT_STATUS:
442             ser_status = opt_arg();
443             break;
444         case OPT_UPDATEDB:
445             doupdatedb = 1;
446             break;
447         case OPT_CRLEXTS:
448             crl_ext = opt_arg();
449             break;
450         case OPT_CRL_REASON:   /* := REV_CRL_REASON */
451         case OPT_CRL_HOLD:
452         case OPT_CRL_COMPROMISE:
453         case OPT_CRL_CA_COMPROMISE:
454             rev_arg = opt_arg();
455             rev_type = (o - OPT_CRL_REASON) + REV_CRL_REASON;
456             break;
457         case OPT_ENGINE:
458             e = setup_engine(opt_arg(), 0);
459             break;
460         }
461     }
462 end_of_options:
463     argc = opt_num_rest();
464     argv = opt_rest();
465
466     BIO_printf(bio_err, "Using configuration from %s\n", configfile);
467
468     if ((conf = app_load_config(configfile)) == NULL)
469         goto end;
470     if (configfile != default_config_file && !app_load_modules(conf))
471         goto end;
472
473     /* Lets get the config section we are using */
474     if (section == NULL
475         && (section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_CA)) == NULL)
476         goto end;
477
478     p = NCONF_get_string(conf, NULL, "oid_file");
479     if (p == NULL)
480         ERR_clear_error();
481     if (p != NULL) {
482         BIO *oid_bio = BIO_new_file(p, "r");
483
484         if (oid_bio == NULL) {
485             ERR_clear_error();
486         } else {
487             OBJ_create_objects(oid_bio);
488             BIO_free(oid_bio);
489         }
490     }
491     if (!add_oid_section(conf)) {
492         ERR_print_errors(bio_err);
493         goto end;
494     }
495
496     app_RAND_load_conf(conf, BASE_SECTION);
497
498     f = NCONF_get_string(conf, section, STRING_MASK);
499     if (f == NULL)
500         ERR_clear_error();
501
502     if (f != NULL && !ASN1_STRING_set_default_mask_asc(f)) {
503         BIO_printf(bio_err, "Invalid global string mask setting %s\n", f);
504         goto end;
505     }
506
507     if (chtype != MBSTRING_UTF8) {
508         f = NCONF_get_string(conf, section, UTF8_IN);
509         if (f == NULL)
510             ERR_clear_error();
511         else if (strcmp(f, "yes") == 0)
512             chtype = MBSTRING_UTF8;
513     }
514
515     db_attr.unique_subject = 1;
516     p = NCONF_get_string(conf, section, ENV_UNIQUE_SUBJECT);
517     if (p != NULL)
518         db_attr.unique_subject = parse_yesno(p, 1);
519     else
520         ERR_clear_error();
521
522     /*****************************************************************/
523     /* report status of cert with serial number given on command line */
524     if (ser_status) {
525         dbfile = lookup_conf(conf, section, ENV_DATABASE);
526         if (dbfile == NULL)
527             goto end;
528
529         db = load_index(dbfile, &db_attr);
530         if (db == NULL)
531             goto end;
532
533         if (index_index(db) <= 0)
534             goto end;
535
536         if (get_certificate_status(ser_status, db) != 1)
537             BIO_printf(bio_err, "Error verifying serial %s!\n", ser_status);
538         goto end;
539     }
540
541     /*****************************************************************/
542     /* we definitely need a private key, so let's get it */
543
544     if (keyfile == NULL
545         && (keyfile = lookup_conf(conf, section, ENV_PRIVATE_KEY)) == NULL)
546         goto end;
547
548     if (key == NULL) {
549         free_key = 1;
550         if (!app_passwd(passinarg, NULL, &key, NULL)) {
551             BIO_printf(bio_err, "Error getting password\n");
552             goto end;
553         }
554     }
555     pkey = load_key(keyfile, keyformat, 0, key, e, "CA private key");
556     if (key != NULL)
557         OPENSSL_cleanse(key, strlen(key));
558     if (pkey == NULL)
559         /* load_key() has already printed an appropriate message */
560         goto end;
561
562     /*****************************************************************/
563     /* we need a certificate */
564     if (!selfsign || spkac_file || ss_cert_file || gencrl) {
565         if (certfile == NULL
566             && (certfile = lookup_conf(conf, section, ENV_CERTIFICATE)) == NULL)
567             goto end;
568
569         x509 = load_cert(certfile, FORMAT_PEM, "CA certificate");
570         if (x509 == NULL)
571             goto end;
572
573         if (!X509_check_private_key(x509, pkey)) {
574             BIO_printf(bio_err,
575                        "CA certificate and CA private key do not match\n");
576             goto end;
577         }
578     }
579     if (!selfsign)
580         x509p = x509;
581
582     f = NCONF_get_string(conf, BASE_SECTION, ENV_PRESERVE);
583     if (f == NULL)
584         ERR_clear_error();
585     if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
586         preserve = 1;
587     f = NCONF_get_string(conf, BASE_SECTION, ENV_MSIE_HACK);
588     if (f == NULL)
589         ERR_clear_error();
590     if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
591         msie_hack = 1;
592
593     f = NCONF_get_string(conf, section, ENV_NAMEOPT);
594
595     if (f != NULL) {
596         if (!set_nameopt(f)) {
597             BIO_printf(bio_err, "Invalid name options: \"%s\"\n", f);
598             goto end;
599         }
600         default_op = 0;
601     }
602
603     f = NCONF_get_string(conf, section, ENV_CERTOPT);
604
605     if (f != NULL) {
606         if (!set_cert_ex(&certopt, f)) {
607             BIO_printf(bio_err, "Invalid certificate options: \"%s\"\n", f);
608             goto end;
609         }
610         default_op = 0;
611     } else {
612         ERR_clear_error();
613     }
614
615     f = NCONF_get_string(conf, section, ENV_EXTCOPY);
616
617     if (f != NULL) {
618         if (!set_ext_copy(&ext_copy, f)) {
619             BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n", f);
620             goto end;
621         }
622     } else {
623         ERR_clear_error();
624     }
625
626     /*****************************************************************/
627     /* lookup where to write new certificates */
628     if ((outdir == NULL) && (req)) {
629
630         outdir = NCONF_get_string(conf, section, ENV_NEW_CERTS_DIR);
631         if (outdir == NULL) {
632             BIO_printf(bio_err,
633                        "there needs to be defined a directory for new certificate to be placed in\n");
634             goto end;
635         }
636 #ifndef OPENSSL_SYS_VMS
637         /*
638          * outdir is a directory spec, but access() for VMS demands a
639          * filename.  We could use the DEC C routine to convert the
640          * directory syntax to Unix, and give that to app_isdir,
641          * but for now the fopen will catch the error if it's not a
642          * directory
643          */
644         if (app_isdir(outdir) <= 0) {
645             BIO_printf(bio_err, "%s: %s is not a directory\n", prog, outdir);
646             perror(outdir);
647             goto end;
648         }
649 #endif
650     }
651
652     /*****************************************************************/
653     /* we need to load the database file */
654     dbfile = lookup_conf(conf, section, ENV_DATABASE);
655     if (dbfile == NULL)
656         goto end;
657
658     db = load_index(dbfile, &db_attr);
659     if (db == NULL)
660         goto end;
661
662     /* Lets check some fields */
663     for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
664         pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
665         if ((pp[DB_type][0] != DB_TYPE_REV) && (pp[DB_rev_date][0] != '\0')) {
666             BIO_printf(bio_err,
667                        "entry %d: not revoked yet, but has a revocation date\n",
668                        i + 1);
669             goto end;
670         }
671         if ((pp[DB_type][0] == DB_TYPE_REV) &&
672             !make_revoked(NULL, pp[DB_rev_date])) {
673             BIO_printf(bio_err, " in entry %d\n", i + 1);
674             goto end;
675         }
676         if (!check_time_format((char *)pp[DB_exp_date])) {
677             BIO_printf(bio_err, "entry %d: invalid expiry date\n", i + 1);
678             goto end;
679         }
680         p = pp[DB_serial];
681         j = strlen(p);
682         if (*p == '-') {
683             p++;
684             j--;
685         }
686         if ((j & 1) || (j < 2)) {
687             BIO_printf(bio_err, "entry %d: bad serial number length (%d)\n",
688                        i + 1, j);
689             goto end;
690         }
691         for ( ; *p; p++) {
692             if (!isxdigit(_UC(*p))) {
693                 BIO_printf(bio_err,
694                            "entry %d: bad char 0%o '%c' in serial number\n",
695                            i + 1, *p, *p);
696                 goto end;
697             }
698         }
699     }
700     if (verbose) {
701         TXT_DB_write(bio_out, db->db);
702         BIO_printf(bio_err, "%d entries loaded from the database\n",
703                    sk_OPENSSL_PSTRING_num(db->db->data));
704         BIO_printf(bio_err, "generating index\n");
705     }
706
707     if (index_index(db) <= 0)
708         goto end;
709
710     /*****************************************************************/
711     /* Update the db file for expired certificates */
712     if (doupdatedb) {
713         if (verbose)
714             BIO_printf(bio_err, "Updating %s ...\n", dbfile);
715
716         i = do_updatedb(db);
717         if (i == -1) {
718             BIO_printf(bio_err, "Malloc failure\n");
719             goto end;
720         } else if (i == 0) {
721             if (verbose)
722                 BIO_printf(bio_err, "No entries found to mark expired\n");
723         } else {
724             if (!save_index(dbfile, "new", db))
725                 goto end;
726
727             if (!rotate_index(dbfile, "new", "old"))
728                 goto end;
729
730             if (verbose)
731                 BIO_printf(bio_err, "Done. %d entries marked as expired\n", i);
732         }
733     }
734
735     /*****************************************************************/
736     /* Read extensions config file                                   */
737     if (extfile) {
738         if ((extconf = app_load_config(extfile)) == NULL) {
739             ret = 1;
740             goto end;
741         }
742
743         if (verbose)
744             BIO_printf(bio_err, "Successfully loaded extensions file %s\n",
745                        extfile);
746
747         /* We can have sections in the ext file */
748         if (extensions == NULL) {
749             extensions = NCONF_get_string(extconf, "default", "extensions");
750             if (extensions == NULL)
751                 extensions = "default";
752         }
753     }
754
755     /*****************************************************************/
756     if (req || gencrl) {
757         if (spkac_file != NULL && outfile != NULL) {
758             output_der = 1;
759             batch = 1;
760         }
761     }
762
763     def_ret = EVP_PKEY_get_default_digest_nid(pkey, &def_nid);
764     /*
765      * EVP_PKEY_get_default_digest_nid() returns 2 if the digest is
766      * mandatory for this algorithm.
767      */
768     if (def_ret == 2 && def_nid == NID_undef) {
769         /* The signing algorithm requires there to be no digest */
770         dgst = EVP_md_null();
771     } else if (md == NULL
772                && (md = lookup_conf(conf, section, ENV_DEFAULT_MD)) == NULL) {
773         goto end;
774     } else {
775         if (strcmp(md, "default") == 0) {
776             if (def_ret <= 0) {
777                 BIO_puts(bio_err, "no default digest\n");
778                 goto end;
779             }
780             md = (char *)OBJ_nid2sn(def_nid);
781         }
782
783         if (!opt_md(md, &dgst))
784             goto end;
785     }
786
787     if (req) {
788         if (email_dn == 1) {
789             char *tmp_email_dn = NULL;
790
791             tmp_email_dn = NCONF_get_string(conf, section, ENV_DEFAULT_EMAIL_DN);
792             if (tmp_email_dn != NULL && strcmp(tmp_email_dn, "no") == 0)
793                 email_dn = 0;
794         }
795         if (verbose)
796             BIO_printf(bio_err, "message digest is %s\n",
797                        OBJ_nid2ln(EVP_MD_type(dgst)));
798         if (policy == NULL
799             && (policy = lookup_conf(conf, section, ENV_POLICY)) == NULL)
800             goto end;
801
802         if (verbose)
803             BIO_printf(bio_err, "policy is %s\n", policy);
804
805         if (NCONF_get_string(conf, section, ENV_RAND_SERIAL) != NULL) {
806             rand_ser = 1;
807         } else {
808             serialfile = lookup_conf(conf, section, ENV_SERIAL);
809             if (serialfile == NULL)
810                 goto end;
811         }
812
813         if (extconf == NULL) {
814             /*
815              * no '-extfile' option, so we look for extensions in the main
816              * configuration file
817              */
818             if (extensions == NULL) {
819                 extensions = NCONF_get_string(conf, section, ENV_EXTENSIONS);
820                 if (extensions == NULL)
821                     ERR_clear_error();
822             }
823             if (extensions != NULL) {
824                 /* Check syntax of file */
825                 X509V3_CTX ctx;
826                 X509V3_set_ctx_test(&ctx);
827                 X509V3_set_nconf(&ctx, conf);
828                 if (!X509V3_EXT_add_nconf(conf, &ctx, extensions, NULL)) {
829                     BIO_printf(bio_err,
830                                "Error Loading extension section %s\n",
831                                extensions);
832                     ret = 1;
833                     goto end;
834                 }
835             }
836         }
837
838         if (startdate == NULL) {
839             startdate = NCONF_get_string(conf, section, ENV_DEFAULT_STARTDATE);
840             if (startdate == NULL)
841                 ERR_clear_error();
842         }
843         if (startdate != NULL && !ASN1_TIME_set_string_X509(NULL, startdate)) {
844             BIO_printf(bio_err,
845                        "start date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n");
846             goto end;
847         }
848         if (startdate == NULL)
849             startdate = "today";
850
851         if (enddate == NULL) {
852             enddate = NCONF_get_string(conf, section, ENV_DEFAULT_ENDDATE);
853             if (enddate == NULL)
854                 ERR_clear_error();
855         }
856         if (enddate != NULL && !ASN1_TIME_set_string_X509(NULL, enddate)) {
857             BIO_printf(bio_err,
858                        "end date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n");
859             goto end;
860         }
861
862         if (days == 0) {
863             if (!NCONF_get_number(conf, section, ENV_DEFAULT_DAYS, &days))
864                 days = 0;
865         }
866         if (enddate == NULL && days == 0) {
867             BIO_printf(bio_err, "cannot lookup how many days to certify for\n");
868             goto end;
869         }
870
871         if (rand_ser) {
872             if ((serial = BN_new()) == NULL || !rand_serial(serial, NULL)) {
873                 BIO_printf(bio_err, "error generating serial number\n");
874                 goto end;
875             }
876         } else {
877             if ((serial = load_serial(serialfile, create_ser, NULL)) == NULL) {
878                 BIO_printf(bio_err, "error while loading serial number\n");
879                 goto end;
880             }
881             if (verbose) {
882                 if (BN_is_zero(serial)) {
883                     BIO_printf(bio_err, "next serial number is 00\n");
884                 } else {
885                     if ((f = BN_bn2hex(serial)) == NULL)
886                         goto end;
887                     BIO_printf(bio_err, "next serial number is %s\n", f);
888                     OPENSSL_free(f);
889                 }
890             }
891         }
892
893         if ((attribs = NCONF_get_section(conf, policy)) == NULL) {
894             BIO_printf(bio_err, "unable to find 'section' for %s\n", policy);
895             goto end;
896         }
897
898         if ((cert_sk = sk_X509_new_null()) == NULL) {
899             BIO_printf(bio_err, "Memory allocation failure\n");
900             goto end;
901         }
902         if (spkac_file != NULL) {
903             total++;
904             j = certify_spkac(&x, spkac_file, pkey, x509, dgst, sigopts,
905                               attribs, db, serial, subj, chtype, multirdn,
906                               email_dn, startdate, enddate, days, extensions,
907                               conf, verbose, certopt, get_nameopt(), default_op,
908                               ext_copy);
909             if (j < 0)
910                 goto end;
911             if (j > 0) {
912                 total_done++;
913                 BIO_printf(bio_err, "\n");
914                 if (!BN_add_word(serial, 1))
915                     goto end;
916                 if (!sk_X509_push(cert_sk, x)) {
917                     BIO_printf(bio_err, "Memory allocation failure\n");
918                     goto end;
919                 }
920             }
921         }
922         if (ss_cert_file != NULL) {
923             total++;
924             j = certify_cert(&x, ss_cert_file, pkey, x509, dgst,
925                              sigopts, vfyopts, attribs,
926                              db, serial, subj, chtype, multirdn, email_dn,
927                              startdate, enddate, days, batch, extensions,
928                              conf, verbose, certopt, get_nameopt(), default_op,
929                              ext_copy);
930             if (j < 0)
931                 goto end;
932             if (j > 0) {
933                 total_done++;
934                 BIO_printf(bio_err, "\n");
935                 if (!BN_add_word(serial, 1))
936                     goto end;
937                 if (!sk_X509_push(cert_sk, x)) {
938                     BIO_printf(bio_err, "Memory allocation failure\n");
939                     goto end;
940                 }
941             }
942         }
943         if (infile != NULL) {
944             total++;
945             j = certify(&x, infile, pkey, x509p, dgst, sigopts, vfyopts,
946                         attribs, db,
947                         serial, subj, chtype, multirdn, email_dn, startdate,
948                         enddate, days, batch, extensions, conf, verbose,
949                         certopt, get_nameopt(), default_op, ext_copy, selfsign);
950             if (j < 0)
951                 goto end;
952             if (j > 0) {
953                 total_done++;
954                 BIO_printf(bio_err, "\n");
955                 if (!BN_add_word(serial, 1))
956                     goto end;
957                 if (!sk_X509_push(cert_sk, x)) {
958                     BIO_printf(bio_err, "Memory allocation failure\n");
959                     goto end;
960                 }
961             }
962         }
963         for (i = 0; i < argc; i++) {
964             total++;
965             j = certify(&x, argv[i], pkey, x509p, dgst, sigopts, vfyopts,
966                         attribs, db,
967                         serial, subj, chtype, multirdn, email_dn, startdate,
968                         enddate, days, batch, extensions, conf, verbose,
969                         certopt, get_nameopt(), default_op, ext_copy, selfsign);
970             if (j < 0)
971                 goto end;
972             if (j > 0) {
973                 total_done++;
974                 BIO_printf(bio_err, "\n");
975                 if (!BN_add_word(serial, 1)) {
976                     X509_free(x);
977                     goto end;
978                 }
979                 if (!sk_X509_push(cert_sk, x)) {
980                     BIO_printf(bio_err, "Memory allocation failure\n");
981                     X509_free(x);
982                     goto end;
983                 }
984             }
985         }
986         /*
987          * we have a stack of newly certified certificates and a data base
988          * and serial number that need updating
989          */
990
991         if (sk_X509_num(cert_sk) > 0) {
992             if (!batch) {
993                 BIO_printf(bio_err,
994                            "\n%d out of %d certificate requests certified, commit? [y/n]",
995                            total_done, total);
996                 (void)BIO_flush(bio_err);
997                 tmp[0] = '\0';
998                 if (fgets(tmp, sizeof(tmp), stdin) == NULL) {
999                     BIO_printf(bio_err, "CERTIFICATION CANCELED: I/O error\n");
1000                     ret = 0;
1001                     goto end;
1002                 }
1003                 if (tmp[0] != 'y' && tmp[0] != 'Y') {
1004                     BIO_printf(bio_err, "CERTIFICATION CANCELED\n");
1005                     ret = 0;
1006                     goto end;
1007                 }
1008             }
1009
1010             BIO_printf(bio_err, "Write out database with %d new entries\n",
1011                        sk_X509_num(cert_sk));
1012
1013             if (serialfile != NULL
1014                     && !save_serial(serialfile, "new", serial, NULL))
1015                 goto end;
1016
1017             if (!save_index(dbfile, "new", db))
1018                 goto end;
1019         }
1020
1021         outdirlen = OPENSSL_strlcpy(new_cert, outdir, sizeof(new_cert));
1022 #ifndef OPENSSL_SYS_VMS
1023         outdirlen = OPENSSL_strlcat(new_cert, "/", sizeof(new_cert));
1024 #endif
1025
1026         if (verbose)
1027             BIO_printf(bio_err, "writing new certificates\n");
1028
1029         for (i = 0; i < sk_X509_num(cert_sk); i++) {
1030             BIO *Cout = NULL;
1031             X509 *xi = sk_X509_value(cert_sk, i);
1032             ASN1_INTEGER *serialNumber = X509_get_serialNumber(xi);
1033             const unsigned char *psn = ASN1_STRING_get0_data(serialNumber);
1034             const int snl = ASN1_STRING_length(serialNumber);
1035             const int filen_len = 2 * (snl > 0 ? snl : 1) + sizeof(".pem");
1036             char *n = new_cert + outdirlen;
1037
1038             if (outdirlen + filen_len > PATH_MAX) {
1039                 BIO_printf(bio_err, "certificate file name too long\n");
1040                 goto end;
1041             }
1042
1043             if (snl > 0) {
1044                 static const char HEX_DIGITS[] = "0123456789ABCDEF";
1045
1046                 for (j = 0; j < snl; j++, psn++) {
1047                     *n++ = HEX_DIGITS[*psn >> 4];
1048                     *n++ = HEX_DIGITS[*psn & 0x0F];
1049                 }
1050             } else {
1051                 *(n++) = '0';
1052                 *(n++) = '0';
1053             }
1054             *(n++) = '.';
1055             *(n++) = 'p';
1056             *(n++) = 'e';
1057             *(n++) = 'm';
1058             *n = '\0';          /* closing new_cert */
1059             if (verbose)
1060                 BIO_printf(bio_err, "writing %s\n", new_cert);
1061
1062             Sout = bio_open_default(outfile, 'w',
1063                                     output_der ? FORMAT_ASN1 : FORMAT_TEXT);
1064             if (Sout == NULL)
1065                 goto end;
1066
1067             Cout = BIO_new_file(new_cert, "w");
1068             if (Cout == NULL) {
1069                 perror(new_cert);
1070                 goto end;
1071             }
1072             write_new_certificate(Cout, xi, 0, notext);
1073             write_new_certificate(Sout, xi, output_der, notext);
1074             BIO_free_all(Cout);
1075             BIO_free_all(Sout);
1076             Sout = NULL;
1077         }
1078
1079         if (sk_X509_num(cert_sk)) {
1080             /* Rename the database and the serial file */
1081             if (serialfile != NULL
1082                     && !rotate_serial(serialfile, "new", "old"))
1083                 goto end;
1084
1085             if (!rotate_index(dbfile, "new", "old"))
1086                 goto end;
1087
1088             BIO_printf(bio_err, "Data Base Updated\n");
1089         }
1090     }
1091
1092     /*****************************************************************/
1093     if (gencrl) {
1094         int crl_v2 = 0;
1095         if (crl_ext == NULL) {
1096             crl_ext = NCONF_get_string(conf, section, ENV_CRLEXT);
1097             if (crl_ext == NULL)
1098                 ERR_clear_error();
1099         }
1100         if (crl_ext != NULL) {
1101             /* Check syntax of file */
1102             X509V3_CTX ctx;
1103             X509V3_set_ctx_test(&ctx);
1104             X509V3_set_nconf(&ctx, conf);
1105             if (!X509V3_EXT_add_nconf(conf, &ctx, crl_ext, NULL)) {
1106                 BIO_printf(bio_err,
1107                            "Error Loading CRL extension section %s\n", crl_ext);
1108                 ret = 1;
1109                 goto end;
1110             }
1111         }
1112
1113         if ((crlnumberfile = NCONF_get_string(conf, section, ENV_CRLNUMBER))
1114             != NULL)
1115             if ((crlnumber = load_serial(crlnumberfile, 0, NULL)) == NULL) {
1116                 BIO_printf(bio_err, "error while loading CRL number\n");
1117                 goto end;
1118             }
1119
1120         if (!crldays && !crlhours && !crlsec) {
1121             if (!NCONF_get_number(conf, section,
1122                                   ENV_DEFAULT_CRL_DAYS, &crldays))
1123                 crldays = 0;
1124             if (!NCONF_get_number(conf, section,
1125                                   ENV_DEFAULT_CRL_HOURS, &crlhours))
1126                 crlhours = 0;
1127             ERR_clear_error();
1128         }
1129         if ((crldays == 0) && (crlhours == 0) && (crlsec == 0)) {
1130             BIO_printf(bio_err,
1131                        "cannot lookup how long until the next CRL is issued\n");
1132             goto end;
1133         }
1134
1135         if (verbose)
1136             BIO_printf(bio_err, "making CRL\n");
1137         if ((crl = X509_CRL_new()) == NULL)
1138             goto end;
1139         if (!X509_CRL_set_issuer_name(crl, X509_get_subject_name(x509)))
1140             goto end;
1141
1142         tmptm = ASN1_TIME_new();
1143         if (tmptm == NULL
1144                 || X509_gmtime_adj(tmptm, 0) == NULL
1145                 || !X509_CRL_set1_lastUpdate(crl, tmptm)
1146                 || X509_time_adj_ex(tmptm, crldays, crlhours * 60 * 60 + crlsec,
1147                                     NULL) == NULL) {
1148             BIO_puts(bio_err, "error setting CRL nextUpdate\n");
1149             ASN1_TIME_free(tmptm);
1150             goto end;
1151         }
1152         X509_CRL_set1_nextUpdate(crl, tmptm);
1153
1154         ASN1_TIME_free(tmptm);
1155
1156         for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
1157             pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
1158             if (pp[DB_type][0] == DB_TYPE_REV) {
1159                 if ((r = X509_REVOKED_new()) == NULL)
1160                     goto end;
1161                 j = make_revoked(r, pp[DB_rev_date]);
1162                 if (!j)
1163                     goto end;
1164                 if (j == 2)
1165                     crl_v2 = 1;
1166                 if (!BN_hex2bn(&serial, pp[DB_serial]))
1167                     goto end;
1168                 tmpser = BN_to_ASN1_INTEGER(serial, NULL);
1169                 BN_free(serial);
1170                 serial = NULL;
1171                 if (!tmpser)
1172                     goto end;
1173                 X509_REVOKED_set_serialNumber(r, tmpser);
1174                 ASN1_INTEGER_free(tmpser);
1175                 X509_CRL_add0_revoked(crl, r);
1176             }
1177         }
1178
1179         /*
1180          * sort the data so it will be written in serial number order
1181          */
1182         X509_CRL_sort(crl);
1183
1184         /* we now have a CRL */
1185         if (verbose)
1186             BIO_printf(bio_err, "signing CRL\n");
1187
1188         /* Add any extensions asked for */
1189
1190         if (crl_ext != NULL || crlnumberfile != NULL) {
1191             X509V3_CTX crlctx;
1192             X509V3_set_ctx(&crlctx, x509, NULL, NULL, crl, 0);
1193             X509V3_set_nconf(&crlctx, conf);
1194
1195             if (crl_ext != NULL)
1196                 if (!X509V3_EXT_CRL_add_nconf(conf, &crlctx, crl_ext, crl))
1197                     goto end;
1198             if (crlnumberfile != NULL) {
1199                 tmpser = BN_to_ASN1_INTEGER(crlnumber, NULL);
1200                 if (!tmpser)
1201                     goto end;
1202                 X509_CRL_add1_ext_i2d(crl, NID_crl_number, tmpser, 0, 0);
1203                 ASN1_INTEGER_free(tmpser);
1204                 crl_v2 = 1;
1205                 if (!BN_add_word(crlnumber, 1))
1206                     goto end;
1207             }
1208         }
1209         if (crl_ext != NULL || crl_v2) {
1210             if (!X509_CRL_set_version(crl, 1))
1211                 goto end;       /* version 2 CRL */
1212         }
1213
1214         /* we have a CRL number that need updating */
1215         if (crlnumberfile != NULL
1216                 && !save_serial(crlnumberfile, "new", crlnumber, NULL))
1217             goto end;
1218
1219         BN_free(crlnumber);
1220         crlnumber = NULL;
1221
1222         if (!do_X509_CRL_sign(crl, pkey, dgst, sigopts))
1223             goto end;
1224
1225         Sout = bio_open_default(outfile, 'w',
1226                                 output_der ? FORMAT_ASN1 : FORMAT_TEXT);
1227         if (Sout == NULL)
1228             goto end;
1229
1230         PEM_write_bio_X509_CRL(Sout, crl);
1231
1232         /* Rename the crlnumber file */
1233         if (crlnumberfile != NULL
1234                 && !rotate_serial(crlnumberfile, "new", "old"))
1235             goto end;
1236
1237     }
1238     /*****************************************************************/
1239     if (dorevoke) {
1240         if (infile == NULL) {
1241             BIO_printf(bio_err, "no input files\n");
1242             goto end;
1243         } else {
1244             X509 *revcert;
1245             revcert = load_cert(infile, FORMAT_PEM, infile);
1246             if (revcert == NULL)
1247                 goto end;
1248             if (dorevoke == 2)
1249                 rev_type = REV_VALID;
1250             j = do_revoke(revcert, db, rev_type, rev_arg);
1251             if (j <= 0)
1252                 goto end;
1253             X509_free(revcert);
1254
1255             if (!save_index(dbfile, "new", db))
1256                 goto end;
1257
1258             if (!rotate_index(dbfile, "new", "old"))
1259                 goto end;
1260
1261             BIO_printf(bio_err, "Data Base Updated\n");
1262         }
1263     }
1264     ret = 0;
1265
1266  end:
1267     if (ret)
1268         ERR_print_errors(bio_err);
1269     BIO_free_all(Sout);
1270     BIO_free_all(out);
1271     BIO_free_all(in);
1272     sk_X509_pop_free(cert_sk, X509_free);
1273
1274     if (free_key)
1275         OPENSSL_free(key);
1276     BN_free(serial);
1277     BN_free(crlnumber);
1278     free_index(db);
1279     sk_OPENSSL_STRING_free(sigopts);
1280     sk_OPENSSL_STRING_free(vfyopts);
1281     EVP_PKEY_free(pkey);
1282     X509_free(x509);
1283     X509_CRL_free(crl);
1284     NCONF_free(conf);
1285     NCONF_free(extconf);
1286     release_engine(e);
1287     return ret;
1288 }
1289
1290 static char *lookup_conf(const CONF *conf, const char *section, const char *tag)
1291 {
1292     char *entry = NCONF_get_string(conf, section, tag);
1293     if (entry == NULL)
1294         BIO_printf(bio_err, "variable lookup failed for %s::%s\n", section, tag);
1295     return entry;
1296 }
1297
1298 static int certify(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509,
1299                    const EVP_MD *dgst,
1300                    STACK_OF(OPENSSL_STRING) *sigopts,
1301                    STACK_OF(OPENSSL_STRING) *vfyopts,
1302                    STACK_OF(CONF_VALUE) *policy, CA_DB *db,
1303                    BIGNUM *serial, const char *subj, unsigned long chtype,
1304                    int multirdn, int email_dn, const char *startdate,
1305                    const char *enddate,
1306                    long days, int batch, const char *ext_sect, CONF *lconf,
1307                    int verbose, unsigned long certopt, unsigned long nameopt,
1308                    int default_op, int ext_copy, int selfsign)
1309 {
1310     X509_REQ *req = NULL;
1311     BIO *in = NULL;
1312     EVP_PKEY *pktmp = NULL;
1313     int ok = -1, i;
1314
1315     in = BIO_new_file(infile, "r");
1316     if (in == NULL) {
1317         ERR_print_errors(bio_err);
1318         goto end;
1319     }
1320     if ((req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL)) == NULL) {
1321         BIO_printf(bio_err, "Error reading certificate request in %s\n",
1322                    infile);
1323         goto end;
1324     }
1325     if (verbose)
1326         X509_REQ_print_ex(bio_err, req, nameopt, X509_FLAG_COMPAT);
1327
1328     BIO_printf(bio_err, "Check that the request matches the signature\n");
1329
1330     if (selfsign && !X509_REQ_check_private_key(req, pkey)) {
1331         BIO_printf(bio_err,
1332                    "Certificate request and CA private key do not match\n");
1333         ok = 0;
1334         goto end;
1335     }
1336     if ((pktmp = X509_REQ_get0_pubkey(req)) == NULL) {
1337         BIO_printf(bio_err, "error unpacking public key\n");
1338         goto end;
1339     }
1340     i = do_X509_REQ_verify(req, pktmp, vfyopts);
1341     pktmp = NULL;
1342     if (i < 0) {
1343         ok = 0;
1344         BIO_printf(bio_err, "Signature verification problems....\n");
1345         ERR_print_errors(bio_err);
1346         goto end;
1347     }
1348     if (i == 0) {
1349         ok = 0;
1350         BIO_printf(bio_err,
1351                    "Signature did not match the certificate request\n");
1352         ERR_print_errors(bio_err);
1353         goto end;
1354     } else {
1355         BIO_printf(bio_err, "Signature ok\n");
1356     }
1357
1358     ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj,
1359                  chtype, multirdn, email_dn, startdate, enddate, days, batch,
1360                  verbose, req, ext_sect, lconf, certopt, nameopt, default_op,
1361                  ext_copy, selfsign);
1362
1363  end:
1364     X509_REQ_free(req);
1365     BIO_free(in);
1366     return ok;
1367 }
1368
1369 static int certify_cert(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509,
1370                         const EVP_MD *dgst,
1371                         STACK_OF(OPENSSL_STRING) *sigopts,
1372                         STACK_OF(OPENSSL_STRING) *vfyopts,
1373                         STACK_OF(CONF_VALUE) *policy, CA_DB *db,
1374                         BIGNUM *serial, const char *subj, unsigned long chtype,
1375                         int multirdn, int email_dn, const char *startdate,
1376                         const char *enddate, long days, int batch, const char *ext_sect,
1377                         CONF *lconf, int verbose, unsigned long certopt,
1378                         unsigned long nameopt, int default_op, int ext_copy)
1379 {
1380     X509 *req = NULL;
1381     X509_REQ *rreq = NULL;
1382     EVP_PKEY *pktmp = NULL;
1383     int ok = -1, i;
1384
1385     if ((req = load_cert(infile, FORMAT_PEM, infile)) == NULL)
1386         goto end;
1387     if (verbose)
1388         X509_print(bio_err, req);
1389
1390     BIO_printf(bio_err, "Check that the request matches the signature\n");
1391
1392     if ((pktmp = X509_get0_pubkey(req)) == NULL) {
1393         BIO_printf(bio_err, "error unpacking public key\n");
1394         goto end;
1395     }
1396     i = do_X509_verify(req, pktmp, vfyopts);
1397     if (i < 0) {
1398         ok = 0;
1399         BIO_printf(bio_err, "Signature verification problems....\n");
1400         goto end;
1401     }
1402     if (i == 0) {
1403         ok = 0;
1404         BIO_printf(bio_err, "Signature did not match the certificate\n");
1405         goto end;
1406     } else {
1407         BIO_printf(bio_err, "Signature ok\n");
1408     }
1409
1410     if ((rreq = X509_to_X509_REQ(req, NULL, NULL)) == NULL)
1411         goto end;
1412
1413     ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj,
1414                  chtype, multirdn, email_dn, startdate, enddate, days, batch,
1415                  verbose, rreq, ext_sect, lconf, certopt, nameopt, default_op,
1416                  ext_copy, 0);
1417
1418  end:
1419     X509_REQ_free(rreq);
1420     X509_free(req);
1421     return ok;
1422 }
1423
1424 static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509,
1425                    const EVP_MD *dgst, STACK_OF(OPENSSL_STRING) *sigopts,
1426                    STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial,
1427                    const char *subj, unsigned long chtype, int multirdn,
1428                    int email_dn, const char *startdate, const char *enddate, long days,
1429                    int batch, int verbose, X509_REQ *req, const char *ext_sect,
1430                    CONF *lconf, unsigned long certopt, unsigned long nameopt,
1431                    int default_op, int ext_copy, int selfsign)
1432 {
1433     const X509_NAME *name = NULL;
1434     X509_NAME *CAname = NULL, *subject = NULL;
1435     const ASN1_TIME *tm;
1436     ASN1_STRING *str, *str2;
1437     ASN1_OBJECT *obj;
1438     X509 *ret = NULL;
1439     X509_NAME_ENTRY *ne, *tne;
1440     EVP_PKEY *pktmp;
1441     int ok = -1, i, j, last, nid;
1442     const char *p;
1443     CONF_VALUE *cv;
1444     OPENSSL_STRING row[DB_NUMBER];
1445     OPENSSL_STRING *irow = NULL;
1446     OPENSSL_STRING *rrow = NULL;
1447     char buf[25];
1448
1449     for (i = 0; i < DB_NUMBER; i++)
1450         row[i] = NULL;
1451
1452     if (subj) {
1453         X509_NAME *n = parse_name(subj, chtype, multirdn);
1454
1455         if (!n) {
1456             ERR_print_errors(bio_err);
1457             goto end;
1458         }
1459         X509_REQ_set_subject_name(req, n);
1460         X509_NAME_free(n);
1461     }
1462
1463     if (default_op)
1464         BIO_printf(bio_err, "The Subject's Distinguished Name is as follows\n");
1465
1466     name = X509_REQ_get_subject_name(req);
1467     for (i = 0; i < X509_NAME_entry_count(name); i++) {
1468         ne = X509_NAME_get_entry(name, i);
1469         str = X509_NAME_ENTRY_get_data(ne);
1470         obj = X509_NAME_ENTRY_get_object(ne);
1471         nid = OBJ_obj2nid(obj);
1472
1473         if (msie_hack) {
1474             /* assume all type should be strings */
1475
1476             if (str->type == V_ASN1_UNIVERSALSTRING)
1477                 ASN1_UNIVERSALSTRING_to_string(str);
1478
1479             if (str->type == V_ASN1_IA5STRING && nid != NID_pkcs9_emailAddress)
1480                 str->type = V_ASN1_T61STRING;
1481
1482             if (nid == NID_pkcs9_emailAddress
1483                 && str->type == V_ASN1_PRINTABLESTRING)
1484                 str->type = V_ASN1_IA5STRING;
1485         }
1486
1487         /* If no EMAIL is wanted in the subject */
1488         if (nid == NID_pkcs9_emailAddress && !email_dn)
1489             continue;
1490
1491         /* check some things */
1492         if (nid == NID_pkcs9_emailAddress && str->type != V_ASN1_IA5STRING) {
1493             BIO_printf(bio_err,
1494                        "\nemailAddress type needs to be of type IA5STRING\n");
1495             goto end;
1496         }
1497         if (str->type != V_ASN1_BMPSTRING && str->type != V_ASN1_UTF8STRING) {
1498             j = ASN1_PRINTABLE_type(str->data, str->length);
1499             if ((j == V_ASN1_T61STRING && str->type != V_ASN1_T61STRING) ||
1500                 (j == V_ASN1_IA5STRING && str->type == V_ASN1_PRINTABLESTRING))
1501             {
1502                 BIO_printf(bio_err,
1503                            "\nThe string contains characters that are illegal for the ASN.1 type\n");
1504                 goto end;
1505             }
1506         }
1507
1508         if (default_op)
1509             old_entry_print(obj, str);
1510     }
1511
1512     /* Ok, now we check the 'policy' stuff. */
1513     if ((subject = X509_NAME_new()) == NULL) {
1514         BIO_printf(bio_err, "Memory allocation failure\n");
1515         goto end;
1516     }
1517
1518     /* take a copy of the issuer name before we mess with it. */
1519     if (selfsign)
1520         CAname = X509_NAME_dup(name);
1521     else
1522         CAname = X509_NAME_dup(X509_get_subject_name(x509));
1523     if (CAname == NULL)
1524         goto end;
1525     str = str2 = NULL;
1526
1527     for (i = 0; i < sk_CONF_VALUE_num(policy); i++) {
1528         cv = sk_CONF_VALUE_value(policy, i); /* get the object id */
1529         if ((j = OBJ_txt2nid(cv->name)) == NID_undef) {
1530             BIO_printf(bio_err,
1531                        "%s:unknown object type in 'policy' configuration\n",
1532                        cv->name);
1533             goto end;
1534         }
1535         obj = OBJ_nid2obj(j);
1536
1537         last = -1;
1538         for (;;) {
1539             X509_NAME_ENTRY *push = NULL;
1540
1541             /* lookup the object in the supplied name list */
1542             j = X509_NAME_get_index_by_OBJ(name, obj, last);
1543             if (j < 0) {
1544                 if (last != -1)
1545                     break;
1546                 tne = NULL;
1547             } else {
1548                 tne = X509_NAME_get_entry(name, j);
1549             }
1550             last = j;
1551
1552             /* depending on the 'policy', decide what to do. */
1553             if (strcmp(cv->value, "optional") == 0) {
1554                 if (tne != NULL)
1555                     push = tne;
1556             } else if (strcmp(cv->value, "supplied") == 0) {
1557                 if (tne == NULL) {
1558                     BIO_printf(bio_err,
1559                                "The %s field needed to be supplied and was missing\n",
1560                                cv->name);
1561                     goto end;
1562                 } else {
1563                     push = tne;
1564                 }
1565             } else if (strcmp(cv->value, "match") == 0) {
1566                 int last2;
1567
1568                 if (tne == NULL) {
1569                     BIO_printf(bio_err,
1570                                "The mandatory %s field was missing\n",
1571                                cv->name);
1572                     goto end;
1573                 }
1574
1575                 last2 = -1;
1576
1577  again2:
1578                 j = X509_NAME_get_index_by_OBJ(CAname, obj, last2);
1579                 if ((j < 0) && (last2 == -1)) {
1580                     BIO_printf(bio_err,
1581                                "The %s field does not exist in the CA certificate,\n"
1582                                "the 'policy' is misconfigured\n", cv->name);
1583                     goto end;
1584                 }
1585                 if (j >= 0) {
1586                     push = X509_NAME_get_entry(CAname, j);
1587                     str = X509_NAME_ENTRY_get_data(tne);
1588                     str2 = X509_NAME_ENTRY_get_data(push);
1589                     last2 = j;
1590                     if (ASN1_STRING_cmp(str, str2) != 0)
1591                         goto again2;
1592                 }
1593                 if (j < 0) {
1594                     BIO_printf(bio_err,
1595                                "The %s field is different between\n"
1596                                "CA certificate (%s) and the request (%s)\n",
1597                                cv->name,
1598                                ((str2 == NULL) ? "NULL" : (char *)str2->data),
1599                                ((str == NULL) ? "NULL" : (char *)str->data));
1600                     goto end;
1601                 }
1602             } else {
1603                 BIO_printf(bio_err,
1604                            "%s:invalid type in 'policy' configuration\n",
1605                            cv->value);
1606                 goto end;
1607             }
1608
1609             if (push != NULL) {
1610                 if (!X509_NAME_add_entry(subject, push, -1, 0)) {
1611                     BIO_printf(bio_err, "Memory allocation failure\n");
1612                     goto end;
1613                 }
1614             }
1615             if (j < 0)
1616                 break;
1617         }
1618     }
1619
1620     if (preserve) {
1621         X509_NAME_free(subject);
1622         /* subject=X509_NAME_dup(X509_REQ_get_subject_name(req)); */
1623         subject = X509_NAME_dup(name);
1624         if (subject == NULL)
1625             goto end;
1626     }
1627
1628     /* We are now totally happy, lets make and sign the certificate */
1629     if (verbose)
1630         BIO_printf(bio_err,
1631                    "Everything appears to be ok, creating and signing the certificate\n");
1632
1633     if ((ret = X509_new()) == NULL)
1634         goto end;
1635
1636 #ifdef X509_V3
1637     /* Make it an X509 v3 certificate. */
1638     if (!X509_set_version(ret, 2))
1639         goto end;
1640 #endif
1641
1642     if (BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(ret)) == NULL)
1643         goto end;
1644     if (selfsign) {
1645         if (!X509_set_issuer_name(ret, subject))
1646             goto end;
1647     } else {
1648         if (!X509_set_issuer_name(ret, X509_get_subject_name(x509)))
1649             goto end;
1650     }
1651
1652     if (!set_cert_times(ret, startdate, enddate, days))
1653         goto end;
1654
1655     if (enddate != NULL) {
1656         int tdays;
1657
1658         if (!ASN1_TIME_diff(&tdays, NULL, NULL, X509_get0_notAfter(ret)))
1659             goto end;
1660         days = tdays;
1661     }
1662
1663     if (!X509_set_subject_name(ret, subject))
1664         goto end;
1665
1666     pktmp = X509_REQ_get0_pubkey(req);
1667     i = X509_set_pubkey(ret, pktmp);
1668     if (!i)
1669         goto end;
1670
1671     /* Lets add the extensions, if there are any */
1672     if (ext_sect) {
1673         X509V3_CTX ctx;
1674
1675         /* Initialize the context structure */
1676         if (selfsign)
1677             X509V3_set_ctx(&ctx, ret, ret, req, NULL, 0);
1678         else
1679             X509V3_set_ctx(&ctx, x509, ret, req, NULL, 0);
1680
1681         if (extconf != NULL) {
1682             if (verbose)
1683                 BIO_printf(bio_err, "Extra configuration file found\n");
1684
1685             /* Use the extconf configuration db LHASH */
1686             X509V3_set_nconf(&ctx, extconf);
1687
1688             /* Test the structure (needed?) */
1689             /* X509V3_set_ctx_test(&ctx); */
1690
1691             /* Adds exts contained in the configuration file */
1692             if (!X509V3_EXT_add_nconf(extconf, &ctx, ext_sect, ret)) {
1693                 BIO_printf(bio_err,
1694                            "ERROR: adding extensions in section %s\n",
1695                            ext_sect);
1696                 ERR_print_errors(bio_err);
1697                 goto end;
1698             }
1699             if (verbose)
1700                 BIO_printf(bio_err,
1701                            "Successfully added extensions from file.\n");
1702         } else if (ext_sect) {
1703             /* We found extensions to be set from config file */
1704             X509V3_set_nconf(&ctx, lconf);
1705
1706             if (!X509V3_EXT_add_nconf(lconf, &ctx, ext_sect, ret)) {
1707                 BIO_printf(bio_err,
1708                            "ERROR: adding extensions in section %s\n",
1709                            ext_sect);
1710                 ERR_print_errors(bio_err);
1711                 goto end;
1712             }
1713
1714             if (verbose)
1715                 BIO_printf(bio_err,
1716                            "Successfully added extensions from config\n");
1717         }
1718     }
1719
1720     /* Copy extensions from request (if any) */
1721
1722     if (!copy_extensions(ret, req, ext_copy)) {
1723         BIO_printf(bio_err, "ERROR: adding extensions from request\n");
1724         ERR_print_errors(bio_err);
1725         goto end;
1726     }
1727
1728     {
1729         const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(ret);
1730
1731         if (exts != NULL && sk_X509_EXTENSION_num(exts) > 0)
1732             /* Make it an X509 v3 certificate. */
1733             if (!X509_set_version(ret, 2))
1734                 goto end;
1735     }
1736
1737     if (verbose)
1738         BIO_printf(bio_err,
1739                    "The subject name appears to be ok, checking data base for clashes\n");
1740
1741     /* Build the correct Subject if no e-mail is wanted in the subject. */
1742     if (!email_dn) {
1743         X509_NAME_ENTRY *tmpne;
1744         X509_NAME *dn_subject;
1745
1746         /*
1747          * Its best to dup the subject DN and then delete any email addresses
1748          * because this retains its structure.
1749          */
1750         if ((dn_subject = X509_NAME_dup(subject)) == NULL) {
1751             BIO_printf(bio_err, "Memory allocation failure\n");
1752             goto end;
1753         }
1754         i = -1;
1755         while ((i = X509_NAME_get_index_by_NID(dn_subject,
1756                                                NID_pkcs9_emailAddress,
1757                                                i)) >= 0) {
1758             tmpne = X509_NAME_delete_entry(dn_subject, i--);
1759             X509_NAME_ENTRY_free(tmpne);
1760         }
1761
1762         if (!X509_set_subject_name(ret, dn_subject)) {
1763             X509_NAME_free(dn_subject);
1764             goto end;
1765         }
1766         X509_NAME_free(dn_subject);
1767     }
1768
1769     row[DB_name] = X509_NAME_oneline(X509_get_subject_name(ret), NULL, 0);
1770     if (row[DB_name] == NULL) {
1771         BIO_printf(bio_err, "Memory allocation failure\n");
1772         goto end;
1773     }
1774
1775     if (BN_is_zero(serial))
1776         row[DB_serial] = OPENSSL_strdup("00");
1777     else
1778         row[DB_serial] = BN_bn2hex(serial);
1779     if (row[DB_serial] == NULL) {
1780         BIO_printf(bio_err, "Memory allocation failure\n");
1781         goto end;
1782     }
1783
1784     if (row[DB_name][0] == '\0') {
1785         /*
1786          * An empty subject! We'll use the serial number instead. If
1787          * unique_subject is in use then we don't want different entries with
1788          * empty subjects matching each other.
1789          */
1790         OPENSSL_free(row[DB_name]);
1791         row[DB_name] = OPENSSL_strdup(row[DB_serial]);
1792         if (row[DB_name] == NULL) {
1793             BIO_printf(bio_err, "Memory allocation failure\n");
1794             goto end;
1795         }
1796     }
1797
1798     if (db->attributes.unique_subject) {
1799         OPENSSL_STRING *crow = row;
1800
1801         rrow = TXT_DB_get_by_index(db->db, DB_name, crow);
1802         if (rrow != NULL) {
1803             BIO_printf(bio_err,
1804                        "ERROR:There is already a certificate for %s\n",
1805                        row[DB_name]);
1806         }
1807     }
1808     if (rrow == NULL) {
1809         rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
1810         if (rrow != NULL) {
1811             BIO_printf(bio_err,
1812                        "ERROR:Serial number %s has already been issued,\n",
1813                        row[DB_serial]);
1814             BIO_printf(bio_err,
1815                        "      check the database/serial_file for corruption\n");
1816         }
1817     }
1818
1819     if (rrow != NULL) {
1820         BIO_printf(bio_err, "The matching entry has the following details\n");
1821         if (rrow[DB_type][0] == DB_TYPE_EXP)
1822             p = "Expired";
1823         else if (rrow[DB_type][0] == DB_TYPE_REV)
1824             p = "Revoked";
1825         else if (rrow[DB_type][0] == DB_TYPE_VAL)
1826             p = "Valid";
1827         else
1828             p = "\ninvalid type, Data base error\n";
1829         BIO_printf(bio_err, "Type          :%s\n", p);;
1830         if (rrow[DB_type][0] == DB_TYPE_REV) {
1831             p = rrow[DB_exp_date];
1832             if (p == NULL)
1833                 p = "undef";
1834             BIO_printf(bio_err, "Was revoked on:%s\n", p);
1835         }
1836         p = rrow[DB_exp_date];
1837         if (p == NULL)
1838             p = "undef";
1839         BIO_printf(bio_err, "Expires on    :%s\n", p);
1840         p = rrow[DB_serial];
1841         if (p == NULL)
1842             p = "undef";
1843         BIO_printf(bio_err, "Serial Number :%s\n", p);
1844         p = rrow[DB_file];
1845         if (p == NULL)
1846             p = "undef";
1847         BIO_printf(bio_err, "File name     :%s\n", p);
1848         p = rrow[DB_name];
1849         if (p == NULL)
1850             p = "undef";
1851         BIO_printf(bio_err, "Subject Name  :%s\n", p);
1852         ok = -1;                /* This is now a 'bad' error. */
1853         goto end;
1854     }
1855
1856     if (!default_op) {
1857         BIO_printf(bio_err, "Certificate Details:\n");
1858         /*
1859          * Never print signature details because signature not present
1860          */
1861         certopt |= X509_FLAG_NO_SIGDUMP | X509_FLAG_NO_SIGNAME;
1862         X509_print_ex(bio_err, ret, nameopt, certopt);
1863     }
1864
1865     BIO_printf(bio_err, "Certificate is to be certified until ");
1866     ASN1_TIME_print(bio_err, X509_get0_notAfter(ret));
1867     if (days)
1868         BIO_printf(bio_err, " (%ld days)", days);
1869     BIO_printf(bio_err, "\n");
1870
1871     if (!batch) {
1872
1873         BIO_printf(bio_err, "Sign the certificate? [y/n]:");
1874         (void)BIO_flush(bio_err);
1875         buf[0] = '\0';
1876         if (fgets(buf, sizeof(buf), stdin) == NULL) {
1877             BIO_printf(bio_err,
1878                        "CERTIFICATE WILL NOT BE CERTIFIED: I/O error\n");
1879             ok = 0;
1880             goto end;
1881         }
1882         if (!(buf[0] == 'y' || buf[0] == 'Y')) {
1883             BIO_printf(bio_err, "CERTIFICATE WILL NOT BE CERTIFIED\n");
1884             ok = 0;
1885             goto end;
1886         }
1887     }
1888
1889     pktmp = X509_get0_pubkey(ret);
1890     if (EVP_PKEY_missing_parameters(pktmp) &&
1891         !EVP_PKEY_missing_parameters(pkey))
1892         EVP_PKEY_copy_parameters(pktmp, pkey);
1893
1894     if (!do_X509_sign(ret, pkey, dgst, sigopts))
1895         goto end;
1896
1897     /* We now just add it to the database as DB_TYPE_VAL('V') */
1898     row[DB_type] = OPENSSL_strdup("V");
1899     tm = X509_get0_notAfter(ret);
1900     row[DB_exp_date] = app_malloc(tm->length + 1, "row expdate");
1901     memcpy(row[DB_exp_date], tm->data, tm->length);
1902     row[DB_exp_date][tm->length] = '\0';
1903     row[DB_rev_date] = NULL;
1904     row[DB_file] = OPENSSL_strdup("unknown");
1905     if ((row[DB_type] == NULL) || (row[DB_exp_date] == NULL) ||
1906         (row[DB_file] == NULL) || (row[DB_name] == NULL)) {
1907         BIO_printf(bio_err, "Memory allocation failure\n");
1908         goto end;
1909     }
1910
1911     irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row space");
1912     for (i = 0; i < DB_NUMBER; i++)
1913         irow[i] = row[i];
1914     irow[DB_NUMBER] = NULL;
1915
1916     if (!TXT_DB_insert(db->db, irow)) {
1917         BIO_printf(bio_err, "failed to update database\n");
1918         BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error);
1919         goto end;
1920     }
1921     irow = NULL;
1922     ok = 1;
1923  end:
1924     if (ok != 1) {
1925         for (i = 0; i < DB_NUMBER; i++)
1926             OPENSSL_free(row[i]);
1927     }
1928     OPENSSL_free(irow);
1929
1930     X509_NAME_free(CAname);
1931     X509_NAME_free(subject);
1932     if (ok <= 0)
1933         X509_free(ret);
1934     else
1935         *xret = ret;
1936     return ok;
1937 }
1938
1939 static void write_new_certificate(BIO *bp, X509 *x, int output_der, int notext)
1940 {
1941
1942     if (output_der) {
1943         (void)i2d_X509_bio(bp, x);
1944         return;
1945     }
1946     if (!notext)
1947         X509_print(bp, x);
1948     PEM_write_bio_X509(bp, x);
1949 }
1950
1951 static int certify_spkac(X509 **xret, const char *infile, EVP_PKEY *pkey,
1952                          X509 *x509, const EVP_MD *dgst,
1953                          STACK_OF(OPENSSL_STRING) *sigopts,
1954                          STACK_OF(CONF_VALUE) *policy, CA_DB *db,
1955                          BIGNUM *serial, const char *subj, unsigned long chtype,
1956                          int multirdn, int email_dn, const char *startdate,
1957                          const char *enddate, long days, const char *ext_sect,
1958                          CONF *lconf, int verbose, unsigned long certopt,
1959                          unsigned long nameopt, int default_op, int ext_copy)
1960 {
1961     STACK_OF(CONF_VALUE) *sk = NULL;
1962     LHASH_OF(CONF_VALUE) *parms = NULL;
1963     X509_REQ *req = NULL;
1964     CONF_VALUE *cv = NULL;
1965     NETSCAPE_SPKI *spki = NULL;
1966     char *type, *buf;
1967     EVP_PKEY *pktmp = NULL;
1968     X509_NAME *n = NULL;
1969     X509_NAME_ENTRY *ne = NULL;
1970     int ok = -1, i, j;
1971     long errline;
1972     int nid;
1973
1974     /*
1975      * Load input file into a hash table.  (This is just an easy
1976      * way to read and parse the file, then put it into a convenient
1977      * STACK format).
1978      */
1979     parms = CONF_load(NULL, infile, &errline);
1980     if (parms == NULL) {
1981         BIO_printf(bio_err, "error on line %ld of %s\n", errline, infile);
1982         ERR_print_errors(bio_err);
1983         goto end;
1984     }
1985
1986     sk = CONF_get_section(parms, "default");
1987     if (sk_CONF_VALUE_num(sk) == 0) {
1988         BIO_printf(bio_err, "no name/value pairs found in %s\n", infile);
1989         goto end;
1990     }
1991
1992     /*
1993      * Now create a dummy X509 request structure.  We don't actually
1994      * have an X509 request, but we have many of the components
1995      * (a public key, various DN components).  The idea is that we
1996      * put these components into the right X509 request structure
1997      * and we can use the same code as if you had a real X509 request.
1998      */
1999     req = X509_REQ_new();
2000     if (req == NULL) {
2001         ERR_print_errors(bio_err);
2002         goto end;
2003     }
2004
2005     /*
2006      * Build up the subject name set.
2007      */
2008     n = X509_REQ_get_subject_name(req);
2009
2010     for (i = 0;; i++) {
2011         if (sk_CONF_VALUE_num(sk) <= i)
2012             break;
2013
2014         cv = sk_CONF_VALUE_value(sk, i);
2015         type = cv->name;
2016         /*
2017          * Skip past any leading X. X: X, etc to allow for multiple instances
2018          */
2019         for (buf = cv->name; *buf; buf++)
2020             if ((*buf == ':') || (*buf == ',') || (*buf == '.')) {
2021                 buf++;
2022                 if (*buf)
2023                     type = buf;
2024                 break;
2025             }
2026
2027         buf = cv->value;
2028         if ((nid = OBJ_txt2nid(type)) == NID_undef) {
2029             if (strcmp(type, "SPKAC") == 0) {
2030                 spki = NETSCAPE_SPKI_b64_decode(cv->value, -1);
2031                 if (spki == NULL) {
2032                     BIO_printf(bio_err,
2033                                "unable to load Netscape SPKAC structure\n");
2034                     ERR_print_errors(bio_err);
2035                     goto end;
2036                 }
2037             }
2038             continue;
2039         }
2040
2041         if (!X509_NAME_add_entry_by_NID(n, nid, chtype,
2042                                         (unsigned char *)buf, -1, -1, 0))
2043             goto end;
2044     }
2045     if (spki == NULL) {
2046         BIO_printf(bio_err, "Netscape SPKAC structure not found in %s\n",
2047                    infile);
2048         goto end;
2049     }
2050
2051     /*
2052      * Now extract the key from the SPKI structure.
2053      */
2054
2055     BIO_printf(bio_err, "Check that the SPKAC request matches the signature\n");
2056
2057     if ((pktmp = NETSCAPE_SPKI_get_pubkey(spki)) == NULL) {
2058         BIO_printf(bio_err, "error unpacking SPKAC public key\n");
2059         goto end;
2060     }
2061
2062     j = NETSCAPE_SPKI_verify(spki, pktmp);
2063     if (j <= 0) {
2064         EVP_PKEY_free(pktmp);
2065         BIO_printf(bio_err,
2066                    "signature verification failed on SPKAC public key\n");
2067         goto end;
2068     }
2069     BIO_printf(bio_err, "Signature ok\n");
2070
2071     X509_REQ_set_pubkey(req, pktmp);
2072     EVP_PKEY_free(pktmp);
2073     ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj,
2074                  chtype, multirdn, email_dn, startdate, enddate, days, 1,
2075                  verbose, req, ext_sect, lconf, certopt, nameopt, default_op,
2076                  ext_copy, 0);
2077  end:
2078     X509_REQ_free(req);
2079     CONF_free(parms);
2080     NETSCAPE_SPKI_free(spki);
2081     X509_NAME_ENTRY_free(ne);
2082
2083     return ok;
2084 }
2085
2086 static int check_time_format(const char *str)
2087 {
2088     return ASN1_TIME_set_string(NULL, str);
2089 }
2090
2091 static int do_revoke(X509 *x509, CA_DB *db, REVINFO_TYPE rev_type,
2092                      const char *value)
2093 {
2094     const ASN1_TIME *tm = NULL;
2095     char *row[DB_NUMBER], **rrow, **irow;
2096     char *rev_str = NULL;
2097     BIGNUM *bn = NULL;
2098     int ok = -1, i;
2099
2100     for (i = 0; i < DB_NUMBER; i++)
2101         row[i] = NULL;
2102     row[DB_name] = X509_NAME_oneline(X509_get_subject_name(x509), NULL, 0);
2103     bn = ASN1_INTEGER_to_BN(X509_get_serialNumber(x509), NULL);
2104     if (!bn)
2105         goto end;
2106     if (BN_is_zero(bn))
2107         row[DB_serial] = OPENSSL_strdup("00");
2108     else
2109         row[DB_serial] = BN_bn2hex(bn);
2110     BN_free(bn);
2111     if (row[DB_name] != NULL && row[DB_name][0] == '\0') {
2112         /* Entries with empty Subjects actually use the serial number instead */
2113         OPENSSL_free(row[DB_name]);
2114         row[DB_name] = OPENSSL_strdup(row[DB_serial]);
2115     }
2116     if ((row[DB_name] == NULL) || (row[DB_serial] == NULL)) {
2117         BIO_printf(bio_err, "Memory allocation failure\n");
2118         goto end;
2119     }
2120     /*
2121      * We have to lookup by serial number because name lookup skips revoked
2122      * certs
2123      */
2124     rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
2125     if (rrow == NULL) {
2126         BIO_printf(bio_err,
2127                    "Adding Entry with serial number %s to DB for %s\n",
2128                    row[DB_serial], row[DB_name]);
2129
2130         /* We now just add it to the database as DB_TYPE_REV('V') */
2131         row[DB_type] = OPENSSL_strdup("V");
2132         tm = X509_get0_notAfter(x509);
2133         row[DB_exp_date] = app_malloc(tm->length + 1, "row exp_data");
2134         memcpy(row[DB_exp_date], tm->data, tm->length);
2135         row[DB_exp_date][tm->length] = '\0';
2136         row[DB_rev_date] = NULL;
2137         row[DB_file] = OPENSSL_strdup("unknown");
2138
2139         if (row[DB_type] == NULL || row[DB_file] == NULL) {
2140             BIO_printf(bio_err, "Memory allocation failure\n");
2141             goto end;
2142         }
2143
2144         irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row ptr");
2145         for (i = 0; i < DB_NUMBER; i++)
2146             irow[i] = row[i];
2147         irow[DB_NUMBER] = NULL;
2148
2149         if (!TXT_DB_insert(db->db, irow)) {
2150             BIO_printf(bio_err, "failed to update database\n");
2151             BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error);
2152             OPENSSL_free(irow);
2153             goto end;
2154         }
2155
2156         for (i = 0; i < DB_NUMBER; i++)
2157             row[i] = NULL;
2158
2159         /* Revoke Certificate */
2160         if (rev_type == REV_VALID)
2161             ok = 1;
2162         else
2163             /* Retry revocation after DB insertion */
2164             ok = do_revoke(x509, db, rev_type, value);
2165
2166         goto end;
2167
2168     } else if (index_name_cmp_noconst(row, rrow)) {
2169         BIO_printf(bio_err, "ERROR:name does not match %s\n", row[DB_name]);
2170         goto end;
2171     } else if (rev_type == REV_VALID) {
2172         BIO_printf(bio_err, "ERROR:Already present, serial number %s\n",
2173                    row[DB_serial]);
2174         goto end;
2175     } else if (rrow[DB_type][0] == DB_TYPE_REV) {
2176         BIO_printf(bio_err, "ERROR:Already revoked, serial number %s\n",
2177                    row[DB_serial]);
2178         goto end;
2179     } else {
2180         BIO_printf(bio_err, "Revoking Certificate %s.\n", rrow[DB_serial]);
2181         rev_str = make_revocation_str(rev_type, value);
2182         if (!rev_str) {
2183             BIO_printf(bio_err, "Error in revocation arguments\n");
2184             goto end;
2185         }
2186         rrow[DB_type][0] = DB_TYPE_REV;
2187         rrow[DB_type][1] = '\0';
2188         rrow[DB_rev_date] = rev_str;
2189     }
2190     ok = 1;
2191  end:
2192     for (i = 0; i < DB_NUMBER; i++)
2193         OPENSSL_free(row[i]);
2194     return ok;
2195 }
2196
2197 static int get_certificate_status(const char *serial, CA_DB *db)
2198 {
2199     char *row[DB_NUMBER], **rrow;
2200     int ok = -1, i;
2201     size_t serial_len = strlen(serial);
2202
2203     /* Free Resources */
2204     for (i = 0; i < DB_NUMBER; i++)
2205         row[i] = NULL;
2206
2207     /* Malloc needed char spaces */
2208     row[DB_serial] = app_malloc(serial_len + 2, "row serial#");
2209
2210     if (serial_len % 2) {
2211         /*
2212          * Set the first char to 0
2213          */
2214         row[DB_serial][0] = '0';
2215
2216         /* Copy String from serial to row[DB_serial] */
2217         memcpy(row[DB_serial] + 1, serial, serial_len);
2218         row[DB_serial][serial_len + 1] = '\0';
2219     } else {
2220         /* Copy String from serial to row[DB_serial] */
2221         memcpy(row[DB_serial], serial, serial_len);
2222         row[DB_serial][serial_len] = '\0';
2223     }
2224
2225     /* Make it Upper Case */
2226     make_uppercase(row[DB_serial]);
2227
2228     ok = 1;
2229
2230     /* Search for the certificate */
2231     rrow = TXT_DB_get_by_index(db->db, DB_serial, row);
2232     if (rrow == NULL) {
2233         BIO_printf(bio_err, "Serial %s not present in db.\n", row[DB_serial]);
2234         ok = -1;
2235         goto end;
2236     } else if (rrow[DB_type][0] == DB_TYPE_VAL) {
2237         BIO_printf(bio_err, "%s=Valid (%c)\n",
2238                    row[DB_serial], rrow[DB_type][0]);
2239         goto end;
2240     } else if (rrow[DB_type][0] == DB_TYPE_REV) {
2241         BIO_printf(bio_err, "%s=Revoked (%c)\n",
2242                    row[DB_serial], rrow[DB_type][0]);
2243         goto end;
2244     } else if (rrow[DB_type][0] == DB_TYPE_EXP) {
2245         BIO_printf(bio_err, "%s=Expired (%c)\n",
2246                    row[DB_serial], rrow[DB_type][0]);
2247         goto end;
2248     } else if (rrow[DB_type][0] == DB_TYPE_SUSP) {
2249         BIO_printf(bio_err, "%s=Suspended (%c)\n",
2250                    row[DB_serial], rrow[DB_type][0]);
2251         goto end;
2252     } else {
2253         BIO_printf(bio_err, "%s=Unknown (%c).\n",
2254                    row[DB_serial], rrow[DB_type][0]);
2255         ok = -1;
2256     }
2257  end:
2258     for (i = 0; i < DB_NUMBER; i++) {
2259         OPENSSL_free(row[i]);
2260     }
2261     return ok;
2262 }
2263
2264 static int do_updatedb(CA_DB *db)
2265 {
2266     ASN1_UTCTIME *a_tm = NULL;
2267     int i, cnt = 0;
2268     int db_y2k, a_y2k;          /* flags = 1 if y >= 2000 */
2269     char **rrow, *a_tm_s;
2270
2271     a_tm = ASN1_UTCTIME_new();
2272     if (a_tm == NULL)
2273         return -1;
2274
2275     /* get actual time and make a string */
2276     if (X509_gmtime_adj(a_tm, 0) == NULL) {
2277         ASN1_UTCTIME_free(a_tm);
2278         return -1;
2279     }
2280     a_tm_s = app_malloc(a_tm->length + 1, "time string");
2281
2282     memcpy(a_tm_s, a_tm->data, a_tm->length);
2283     a_tm_s[a_tm->length] = '\0';
2284
2285     if (strncmp(a_tm_s, "49", 2) <= 0)
2286         a_y2k = 1;
2287     else
2288         a_y2k = 0;
2289
2290     for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
2291         rrow = sk_OPENSSL_PSTRING_value(db->db->data, i);
2292
2293         if (rrow[DB_type][0] == DB_TYPE_VAL) {
2294             /* ignore entries that are not valid */
2295             if (strncmp(rrow[DB_exp_date], "49", 2) <= 0)
2296                 db_y2k = 1;
2297             else
2298                 db_y2k = 0;
2299
2300             if (db_y2k == a_y2k) {
2301                 /* all on the same y2k side */
2302                 if (strcmp(rrow[DB_exp_date], a_tm_s) <= 0) {
2303                     rrow[DB_type][0] = DB_TYPE_EXP;
2304                     rrow[DB_type][1] = '\0';
2305                     cnt++;
2306
2307                     BIO_printf(bio_err, "%s=Expired\n", rrow[DB_serial]);
2308                 }
2309             } else if (db_y2k < a_y2k) {
2310                 rrow[DB_type][0] = DB_TYPE_EXP;
2311                 rrow[DB_type][1] = '\0';
2312                 cnt++;
2313
2314                 BIO_printf(bio_err, "%s=Expired\n", rrow[DB_serial]);
2315             }
2316
2317         }
2318     }
2319
2320     ASN1_UTCTIME_free(a_tm);
2321     OPENSSL_free(a_tm_s);
2322     return cnt;
2323 }
2324
2325 static const char *crl_reasons[] = {
2326     /* CRL reason strings */
2327     "unspecified",
2328     "keyCompromise",
2329     "CACompromise",
2330     "affiliationChanged",
2331     "superseded",
2332     "cessationOfOperation",
2333     "certificateHold",
2334     "removeFromCRL",
2335     /* Additional pseudo reasons */
2336     "holdInstruction",
2337     "keyTime",
2338     "CAkeyTime"
2339 };
2340
2341 #define NUM_REASONS OSSL_NELEM(crl_reasons)
2342
2343 /*
2344  * Given revocation information convert to a DB string. The format of the
2345  * string is: revtime[,reason,extra]. Where 'revtime' is the revocation time
2346  * (the current time). 'reason' is the optional CRL reason and 'extra' is any
2347  * additional argument
2348  */
2349
2350 static char *make_revocation_str(REVINFO_TYPE rev_type, const char *rev_arg)
2351 {
2352     char *str;
2353     const char *reason = NULL, *other = NULL;
2354     ASN1_OBJECT *otmp;
2355     ASN1_UTCTIME *revtm = NULL;
2356     int i;
2357
2358     switch (rev_type) {
2359     case REV_NONE:
2360     case REV_VALID:
2361         break;
2362
2363     case REV_CRL_REASON:
2364         for (i = 0; i < 8; i++) {
2365             if (strcasecmp(rev_arg, crl_reasons[i]) == 0) {
2366                 reason = crl_reasons[i];
2367                 break;
2368             }
2369         }
2370         if (reason == NULL) {
2371             BIO_printf(bio_err, "Unknown CRL reason %s\n", rev_arg);
2372             return NULL;
2373         }
2374         break;
2375
2376     case REV_HOLD:
2377         /* Argument is an OID */
2378         otmp = OBJ_txt2obj(rev_arg, 0);
2379         ASN1_OBJECT_free(otmp);
2380
2381         if (otmp == NULL) {
2382             BIO_printf(bio_err, "Invalid object identifier %s\n", rev_arg);
2383             return NULL;
2384         }
2385
2386         reason = "holdInstruction";
2387         other = rev_arg;
2388         break;
2389
2390     case REV_KEY_COMPROMISE:
2391     case REV_CA_COMPROMISE:
2392         /* Argument is the key compromise time  */
2393         if (!ASN1_GENERALIZEDTIME_set_string(NULL, rev_arg)) {
2394             BIO_printf(bio_err,
2395                        "Invalid time format %s. Need YYYYMMDDHHMMSSZ\n",
2396                        rev_arg);
2397             return NULL;
2398         }
2399         other = rev_arg;
2400         if (rev_type == REV_KEY_COMPROMISE)
2401             reason = "keyTime";
2402         else
2403             reason = "CAkeyTime";
2404
2405         break;
2406     }
2407
2408     revtm = X509_gmtime_adj(NULL, 0);
2409
2410     if (!revtm)
2411         return NULL;
2412
2413     i = revtm->length + 1;
2414
2415     if (reason)
2416         i += strlen(reason) + 1;
2417     if (other)
2418         i += strlen(other) + 1;
2419
2420     str = app_malloc(i, "revocation reason");
2421     OPENSSL_strlcpy(str, (char *)revtm->data, i);
2422     if (reason) {
2423         OPENSSL_strlcat(str, ",", i);
2424         OPENSSL_strlcat(str, reason, i);
2425     }
2426     if (other) {
2427         OPENSSL_strlcat(str, ",", i);
2428         OPENSSL_strlcat(str, other, i);
2429     }
2430     ASN1_UTCTIME_free(revtm);
2431     return str;
2432 }
2433
2434 /*-
2435  * Convert revocation field to X509_REVOKED entry
2436  * return code:
2437  * 0 error
2438  * 1 OK
2439  * 2 OK and some extensions added (i.e. V2 CRL)
2440  */
2441
2442 static int make_revoked(X509_REVOKED *rev, const char *str)
2443 {
2444     char *tmp = NULL;
2445     int reason_code = -1;
2446     int i, ret = 0;
2447     ASN1_OBJECT *hold = NULL;
2448     ASN1_GENERALIZEDTIME *comp_time = NULL;
2449     ASN1_ENUMERATED *rtmp = NULL;
2450
2451     ASN1_TIME *revDate = NULL;
2452
2453     i = unpack_revinfo(&revDate, &reason_code, &hold, &comp_time, str);
2454
2455     if (i == 0)
2456         goto end;
2457
2458     if (rev && !X509_REVOKED_set_revocationDate(rev, revDate))
2459         goto end;
2460
2461     if (rev && (reason_code != OCSP_REVOKED_STATUS_NOSTATUS)) {
2462         rtmp = ASN1_ENUMERATED_new();
2463         if (rtmp == NULL || !ASN1_ENUMERATED_set(rtmp, reason_code))
2464             goto end;
2465         if (!X509_REVOKED_add1_ext_i2d(rev, NID_crl_reason, rtmp, 0, 0))
2466             goto end;
2467     }
2468
2469     if (rev && comp_time) {
2470         if (!X509_REVOKED_add1_ext_i2d
2471             (rev, NID_invalidity_date, comp_time, 0, 0))
2472             goto end;
2473     }
2474     if (rev && hold) {
2475         if (!X509_REVOKED_add1_ext_i2d
2476             (rev, NID_hold_instruction_code, hold, 0, 0))
2477             goto end;
2478     }
2479
2480     if (reason_code != OCSP_REVOKED_STATUS_NOSTATUS)
2481         ret = 2;
2482     else
2483         ret = 1;
2484
2485  end:
2486
2487     OPENSSL_free(tmp);
2488     ASN1_OBJECT_free(hold);
2489     ASN1_GENERALIZEDTIME_free(comp_time);
2490     ASN1_ENUMERATED_free(rtmp);
2491     ASN1_TIME_free(revDate);
2492
2493     return ret;
2494 }
2495
2496 static int old_entry_print(const ASN1_OBJECT *obj, const ASN1_STRING *str)
2497 {
2498     char buf[25], *pbuf;
2499     const char *p;
2500     int j;
2501
2502     j = i2a_ASN1_OBJECT(bio_err, obj);
2503     pbuf = buf;
2504     for (j = 22 - j; j > 0; j--)
2505         *(pbuf++) = ' ';
2506     *(pbuf++) = ':';
2507     *(pbuf++) = '\0';
2508     BIO_puts(bio_err, buf);
2509
2510     if (str->type == V_ASN1_PRINTABLESTRING)
2511         BIO_printf(bio_err, "PRINTABLE:'");
2512     else if (str->type == V_ASN1_T61STRING)
2513         BIO_printf(bio_err, "T61STRING:'");
2514     else if (str->type == V_ASN1_IA5STRING)
2515         BIO_printf(bio_err, "IA5STRING:'");
2516     else if (str->type == V_ASN1_UNIVERSALSTRING)
2517         BIO_printf(bio_err, "UNIVERSALSTRING:'");
2518     else
2519         BIO_printf(bio_err, "ASN.1 %2d:'", str->type);
2520
2521     p = (const char *)str->data;
2522     for (j = str->length; j > 0; j--) {
2523         if ((*p >= ' ') && (*p <= '~'))
2524             BIO_printf(bio_err, "%c", *p);
2525         else if (*p & 0x80)
2526             BIO_printf(bio_err, "\\0x%02X", *p);
2527         else if ((unsigned char)*p == 0xf7)
2528             BIO_printf(bio_err, "^?");
2529         else
2530             BIO_printf(bio_err, "^%c", *p + '@');
2531         p++;
2532     }
2533     BIO_printf(bio_err, "'\n");
2534     return 1;
2535 }
2536
2537 int unpack_revinfo(ASN1_TIME **prevtm, int *preason, ASN1_OBJECT **phold,
2538                    ASN1_GENERALIZEDTIME **pinvtm, const char *str)
2539 {
2540     char *tmp;
2541     char *rtime_str, *reason_str = NULL, *arg_str = NULL, *p;
2542     int reason_code = -1;
2543     int ret = 0;
2544     unsigned int i;
2545     ASN1_OBJECT *hold = NULL;
2546     ASN1_GENERALIZEDTIME *comp_time = NULL;
2547
2548     tmp = OPENSSL_strdup(str);
2549     if (!tmp) {
2550         BIO_printf(bio_err, "memory allocation failure\n");
2551         goto end;
2552     }
2553
2554     p = strchr(tmp, ',');
2555
2556     rtime_str = tmp;
2557
2558     if (p) {
2559         *p = '\0';
2560         p++;
2561         reason_str = p;
2562         p = strchr(p, ',');
2563         if (p) {
2564             *p = '\0';
2565             arg_str = p + 1;
2566         }
2567     }
2568
2569     if (prevtm) {
2570         *prevtm = ASN1_UTCTIME_new();
2571         if (*prevtm == NULL) {
2572             BIO_printf(bio_err, "memory allocation failure\n");
2573             goto end;
2574         }
2575         if (!ASN1_UTCTIME_set_string(*prevtm, rtime_str)) {
2576             BIO_printf(bio_err, "invalid revocation date %s\n", rtime_str);
2577             goto end;
2578         }
2579     }
2580     if (reason_str) {
2581         for (i = 0; i < NUM_REASONS; i++) {
2582             if (strcasecmp(reason_str, crl_reasons[i]) == 0) {
2583                 reason_code = i;
2584                 break;
2585             }
2586         }
2587         if (reason_code == OCSP_REVOKED_STATUS_NOSTATUS) {
2588             BIO_printf(bio_err, "invalid reason code %s\n", reason_str);
2589             goto end;
2590         }
2591
2592         if (reason_code == 7) {
2593             reason_code = OCSP_REVOKED_STATUS_REMOVEFROMCRL;
2594         } else if (reason_code == 8) { /* Hold instruction */
2595             if (!arg_str) {
2596                 BIO_printf(bio_err, "missing hold instruction\n");
2597                 goto end;
2598             }
2599             reason_code = OCSP_REVOKED_STATUS_CERTIFICATEHOLD;
2600             hold = OBJ_txt2obj(arg_str, 0);
2601
2602             if (!hold) {
2603                 BIO_printf(bio_err, "invalid object identifier %s\n", arg_str);
2604                 goto end;
2605             }
2606             if (phold)
2607                 *phold = hold;
2608             else
2609                 ASN1_OBJECT_free(hold);
2610         } else if ((reason_code == 9) || (reason_code == 10)) {
2611             if (!arg_str) {
2612                 BIO_printf(bio_err, "missing compromised time\n");
2613                 goto end;
2614             }
2615             comp_time = ASN1_GENERALIZEDTIME_new();
2616             if (comp_time == NULL) {
2617                 BIO_printf(bio_err, "memory allocation failure\n");
2618                 goto end;
2619             }
2620             if (!ASN1_GENERALIZEDTIME_set_string(comp_time, arg_str)) {
2621                 BIO_printf(bio_err, "invalid compromised time %s\n", arg_str);
2622                 goto end;
2623             }
2624             if (reason_code == 9)
2625                 reason_code = OCSP_REVOKED_STATUS_KEYCOMPROMISE;
2626             else
2627                 reason_code = OCSP_REVOKED_STATUS_CACOMPROMISE;
2628         }
2629     }
2630
2631     if (preason)
2632         *preason = reason_code;
2633     if (pinvtm) {
2634         *pinvtm = comp_time;
2635         comp_time = NULL;
2636     }
2637
2638     ret = 1;
2639
2640  end:
2641
2642     OPENSSL_free(tmp);
2643     ASN1_GENERALIZEDTIME_free(comp_time);
2644
2645     return ret;
2646 }