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