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