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