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