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