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