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