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