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