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