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