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