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