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