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