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