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