Update.
[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 <sys/types.h>
65 #include <sys/stat.h>
66 #include "apps.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/pem.h>
77
78 #ifndef W_OK
79 #include <sys/file.h>
80 #endif
81
82 #undef PROG
83 #define PROG ca_main
84
85 #define BASE_SECTION    "ca"
86 #define CONFIG_FILE "lib/openssl.cnf"
87
88 #define ENV_DEFAULT_CA          "default_ca"
89
90 #define ENV_DIR                 "dir"
91 #define ENV_CERTS               "certs"
92 #define ENV_CRL_DIR             "crl_dir"
93 #define ENV_CA_DB               "CA_DB"
94 #define ENV_NEW_CERTS_DIR       "new_certs_dir"
95 #define ENV_CERTIFICATE         "certificate"
96 #define ENV_SERIAL              "serial"
97 #define ENV_CRL                 "crl"
98 #define ENV_PRIVATE_KEY         "private_key"
99 #define ENV_RANDFILE            "RANDFILE"
100 #define ENV_DEFAULT_DAYS        "default_days"
101 #define ENV_DEFAULT_STARTDATE   "default_startdate"
102 #define ENV_DEFAULT_CRL_DAYS    "default_crl_days"
103 #define ENV_DEFAULT_CRL_HOURS   "default_crl_hours"
104 #define ENV_DEFAULT_MD          "default_md"
105 #define ENV_PRESERVE            "preserve"
106 #define ENV_POLICY              "policy"
107 #define ENV_EXTENSIONS          "x509_extensions"
108 #define ENV_CRLEXT              "crl_extensions"
109 #define ENV_MSIE_HACK           "msie_hack"
110
111 #define ENV_DATABASE            "database"
112
113 #define DB_type         0
114 #define DB_exp_date     1
115 #define DB_rev_date     2
116 #define DB_serial       3       /* index - unique */
117 #define DB_file         4       
118 #define DB_name         5       /* index - unique for active */
119 #define DB_NUMBER       6
120
121 #define DB_TYPE_REV     'R'
122 #define DB_TYPE_EXP     'E'
123 #define DB_TYPE_VAL     'V'
124
125 static char *ca_usage[]={
126 "usage: ca args\n",
127 "\n",
128 " -verbose        - Talk alot while doing things\n",
129 " -config file    - A config file\n",
130 " -name arg       - The particular CA definition to use\n",
131 " -gencrl         - Generate a new CRL\n",
132 " -crldays days   - Days is when the next CRL is due\n",
133 " -crlhours hours - Hours is when the next CRL is due\n",
134 " -days arg       - number of days to certify the certificate for\n",
135 " -md arg         - md to use, one of md2, md5, sha or sha1\n",
136 " -policy arg     - The CA 'policy' to support\n",
137 " -keyfile arg    - PEM private key file\n",
138 " -key arg        - key to decode the private key if it is encrypted\n",
139 " -cert file      - The CA certificate\n",
140 " -in file        - The input PEM encoded certificate request(s)\n",
141 " -out file       - Where to put the output file(s)\n",
142 " -outdir dir     - Where to put output certificates\n",
143 " -infiles ....   - The last argument, requests to process\n",
144 " -spkac file     - File contains DN and signed public key and challenge\n",
145 " -ss_cert file   - File contains a self signed cert to sign\n",
146 " -preserveDN     - Don't re-order the DN\n",
147 " -batch          - Don't ask questions\n",
148 " -msie_hack      - msie modifications to handle all those universal strings\n",
149 " -revoke file    - Revoke a certificate (given in file)\n",
150 NULL
151 };
152
153 #ifdef EFENCE
154 extern int EF_PROTECT_FREE;
155 extern int EF_PROTECT_BELOW;
156 extern int EF_ALIGNMENT;
157 #endif
158
159 static int add_oid_section(LHASH *conf);
160 static void lookup_fail(char *name,char *tag);
161 static int MS_CALLBACK key_callback(char *buf,int len,int verify);
162 static unsigned long index_serial_hash(char **a);
163 static int index_serial_cmp(char **a, char **b);
164 static unsigned long index_name_hash(char **a);
165 static int index_name_qual(char **a);
166 static int index_name_cmp(char **a,char **b);
167 static BIGNUM *load_serial(char *serialfile);
168 static int save_serial(char *serialfile, BIGNUM *serial);
169 static int certify(X509 **xret, char *infile,EVP_PKEY *pkey,X509 *x509,
170                    const EVP_MD *dgst,STACK *policy,TXT_DB *db,BIGNUM *serial,
171                    char *startdate,int days,int batch,char *ext_sect,
172                    LHASH *conf,int verbose);
173 static int certify_cert(X509 **xret, char *infile,EVP_PKEY *pkey,X509 *x509,
174                         const EVP_MD *dgst,STACK *policy,TXT_DB *db,
175                         BIGNUM *serial,char *startdate,int days,int batch,
176                         char *ext_sect, LHASH *conf,int verbose);
177 static int certify_spkac(X509 **xret, char *infile,EVP_PKEY *pkey,X509 *x509,
178                          const EVP_MD *dgst,STACK *policy,TXT_DB *db,
179                          BIGNUM *serial,char *startdate,int days,
180                          char *ext_sect,LHASH *conf,int verbose);
181 static int fix_data(int nid, int *type);
182 static void write_new_certificate(BIO *bp, X509 *x, int output_der);
183 static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, const EVP_MD *dgst,
184         STACK *policy, TXT_DB *db, BIGNUM *serial, char *startdate,
185         int days, int batch, int verbose, X509_REQ *req, char *ext_sect,
186         LHASH *conf);
187 static int do_revoke(X509 *x509, TXT_DB *db);
188 static int check_time_format(char *str);
189 static LHASH *conf;
190 static char *key=NULL;
191 static char *section=NULL;
192
193 static int preserve=0;
194 static int msie_hack=0;
195
196 int MAIN(int argc, char **argv)
197         {
198         int total=0;
199         int total_done=0;
200         int badops=0;
201         int ret=1;
202         int req=0;
203         int verbose=0;
204         int gencrl=0;
205         int dorevoke=0;
206         long crldays=0;
207         long crlhours=0;
208         long errorline= -1;
209         char *configfile=NULL;
210         char *md=NULL;
211         char *policy=NULL;
212         char *keyfile=NULL;
213         char *certfile=NULL;
214         char *infile=NULL;
215         char *spkac_file=NULL;
216         char *ss_cert_file=NULL;
217         EVP_PKEY *pkey=NULL;
218         int output_der = 0;
219         char *outfile=NULL;
220         char *outdir=NULL;
221         char *serialfile=NULL;
222         char *extensions=NULL;
223         char *crl_ext=NULL;
224         BIGNUM *serial=NULL;
225         char *startdate=NULL;
226         int days=0;
227         int batch=0;
228         X509 *x509=NULL;
229         X509 *x=NULL;
230         BIO *in=NULL,*out=NULL,*Sout=NULL,*Cout=NULL;
231         char *dbfile=NULL;
232         TXT_DB *db=NULL;
233         X509_CRL *crl=NULL;
234         X509_CRL_INFO *ci=NULL;
235         X509_REVOKED *r=NULL;
236         char **pp,*p,*f;
237         int i,j;
238         long l;
239         const EVP_MD *dgst=NULL;
240         STACK *attribs=NULL;
241         STACK *cert_sk=NULL;
242         BIO *hex=NULL;
243 #undef BSIZE
244 #define BSIZE 256
245         MS_STATIC char buf[3][BSIZE];
246
247 #ifdef EFENCE
248 EF_PROTECT_FREE=1;
249 EF_PROTECT_BELOW=1;
250 EF_ALIGNMENT=0;
251 #endif
252
253         apps_startup();
254
255         X509V3_add_standard_extensions();
256
257         preserve=0;
258         if (bio_err == NULL)
259                 if ((bio_err=BIO_new(BIO_s_file())) != NULL)
260                         BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);
261
262         argc--;
263         argv++;
264         while (argc >= 1)
265                 {
266                 if      (strcmp(*argv,"-verbose") == 0)
267                         verbose=1;
268                 else if (strcmp(*argv,"-config") == 0)
269                         {
270                         if (--argc < 1) goto bad;
271                         configfile= *(++argv);
272                         }
273                 else if (strcmp(*argv,"-name") == 0)
274                         {
275                         if (--argc < 1) goto bad;
276                         section= *(++argv);
277                         }
278                 else if (strcmp(*argv,"-startdate") == 0)
279                         {
280                         if (--argc < 1) goto bad;
281                         startdate= *(++argv);
282                         }
283                 else if (strcmp(*argv,"-days") == 0)
284                         {
285                         if (--argc < 1) goto bad;
286                         days=atoi(*(++argv));
287                         }
288                 else if (strcmp(*argv,"-md") == 0)
289                         {
290                         if (--argc < 1) goto bad;
291                         md= *(++argv);
292                         }
293                 else if (strcmp(*argv,"-policy") == 0)
294                         {
295                         if (--argc < 1) goto bad;
296                         policy= *(++argv);
297                         }
298                 else if (strcmp(*argv,"-keyfile") == 0)
299                         {
300                         if (--argc < 1) goto bad;
301                         keyfile= *(++argv);
302                         }
303                 else if (strcmp(*argv,"-key") == 0)
304                         {
305                         if (--argc < 1) goto bad;
306                         key= *(++argv);
307                         }
308                 else if (strcmp(*argv,"-cert") == 0)
309                         {
310                         if (--argc < 1) goto bad;
311                         certfile= *(++argv);
312                         }
313                 else if (strcmp(*argv,"-in") == 0)
314                         {
315                         if (--argc < 1) goto bad;
316                         infile= *(++argv);
317                         req=1;
318                         }
319                 else if (strcmp(*argv,"-out") == 0)
320                         {
321                         if (--argc < 1) goto bad;
322                         outfile= *(++argv);
323                         }
324                 else if (strcmp(*argv,"-outdir") == 0)
325                         {
326                         if (--argc < 1) goto bad;
327                         outdir= *(++argv);
328                         }
329                 else if (strcmp(*argv,"-batch") == 0)
330                         batch=1;
331                 else if (strcmp(*argv,"-preserveDN") == 0)
332                         preserve=1;
333                 else if (strcmp(*argv,"-gencrl") == 0)
334                         gencrl=1;
335                 else if (strcmp(*argv,"-msie_hack") == 0)
336                         msie_hack=1;
337                 else if (strcmp(*argv,"-crldays") == 0)
338                         {
339                         if (--argc < 1) goto bad;
340                         crldays= atol(*(++argv));
341                         }
342                 else if (strcmp(*argv,"-crlhours") == 0)
343                         {
344                         if (--argc < 1) goto bad;
345                         crlhours= atol(*(++argv));
346                         }
347                 else if (strcmp(*argv,"-infiles") == 0)
348                         {
349                         argc--;
350                         argv++;
351                         req=1;
352                         break;
353                         }
354                 else if (strcmp(*argv, "-ss_cert") == 0)
355                         {
356                         if (--argc < 1) goto bad;
357                         ss_cert_file = *(++argv);
358                         req=1;
359                         }
360                 else if (strcmp(*argv, "-spkac") == 0)
361                         {
362                         if (--argc < 1) goto bad;
363                         spkac_file = *(++argv);
364                         req=1;
365                         }
366                 else if (strcmp(*argv,"-revoke") == 0)
367                         {
368                         if (--argc < 1) goto bad;
369                         infile= *(++argv);
370                         dorevoke=1;
371                         }
372                 else
373                         {
374 bad:
375                         BIO_printf(bio_err,"unknown option %s\n",*argv);
376                         badops=1;
377                         break;
378                         }
379                 argc--;
380                 argv++;
381                 }
382
383         if (badops)
384                 {
385                 for (pp=ca_usage; (*pp != NULL); pp++)
386                         BIO_printf(bio_err,*pp);
387                 goto err;
388                 }
389
390         ERR_load_crypto_strings();
391
392         /*****************************************************************/
393         if (configfile == NULL) configfile = getenv("OPENSSL_CONF");
394         if (configfile == NULL) configfile = getenv("SSLEAY_CONF");
395         if (configfile == NULL)
396                 {
397                 /* We will just use 'buf[0]' as a temporary buffer.  */
398                 strncpy(buf[0],X509_get_default_cert_area(),
399                         sizeof(buf[0])-2-sizeof(CONFIG_FILE));
400                 strcat(buf[0],"/");
401                 strcat(buf[0],CONFIG_FILE);
402                 configfile=buf[0];
403                 }
404
405         BIO_printf(bio_err,"Using configuration from %s\n",configfile);
406         if ((conf=CONF_load(NULL,configfile,&errorline)) == NULL)
407                 {
408                 if (errorline <= 0)
409                         BIO_printf(bio_err,"error loading the config file '%s'\n",
410                                 configfile);
411                 else
412                         BIO_printf(bio_err,"error on line %ld of config file '%s'\n"
413                                 ,errorline,configfile);
414                 goto err;
415                 }
416
417         /* Lets get the config section we are using */
418         if (section == NULL)
419                 {
420                 section=CONF_get_string(conf,BASE_SECTION,ENV_DEFAULT_CA);
421                 if (section == NULL)
422                         {
423                         lookup_fail(BASE_SECTION,ENV_DEFAULT_CA);
424                         goto err;
425                         }
426                 }
427
428         if (conf != NULL)
429                 {
430                 p=CONF_get_string(conf,NULL,"oid_file");
431                 if (p != NULL)
432                         {
433                         BIO *oid_bio;
434
435                         oid_bio=BIO_new_file(p,"r");
436                         if (oid_bio == NULL) 
437                                 {
438                                 /*
439                                 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
440                                 ERR_print_errors(bio_err);
441                                 */
442                                 ERR_clear_error();
443                                 }
444                         else
445                                 {
446                                 OBJ_create_objects(oid_bio);
447                                 BIO_free(oid_bio);
448                                 }
449                         }
450                 }
451                 if(!add_oid_section(conf)) {
452                         ERR_print_errors(bio_err);
453                         goto err;
454                 }
455
456         in=BIO_new(BIO_s_file());
457         out=BIO_new(BIO_s_file());
458         Sout=BIO_new(BIO_s_file());
459         Cout=BIO_new(BIO_s_file());
460         if ((in == NULL) || (out == NULL) || (Sout == NULL) || (Cout == NULL))
461                 {
462                 ERR_print_errors(bio_err);
463                 goto err;
464                 }
465
466         /*****************************************************************/
467         /* we definitly need an public key, so lets get it */
468
469         if ((keyfile == NULL) && ((keyfile=CONF_get_string(conf,
470                 section,ENV_PRIVATE_KEY)) == NULL))
471                 {
472                 lookup_fail(section,ENV_PRIVATE_KEY);
473                 goto err;
474                 }
475         if (BIO_read_filename(in,keyfile) <= 0)
476                 {
477                 perror(keyfile);
478                 BIO_printf(bio_err,"trying to load CA private key\n");
479                 goto err;
480                 }
481         if (key == NULL)
482                 pkey=PEM_read_bio_PrivateKey(in,NULL,NULL);
483         else
484                 {
485                 pkey=PEM_read_bio_PrivateKey(in,NULL,key_callback);
486                 memset(key,0,strlen(key));
487                 }
488         if (pkey == NULL)
489                 {
490                 BIO_printf(bio_err,"unable to load CA private key\n");
491                 goto err;
492                 }
493
494         /*****************************************************************/
495         /* we need a certificate */
496         if ((certfile == NULL) && ((certfile=CONF_get_string(conf,
497                 section,ENV_CERTIFICATE)) == NULL))
498                 {
499                 lookup_fail(section,ENV_CERTIFICATE);
500                 goto err;
501                 }
502         if (BIO_read_filename(in,certfile) <= 0)
503                 {
504                 perror(certfile);
505                 BIO_printf(bio_err,"trying to load CA certificate\n");
506                 goto err;
507                 }
508         x509=PEM_read_bio_X509(in,NULL,NULL);
509         if (x509 == NULL)
510                 {
511                 BIO_printf(bio_err,"unable to load CA certificate\n");
512                 goto err;
513                 }
514
515         if (!X509_check_private_key(x509,pkey))
516                 {
517                 BIO_printf(bio_err,"CA certificate and CA private key do not match\n");
518                 goto err;
519                 }
520
521         f=CONF_get_string(conf,BASE_SECTION,ENV_PRESERVE);
522         if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
523                 preserve=1;
524         f=CONF_get_string(conf,BASE_SECTION,ENV_MSIE_HACK);
525         if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
526                 msie_hack=1;
527
528         /*****************************************************************/
529         /* lookup where to write new certificates */
530         if ((outdir == NULL) && (req))
531                 {
532                 struct stat sb;
533
534                 if ((outdir=CONF_get_string(conf,section,ENV_NEW_CERTS_DIR))
535                         == NULL)
536                         {
537                         BIO_printf(bio_err,"there needs to be defined a directory for new certificate to be placed in\n");
538                         goto err;
539                         }
540                 if (access(outdir,R_OK|W_OK|X_OK) != 0)
541                         {
542                         BIO_printf(bio_err,"I am unable to acces the %s directory\n",outdir);
543                         perror(outdir);
544                         goto err;
545                         }
546
547                 if (stat(outdir,&sb) != 0)
548                         {
549                         BIO_printf(bio_err,"unable to stat(%s)\n",outdir);
550                         perror(outdir);
551                         goto err;
552                         }
553                 if (!(sb.st_mode & S_IFDIR))
554                         {
555                         BIO_printf(bio_err,"%s need to be a directory\n",outdir);
556                         perror(outdir);
557                         goto err;
558                         }
559                 }
560
561         /*****************************************************************/
562         /* we need to load the database file */
563         if ((dbfile=CONF_get_string(conf,section,ENV_DATABASE)) == NULL)
564                 {
565                 lookup_fail(section,ENV_DATABASE);
566                 goto err;
567                 }
568         if (BIO_read_filename(in,dbfile) <= 0)
569                 {
570                 perror(dbfile);
571                 BIO_printf(bio_err,"unable to open '%s'\n",dbfile);
572                 goto err;
573                 }
574         db=TXT_DB_read(in,DB_NUMBER);
575         if (db == NULL) goto err;
576
577         /* Lets check some fields */
578         for (i=0; i<sk_num(db->data); i++)
579                 {
580                 pp=(char **)sk_value(db->data,i);
581                 if ((pp[DB_type][0] != DB_TYPE_REV) &&
582                         (pp[DB_rev_date][0] != '\0'))
583                         {
584                         BIO_printf(bio_err,"entry %d: not revoked yet, but has a revocation date\n",i+1);
585                         goto err;
586                         }
587                 if ((pp[DB_type][0] == DB_TYPE_REV) &&
588                         !check_time_format(pp[DB_rev_date]))
589                         {
590                         BIO_printf(bio_err,"entry %d: invalid revocation date\n",
591                                 i+1);
592                         goto err;
593                         }
594                 if (!check_time_format(pp[DB_exp_date]))
595                         {
596                         BIO_printf(bio_err,"entry %d: invalid expiry date\n",i+1);
597                         goto err;
598                         }
599                 p=pp[DB_serial];
600                 j=strlen(p);
601                 if ((j&1) || (j < 2))
602                         {
603                         BIO_printf(bio_err,"entry %d: bad serial number length (%d)\n",i+1,j);
604                         goto err;
605                         }
606                 while (*p)
607                         {
608                         if (!(  ((*p >= '0') && (*p <= '9')) ||
609                                 ((*p >= 'A') && (*p <= 'F')) ||
610                                 ((*p >= 'a') && (*p <= 'f')))  )
611                                 {
612                                 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);
613                                 goto err;
614                                 }
615                         p++;
616                         }
617                 }
618         if (verbose)
619                 {
620                 BIO_set_fp(out,stdout,BIO_NOCLOSE|BIO_FP_TEXT); /* cannot fail */
621                 TXT_DB_write(out,db);
622                 BIO_printf(bio_err,"%d entries loaded from the database\n",
623                         db->data->num);
624                 BIO_printf(bio_err,"generating indexs\n");
625                 }
626         
627         if (!TXT_DB_create_index(db,DB_serial,NULL,index_serial_hash,
628                 index_serial_cmp))
629                 {
630                 BIO_printf(bio_err,"error creating serial number index:(%ld,%ld,%ld)\n",db->error,db->arg1,db->arg2);
631                 goto err;
632                 }
633
634         if (!TXT_DB_create_index(db,DB_name,index_name_qual,index_name_hash,
635                 index_name_cmp))
636                 {
637                 BIO_printf(bio_err,"error creating name index:(%ld,%ld,%ld)\n",
638                         db->error,db->arg1,db->arg2);
639                 goto err;
640                 }
641
642         /*****************************************************************/
643         if (req || gencrl)
644                 {
645                 if (outfile != NULL)
646                         {
647
648                         if (BIO_write_filename(Sout,outfile) <= 0)
649                                 {
650                                 perror(outfile);
651                                 goto err;
652                                 }
653                         }
654                 else
655                         BIO_set_fp(Sout,stdout,BIO_NOCLOSE|BIO_FP_TEXT);
656                 }
657
658         if (req)
659                 {
660                 if ((md == NULL) && ((md=CONF_get_string(conf,
661                         section,ENV_DEFAULT_MD)) == NULL))
662                         {
663                         lookup_fail(section,ENV_DEFAULT_MD);
664                         goto err;
665                         }
666                 if ((dgst=EVP_get_digestbyname(md)) == NULL)
667                         {
668                         BIO_printf(bio_err,"%s is an unsupported message digest type\n",md);
669                         goto err;
670                         }
671                 if (verbose)
672                         BIO_printf(bio_err,"message digest is %s\n",
673                                 OBJ_nid2ln(dgst->type));
674                 if ((policy == NULL) && ((policy=CONF_get_string(conf,
675                         section,ENV_POLICY)) == NULL))
676                         {
677                         lookup_fail(section,ENV_POLICY);
678                         goto err;
679                         }
680                 if (verbose)
681                         BIO_printf(bio_err,"policy is %s\n",policy);
682
683                 if ((serialfile=CONF_get_string(conf,section,ENV_SERIAL))
684                         == NULL)
685                         {
686                         lookup_fail(section,ENV_SERIAL);
687                         goto err;
688                         }
689
690                 extensions=CONF_get_string(conf,section,ENV_EXTENSIONS);
691                 if(extensions) {
692                         /* Check syntax of file */
693                         X509V3_CTX ctx;
694                         X509V3_set_ctx_test(&ctx);
695                         X509V3_set_conf_lhash(&ctx, conf);
696                         if(!X509V3_EXT_add_conf(conf, &ctx, extensions, NULL)) {
697                                 BIO_printf(bio_err,
698                                  "Error Loading extension section %s\n",
699                                                                  extensions);
700                                 ret = 1;
701                                 goto err;
702                         }
703                 }
704
705                 if (startdate == NULL)
706                         {
707                         startdate=(char *)CONF_get_string(conf,section,
708                                 ENV_DEFAULT_STARTDATE);
709                         if (startdate == NULL)
710                                 startdate="today";
711                         else
712                                 {
713                                 if (!ASN1_UTCTIME_set_string(NULL,startdate))
714                                         {
715                                         BIO_printf(bio_err,"start date is invalid, it should be YYMMDDHHMMSS\n");
716                                         goto err;
717                                         }
718                                 }
719                         }
720
721                 if (days == 0)
722                         {
723                         days=(int)CONF_get_number(conf,section,
724                                 ENV_DEFAULT_DAYS);
725                         }
726                 if (days == 0)
727                         {
728                         BIO_printf(bio_err,"cannot lookup how many days to certify for\n");
729                         goto err;
730                         }
731
732                 if ((serial=load_serial(serialfile)) == NULL)
733                         {
734                         BIO_printf(bio_err,"error while loading serial number\n");
735                         goto err;
736                         }
737                 if (verbose)
738                         {
739                         if ((f=BN_bn2hex(serial)) == NULL) goto err;
740                         BIO_printf(bio_err,"next serial number is %s\n",f);
741                         Free(f);
742                         }
743
744                 if ((attribs=CONF_get_section(conf,policy)) == NULL)
745                         {
746                         BIO_printf(bio_err,"unable to find 'section' for %s\n",policy);
747                         goto err;
748                         }
749
750                 if ((cert_sk=sk_new_null()) == NULL)
751                         {
752                         BIO_printf(bio_err,"Malloc failure\n");
753                         goto err;
754                         }
755                 if (spkac_file != NULL)
756                         {
757                         total++;
758                         j=certify_spkac(&x,spkac_file,pkey,x509,dgst,attribs,db,
759                                 serial,startdate,days,extensions,conf,verbose);
760                         if (j < 0) goto err;
761                         if (j > 0)
762                                 {
763                                 total_done++;
764                                 BIO_printf(bio_err,"\n");
765                                 if (!BN_add_word(serial,1)) goto err;
766                                 if (!sk_push(cert_sk,(char *)x))
767                                         {
768                                         BIO_printf(bio_err,"Malloc failure\n");
769                                         goto err;
770                                         }
771                                 if (outfile)
772                                         {
773                                         output_der = 1;
774                                         batch = 1;
775                                         }
776                                 }
777                         }
778                 if (ss_cert_file != NULL)
779                         {
780                         total++;
781                         j=certify_cert(&x,ss_cert_file,pkey,x509,dgst,attribs,
782                                 db,serial,startdate,days,batch,
783                                 extensions,conf,verbose);
784                         if (j < 0) goto err;
785                         if (j > 0)
786                                 {
787                                 total_done++;
788                                 BIO_printf(bio_err,"\n");
789                                 if (!BN_add_word(serial,1)) goto err;
790                                 if (!sk_push(cert_sk,(char *)x))
791                                         {
792                                         BIO_printf(bio_err,"Malloc failure\n");
793                                         goto err;
794                                         }
795                                 }
796                         }
797                 if (infile != NULL)
798                         {
799                         total++;
800                         j=certify(&x,infile,pkey,x509,dgst,attribs,db,
801                                 serial,startdate,days,batch,
802                                 extensions,conf,verbose);
803                         if (j < 0) goto err;
804                         if (j > 0)
805                                 {
806                                 total_done++;
807                                 BIO_printf(bio_err,"\n");
808                                 if (!BN_add_word(serial,1)) goto err;
809                                 if (!sk_push(cert_sk,(char *)x))
810                                         {
811                                         BIO_printf(bio_err,"Malloc failure\n");
812                                         goto err;
813                                         }
814                                 }
815                         }
816                 for (i=0; i<argc; i++)
817                         {
818                         total++;
819                         j=certify(&x,argv[i],pkey,x509,dgst,attribs,db,
820                                 serial,startdate,days,batch,
821                                 extensions,conf,verbose);
822                         if (j < 0) goto err;
823                         if (j > 0)
824                                 {
825                                 total_done++;
826                                 BIO_printf(bio_err,"\n");
827                                 if (!BN_add_word(serial,1)) goto err;
828                                 if (!sk_push(cert_sk,(char *)x))
829                                         {
830                                         BIO_printf(bio_err,"Malloc failure\n");
831                                         goto err;
832                                         }
833                                 }
834                         }       
835                 /* we have a stack of newly certified certificates
836                  * and a data base and serial number that need
837                  * updating */
838
839                 if (sk_num(cert_sk) > 0)
840                         {
841                         if (!batch)
842                                 {
843                                 BIO_printf(bio_err,"\n%d out of %d certificate requests certified, commit? [y/n]",total_done,total);
844                                 BIO_flush(bio_err);
845                                 buf[0][0]='\0';
846                                 fgets(buf[0],10,stdin);
847                                 if ((buf[0][0] != 'y') && (buf[0][0] != 'Y'))
848                                         {
849                                         BIO_printf(bio_err,"CERTIFICATION CANCELED\n"); 
850                                         ret=0;
851                                         goto err;
852                                         }
853                                 }
854
855                         BIO_printf(bio_err,"Write out database with %d new entries\n",sk_num(cert_sk));
856
857                         strncpy(buf[0],serialfile,BSIZE-4);
858                         strcat(buf[0],".new");
859
860                         if (!save_serial(buf[0],serial)) goto err;
861
862                         strncpy(buf[1],dbfile,BSIZE-4);
863                         strcat(buf[1],".new");
864                         if (BIO_write_filename(out,buf[1]) <= 0)
865                                 {
866                                 perror(dbfile);
867                                 BIO_printf(bio_err,"unable to open '%s'\n",dbfile);
868                                 goto err;
869                                 }
870                         l=TXT_DB_write(out,db);
871                         if (l <= 0) goto err;
872                         }
873         
874                 if (verbose)
875                         BIO_printf(bio_err,"writing new certificates\n");
876                 for (i=0; i<sk_num(cert_sk); i++)
877                         {
878                         int k;
879                         unsigned char *n;
880
881                         x=(X509 *)sk_value(cert_sk,i);
882
883                         j=x->cert_info->serialNumber->length;
884                         p=(char *)x->cert_info->serialNumber->data;
885                         
886                         strncpy(buf[2],outdir,BSIZE-(j*2)-6);
887                         strcat(buf[2],"/");
888                         n=(unsigned char *)&(buf[2][strlen(buf[2])]);
889                         if (j > 0)
890                                 {
891                                 for (k=0; k<j; k++)
892                                         {
893                                         sprintf((char *)n,"%02X",(unsigned char)*(p++));
894                                         n+=2;
895                                         }
896                                 }
897                         else
898                                 {
899                                 *(n++)='0';
900                                 *(n++)='0';
901                                 }
902                         *(n++)='.'; *(n++)='p'; *(n++)='e'; *(n++)='m';
903                         *n='\0';
904                         if (verbose)
905                                 BIO_printf(bio_err,"writing %s\n",buf[2]);
906
907                         if (BIO_write_filename(Cout,buf[2]) <= 0)
908                                 {
909                                 perror(buf[2]);
910                                 goto err;
911                                 }
912                         write_new_certificate(Cout,x, 0);
913                         write_new_certificate(Sout,x, output_der);
914                         }
915
916                 if (sk_num(cert_sk))
917                         {
918                         /* Rename the database and the serial file */
919                         strncpy(buf[2],serialfile,BSIZE-4);
920                         strcat(buf[2],".old");
921                         BIO_free(in);
922                         BIO_free(out);
923                         in=NULL;
924                         out=NULL;
925                         if (rename(serialfile,buf[2]) < 0)
926                                 {
927                                 BIO_printf(bio_err,"unabel to rename %s to %s\n",
928                                         serialfile,buf[2]);
929                                 perror("reason");
930                                 goto err;
931                                 }
932                         if (rename(buf[0],serialfile) < 0)
933                                 {
934                                 BIO_printf(bio_err,"unabel to rename %s to %s\n",
935                                         buf[0],serialfile);
936                                 perror("reason");
937                                 rename(buf[2],serialfile);
938                                 goto err;
939                                 }
940
941                         strncpy(buf[2],dbfile,BSIZE-4);
942                         strcat(buf[2],".old");
943                         if (rename(dbfile,buf[2]) < 0)
944                                 {
945                                 BIO_printf(bio_err,"unabel to rename %s to %s\n",
946                                         dbfile,buf[2]);
947                                 perror("reason");
948                                 goto err;
949                                 }
950                         if (rename(buf[1],dbfile) < 0)
951                                 {
952                                 BIO_printf(bio_err,"unabel to rename %s to %s\n",
953                                         buf[1],dbfile);
954                                 perror("reason");
955                                 rename(buf[2],dbfile);
956                                 goto err;
957                                 }
958                         BIO_printf(bio_err,"Data Base Updated\n");
959                         }
960                 }
961         
962         /*****************************************************************/
963         if (gencrl)
964                 {
965                 crl_ext=CONF_get_string(conf,section,ENV_CRLEXT);
966                 if(crl_ext) {
967                         /* Check syntax of file */
968                         X509V3_CTX ctx;
969                         X509V3_set_ctx_test(&ctx);
970                         X509V3_set_conf_lhash(&ctx, conf);
971                         if(!X509V3_EXT_add_conf(conf, &ctx, crl_ext, NULL)) {
972                                 BIO_printf(bio_err,
973                                  "Error Loading CRL extension section %s\n",
974                                                                  crl_ext);
975                                 ret = 1;
976                                 goto err;
977                         }
978                 }
979                 if ((hex=BIO_new(BIO_s_mem())) == NULL) goto err;
980
981                 if (!crldays && !crlhours)
982                         {
983                         crldays=CONF_get_number(conf,section,
984                                 ENV_DEFAULT_CRL_DAYS);
985                         crlhours=CONF_get_number(conf,section,
986                                 ENV_DEFAULT_CRL_HOURS);
987                         }
988                 if ((crldays == 0) && (crlhours == 0))
989                         {
990                         BIO_printf(bio_err,"cannot lookup how long until the next CRL is issuer\n");
991                         goto err;
992                         }
993
994                 if (verbose) BIO_printf(bio_err,"making CRL\n");
995                 if ((crl=X509_CRL_new()) == NULL) goto err;
996                 ci=crl->crl;
997                 X509_NAME_free(ci->issuer);
998                 ci->issuer=X509_NAME_dup(x509->cert_info->subject);
999                 if (ci->issuer == NULL) goto err;
1000
1001                 X509_gmtime_adj(ci->lastUpdate,0);
1002                 if (ci->nextUpdate == NULL)
1003                         ci->nextUpdate=ASN1_UTCTIME_new();
1004                 X509_gmtime_adj(ci->nextUpdate,(crldays*24+crlhours)*60*60);
1005
1006                 for (i=0; i<sk_num(db->data); i++)
1007                         {
1008                         pp=(char **)sk_value(db->data,i);
1009                         if (pp[DB_type][0] == DB_TYPE_REV)
1010                                 {
1011                                 if ((r=X509_REVOKED_new()) == NULL) goto err;
1012                                 ASN1_STRING_set((ASN1_STRING *)
1013                                         r->revocationDate,
1014                                         (unsigned char *)pp[DB_rev_date],
1015                                         strlen(pp[DB_rev_date]));
1016                                 /* strcpy(r->revocationDate,pp[DB_rev_date]);*/
1017
1018                                 BIO_reset(hex);
1019                                 if (!BIO_puts(hex,pp[DB_serial]))
1020                                         goto err;
1021                                 if (!a2i_ASN1_INTEGER(hex,r->serialNumber,
1022                                         buf[0],BSIZE)) goto err;
1023
1024                                 sk_push(ci->revoked,(char *)r);
1025                                 }
1026                         }
1027                 /* sort the data so it will be written in serial
1028                  * number order */
1029                 sk_find(ci->revoked,NULL);
1030                 for (i=0; i<sk_num(ci->revoked); i++)
1031                         {
1032                         r=(X509_REVOKED *)sk_value(ci->revoked,i);
1033                         r->sequence=i;
1034                         }
1035
1036                 /* we now have a CRL */
1037                 if (verbose) BIO_printf(bio_err,"signing CRL\n");
1038                 if (md != NULL)
1039                         {
1040                         if ((dgst=EVP_get_digestbyname(md)) == NULL)
1041                                 {
1042                                 BIO_printf(bio_err,"%s is an unsupported message digest type\n",md);
1043                                 goto err;
1044                                 }
1045                         }
1046                 else
1047                     {
1048 #ifndef NO_DSA
1049                     if (pkey->type == EVP_PKEY_DSA) 
1050                         dgst=EVP_dss1();
1051                     else
1052 #endif
1053                         dgst=EVP_md5();
1054                     }
1055
1056                 /* Add any extensions asked for */
1057
1058                 if(crl_ext) {
1059                     X509V3_CTX crlctx;
1060                     if (ci->version == NULL)
1061                     if ((ci->version=ASN1_INTEGER_new()) == NULL) goto err;
1062                     ASN1_INTEGER_set(ci->version,1); /* version 2 CRL */
1063                     X509V3_set_ctx(&crlctx, x509, NULL, NULL, crl, 0);
1064                     X509V3_set_conf_lhash(&crlctx, conf);
1065
1066                     if(!X509V3_EXT_CRL_add_conf(conf, &crlctx,
1067                                                  crl_ext, crl)) goto err;
1068                 }
1069
1070                 if (!X509_CRL_sign(crl,pkey,dgst)) goto err;
1071
1072                 PEM_write_bio_X509_CRL(Sout,crl);
1073                 }
1074         /*****************************************************************/
1075         if (dorevoke)
1076                 {
1077                 in=BIO_new(BIO_s_file());
1078                 out=BIO_new(BIO_s_file());
1079                 if ((in == NULL) || (out == NULL))
1080                         {
1081                         ERR_print_errors(bio_err);
1082                         goto err;
1083                         }
1084                 if (infile == NULL) 
1085                         {
1086                         BIO_printf(bio_err,"no input files\n");
1087                         goto err;
1088                         }
1089                 else
1090                         {
1091                         if (BIO_read_filename(in,infile) <= 0)
1092                                 {
1093                                 perror(infile);
1094                                 BIO_printf(bio_err,"error trying to load '%s' certificate\n",infile);
1095                                 goto err;
1096                                 }
1097                         x509=PEM_read_bio_X509(in,NULL,NULL);
1098                         if (x509 == NULL)
1099                                 {
1100                                 BIO_printf(bio_err,"unable to load '%s' certificate\n",infile);
1101                                 goto err;
1102                                 }
1103                         j=do_revoke(x509,db);
1104
1105                         strncpy(buf[0],dbfile,BSIZE-4);
1106                         strcat(buf[0],".new");
1107                         if (BIO_write_filename(out,buf[0]) <= 0)
1108                                 {
1109                                 perror(dbfile);
1110                                 BIO_printf(bio_err,"unable to open '%s'\n",dbfile);
1111                                 goto err;
1112                                 }
1113                         j=TXT_DB_write(out,db);
1114                         if (j <= 0) goto err;
1115                         BIO_free(in);
1116                         BIO_free(out);
1117                         in=NULL;
1118                         out=NULL;
1119                         strncpy(buf[1],dbfile,BSIZE-4);
1120                         strcat(buf[1],".old");
1121                         if (rename(dbfile,buf[1]) < 0)
1122                                 {
1123                                 BIO_printf(bio_err,"unable to rename %s to %s\n", dbfile, buf[1]);
1124                                 perror("reason");
1125                                 goto err;
1126                                 }
1127                         if (rename(buf[0],dbfile) < 0)
1128                                 {
1129                                 BIO_printf(bio_err,"unable to rename %s to %s\n", buf[0],dbfile);
1130                                 perror("reason");
1131                                 rename(buf[1],dbfile);
1132                                 goto err;
1133                                 }
1134                         BIO_printf(bio_err,"Data Base Updated\n"); 
1135                         }
1136                 }
1137         /*****************************************************************/
1138         ret=0;
1139 err:
1140         BIO_free(hex);
1141         BIO_free(Cout);
1142         BIO_free(Sout);
1143         BIO_free(out);
1144         BIO_free(in);
1145
1146         sk_pop_free(cert_sk,X509_free);
1147
1148         if (ret) ERR_print_errors(bio_err);
1149         BN_free(serial);
1150         TXT_DB_free(db);
1151         EVP_PKEY_free(pkey);
1152         X509_free(x509);
1153         X509_CRL_free(crl);
1154         CONF_free(conf);
1155         X509V3_EXT_cleanup();
1156         OBJ_cleanup();
1157         EXIT(ret);
1158         }
1159
1160 static void lookup_fail(char *name, char *tag)
1161         {
1162         BIO_printf(bio_err,"variable lookup failed for %s::%s\n",name,tag);
1163         }
1164
1165 static int MS_CALLBACK key_callback(char *buf, int len, int verify)
1166         {
1167         int i;
1168
1169         if (key == NULL) return(0);
1170         i=strlen(key);
1171         i=(i > len)?len:i;
1172         memcpy(buf,key,i);
1173         return(i);
1174         }
1175
1176 static unsigned long index_serial_hash(char **a)
1177         {
1178         char *n;
1179
1180         n=a[DB_serial];
1181         while (*n == '0') n++;
1182         return(lh_strhash(n));
1183         }
1184
1185 static int index_serial_cmp(char **a, char **b)
1186         {
1187         char *aa,*bb;
1188
1189         for (aa=a[DB_serial]; *aa == '0'; aa++);
1190         for (bb=b[DB_serial]; *bb == '0'; bb++);
1191         return(strcmp(aa,bb));
1192         }
1193
1194 static unsigned long index_name_hash(char **a)
1195         { return(lh_strhash(a[DB_name])); }
1196
1197 static int index_name_qual(char **a)
1198         { return(a[0][0] == 'V'); }
1199
1200 static int index_name_cmp(char **a, char **b)
1201         { return(strcmp(a[DB_name],
1202              b[DB_name])); }
1203
1204 static BIGNUM *load_serial(char *serialfile)
1205         {
1206         BIO *in=NULL;
1207         BIGNUM *ret=NULL;
1208         MS_STATIC char buf[1024];
1209         ASN1_INTEGER *ai=NULL;
1210
1211         if ((in=BIO_new(BIO_s_file())) == NULL)
1212                 {
1213                 ERR_print_errors(bio_err);
1214                 goto err;
1215                 }
1216
1217         if (BIO_read_filename(in,serialfile) <= 0)
1218                 {
1219                 perror(serialfile);
1220                 goto err;
1221                 }
1222         ai=ASN1_INTEGER_new();
1223         if (ai == NULL) goto err;
1224         if (!a2i_ASN1_INTEGER(in,ai,buf,1024))
1225                 {
1226                 BIO_printf(bio_err,"unable to load number from %s\n",
1227                         serialfile);
1228                 goto err;
1229                 }
1230         ret=ASN1_INTEGER_to_BN(ai,NULL);
1231         if (ret == NULL)
1232                 {
1233                 BIO_printf(bio_err,"error converting number from bin to BIGNUM");
1234                 goto err;
1235                 }
1236 err:
1237         if (in != NULL) BIO_free(in);
1238         if (ai != NULL) ASN1_INTEGER_free(ai);
1239         return(ret);
1240         }
1241
1242 static int save_serial(char *serialfile, BIGNUM *serial)
1243         {
1244         BIO *out;
1245         int ret=0;
1246         ASN1_INTEGER *ai=NULL;
1247
1248         out=BIO_new(BIO_s_file());
1249         if (out == NULL)
1250                 {
1251                 ERR_print_errors(bio_err);
1252                 goto err;
1253                 }
1254         if (BIO_write_filename(out,serialfile) <= 0)
1255                 {
1256                 perror(serialfile);
1257                 goto err;
1258                 }
1259
1260         if ((ai=BN_to_ASN1_INTEGER(serial,NULL)) == NULL)
1261                 {
1262                 BIO_printf(bio_err,"error converting serial to ASN.1 format\n");
1263                 goto err;
1264                 }
1265         i2a_ASN1_INTEGER(out,ai);
1266         BIO_puts(out,"\n");
1267         ret=1;
1268 err:
1269         if (out != NULL) BIO_free(out);
1270         if (ai != NULL) ASN1_INTEGER_free(ai);
1271         return(ret);
1272         }
1273
1274 static int certify(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509,
1275              const EVP_MD *dgst, STACK *policy, TXT_DB *db, BIGNUM *serial,
1276              char *startdate, int days, int batch, char *ext_sect, LHASH *lconf,
1277                  int verbose)
1278         {
1279         X509_REQ *req=NULL;
1280         BIO *in=NULL;
1281         EVP_PKEY *pktmp=NULL;
1282         int ok= -1,i;
1283
1284         in=BIO_new(BIO_s_file());
1285
1286         if (BIO_read_filename(in,infile) <= 0)
1287                 {
1288                 perror(infile);
1289                 goto err;
1290                 }
1291         if ((req=PEM_read_bio_X509_REQ(in,NULL,NULL)) == NULL)
1292                 {
1293                 BIO_printf(bio_err,"Error reading certificate request in %s\n",
1294                         infile);
1295                 goto err;
1296                 }
1297         if (verbose)
1298                 X509_REQ_print(bio_err,req);
1299
1300         BIO_printf(bio_err,"Check that the request matches the signature\n");
1301
1302         if ((pktmp=X509_REQ_get_pubkey(req)) == NULL)
1303                 {
1304                 BIO_printf(bio_err,"error unpacking public key\n");
1305                 goto err;
1306                 }
1307         i=X509_REQ_verify(req,pktmp);
1308         EVP_PKEY_free(pktmp);
1309         if (i < 0)
1310                 {
1311                 ok=0;
1312                 BIO_printf(bio_err,"Signature verification problems....\n");
1313                 goto err;
1314                 }
1315         if (i == 0)
1316                 {
1317                 ok=0;
1318                 BIO_printf(bio_err,"Signature did not match the certificate request\n");
1319                 goto err;
1320                 }
1321         else
1322                 BIO_printf(bio_err,"Signature ok\n");
1323
1324         ok=do_body(xret,pkey,x509,dgst,policy,db,serial,startdate,
1325                 days,batch,verbose,req,ext_sect,lconf);
1326
1327 err:
1328         if (req != NULL) X509_REQ_free(req);
1329         if (in != NULL) BIO_free(in);
1330         return(ok);
1331         }
1332
1333 static int certify_cert(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509,
1334              const EVP_MD *dgst, STACK *policy, TXT_DB *db, BIGNUM *serial,
1335              char *startdate, int days, int batch, char *ext_sect, LHASH *lconf,
1336                  int verbose)
1337
1338         {
1339         X509 *req=NULL;
1340         X509_REQ *rreq=NULL;
1341         BIO *in=NULL;
1342         EVP_PKEY *pktmp=NULL;
1343         int ok= -1,i;
1344
1345         in=BIO_new(BIO_s_file());
1346
1347         if (BIO_read_filename(in,infile) <= 0)
1348                 {
1349                 perror(infile);
1350                 goto err;
1351                 }
1352         if ((req=PEM_read_bio_X509(in,NULL,NULL)) == NULL)
1353                 {
1354                 BIO_printf(bio_err,"Error reading self signed certificate in %s\n",infile);
1355                 goto err;
1356                 }
1357         if (verbose)
1358                 X509_print(bio_err,req);
1359
1360         BIO_printf(bio_err,"Check that the request matches the signature\n");
1361
1362         if ((pktmp=X509_get_pubkey(req)) == NULL)
1363                 {
1364                 BIO_printf(bio_err,"error unpacking public key\n");
1365                 goto err;
1366                 }
1367         i=X509_verify(req,pktmp);
1368         EVP_PKEY_free(pktmp);
1369         if (i < 0)
1370                 {
1371                 ok=0;
1372                 BIO_printf(bio_err,"Signature verification problems....\n");
1373                 goto err;
1374                 }
1375         if (i == 0)
1376                 {
1377                 ok=0;
1378                 BIO_printf(bio_err,"Signature did not match the certificate\n");
1379                 goto err;
1380                 }
1381         else
1382                 BIO_printf(bio_err,"Signature ok\n");
1383
1384         if ((rreq=X509_to_X509_REQ(req,NULL,EVP_md5())) == NULL)
1385                 goto err;
1386
1387         ok=do_body(xret,pkey,x509,dgst,policy,db,serial,startdate,days,
1388                 batch,verbose,rreq,ext_sect,lconf);
1389
1390 err:
1391         if (rreq != NULL) X509_REQ_free(rreq);
1392         if (req != NULL) X509_free(req);
1393         if (in != NULL) BIO_free(in);
1394         return(ok);
1395         }
1396
1397 static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, const EVP_MD *dgst,
1398              STACK *policy, TXT_DB *db, BIGNUM *serial, char *startdate, int days,
1399              int batch, int verbose, X509_REQ *req, char *ext_sect, LHASH *lconf)
1400         {
1401         X509_NAME *name=NULL,*CAname=NULL,*subject=NULL;
1402         ASN1_UTCTIME *tm,*tmptm;
1403         ASN1_STRING *str,*str2;
1404         ASN1_OBJECT *obj;
1405         X509 *ret=NULL;
1406         X509_CINF *ci;
1407         X509_NAME_ENTRY *ne;
1408         X509_NAME_ENTRY *tne,*push;
1409         EVP_PKEY *pktmp;
1410         int ok= -1,i,j,last,nid;
1411         char *p;
1412         CONF_VALUE *cv;
1413         char *row[DB_NUMBER],**rrow,**irow=NULL;
1414         char buf[25],*pbuf;
1415
1416         tmptm=ASN1_UTCTIME_new();
1417         if (tmptm == NULL)
1418                 {
1419                 BIO_printf(bio_err,"malloc error\n");
1420                 return(0);
1421                 }
1422
1423         for (i=0; i<DB_NUMBER; i++)
1424                 row[i]=NULL;
1425
1426         BIO_printf(bio_err,"The Subjects Distinguished Name is as follows\n");
1427         name=X509_REQ_get_subject_name(req);
1428         for (i=0; i<X509_NAME_entry_count(name); i++)
1429                 {
1430                 ne=(X509_NAME_ENTRY *)X509_NAME_get_entry(name,i);
1431                 obj=X509_NAME_ENTRY_get_object(ne);
1432                 j=i2a_ASN1_OBJECT(bio_err,obj);
1433                 str=X509_NAME_ENTRY_get_data(ne);
1434                 pbuf=buf;
1435                 for (j=22-j; j>0; j--)
1436                         *(pbuf++)=' ';
1437                 *(pbuf++)=':';
1438                 *(pbuf++)='\0';
1439                 BIO_puts(bio_err,buf);
1440
1441                 if (msie_hack)
1442                         {
1443                         /* assume all type should be strings */
1444                         nid=OBJ_obj2nid(ne->object);
1445
1446                         if (str->type == V_ASN1_UNIVERSALSTRING)
1447                                 ASN1_UNIVERSALSTRING_to_string(str);
1448
1449                         if ((str->type == V_ASN1_IA5STRING) &&
1450                                 (nid != NID_pkcs9_emailAddress))
1451                                 str->type=V_ASN1_T61STRING;
1452
1453                         if ((nid == NID_pkcs9_emailAddress) &&
1454                                 (str->type == V_ASN1_PRINTABLESTRING))
1455                                 str->type=V_ASN1_IA5STRING;
1456                         }
1457
1458                 if (str->type == V_ASN1_PRINTABLESTRING)
1459                         BIO_printf(bio_err,"PRINTABLE:'");
1460                 else if (str->type == V_ASN1_T61STRING)
1461                         BIO_printf(bio_err,"T61STRING:'");
1462                 else if (str->type == V_ASN1_IA5STRING)
1463                         BIO_printf(bio_err,"IA5STRING:'");
1464                 else if (str->type == V_ASN1_UNIVERSALSTRING)
1465                         BIO_printf(bio_err,"UNIVERSALSTRING:'");
1466                 else
1467                         BIO_printf(bio_err,"ASN.1 %2d:'",str->type);
1468
1469                 /* check some things */
1470                 if ((OBJ_obj2nid(obj) == NID_pkcs9_emailAddress) &&
1471                         (str->type != V_ASN1_IA5STRING))
1472                         {
1473                         BIO_printf(bio_err,"\nemailAddress type needs to be of type IA5STRING\n");
1474                         goto err;
1475                         }
1476                 j=ASN1_PRINTABLE_type(str->data,str->length);
1477                 if (    ((j == V_ASN1_T61STRING) &&
1478                          (str->type != V_ASN1_T61STRING)) ||
1479                         ((j == V_ASN1_IA5STRING) &&
1480                          (str->type == V_ASN1_PRINTABLESTRING)))
1481                         {
1482                         BIO_printf(bio_err,"\nThe string contains characters that are illegal for the ASN.1 type\n");
1483                         goto err;
1484                         }
1485                         
1486                 p=(char *)str->data;
1487                 for (j=str->length; j>0; j--)
1488                         {
1489                         if ((*p >= ' ') && (*p <= '~'))
1490                                 BIO_printf(bio_err,"%c",*p);
1491                         else if (*p & 0x80)
1492                                 BIO_printf(bio_err,"\\0x%02X",*p);
1493                         else if ((unsigned char)*p == 0xf7)
1494                                 BIO_printf(bio_err,"^?");
1495                         else    BIO_printf(bio_err,"^%c",*p+'@');
1496                         p++;
1497                         }
1498                 BIO_printf(bio_err,"'\n");
1499                 }
1500
1501         /* Ok, now we check the 'policy' stuff. */
1502         if ((subject=X509_NAME_new()) == NULL)
1503                 {
1504                 BIO_printf(bio_err,"Malloc failure\n");
1505                 goto err;
1506                 }
1507
1508         /* take a copy of the issuer name before we mess with it. */
1509         CAname=X509_NAME_dup(x509->cert_info->subject);
1510         if (CAname == NULL) goto err;
1511         str=str2=NULL;
1512
1513         for (i=0; i<sk_num(policy); i++)
1514                 {
1515                 cv=(CONF_VALUE *)sk_value(policy,i); /* get the object id */
1516                 if ((j=OBJ_txt2nid(cv->name)) == NID_undef)
1517                         {
1518                         BIO_printf(bio_err,"%s:unknown object type in 'policy' configuration\n",cv->name);
1519                         goto err;
1520                         }
1521                 obj=OBJ_nid2obj(j);
1522
1523                 last= -1;
1524                 for (;;)
1525                         {
1526                         /* lookup the object in the supplied name list */
1527                         j=X509_NAME_get_index_by_OBJ(name,obj,last);
1528                         if (j < 0)
1529                                 {
1530                                 if (last != -1) break;
1531                                 tne=NULL;
1532                                 }
1533                         else
1534                                 {
1535                                 tne=X509_NAME_get_entry(name,j);
1536                                 }
1537                         last=j;
1538
1539                         /* depending on the 'policy', decide what to do. */
1540                         push=NULL;
1541                         if (strcmp(cv->value,"optional") == 0)
1542                                 {
1543                                 if (tne != NULL)
1544                                         push=tne;
1545                                 }
1546                         else if (strcmp(cv->value,"supplied") == 0)
1547                                 {
1548                                 if (tne == NULL)
1549                                         {
1550                                         BIO_printf(bio_err,"The %s field needed to be supplied and was missing\n",cv->name);
1551                                         goto err;
1552                                         }
1553                                 else
1554                                         push=tne;
1555                                 }
1556                         else if (strcmp(cv->value,"match") == 0)
1557                                 {
1558                                 int last2;
1559
1560                                 if (tne == NULL)
1561                                         {
1562                                         BIO_printf(bio_err,"The mandatory %s field was missing\n",cv->name);
1563                                         goto err;
1564                                         }
1565
1566                                 last2= -1;
1567
1568 again2:
1569                                 j=X509_NAME_get_index_by_OBJ(CAname,obj,last2);
1570                                 if ((j < 0) && (last2 == -1))
1571                                         {
1572                                         BIO_printf(bio_err,"The %s field does not exist in the CA certificate,\nthe 'policy' is misconfigured\n",cv->name);
1573                                         goto err;
1574                                         }
1575                                 if (j >= 0)
1576                                         {
1577                                         push=X509_NAME_get_entry(CAname,j);
1578                                         str=X509_NAME_ENTRY_get_data(tne);
1579                                         str2=X509_NAME_ENTRY_get_data(push);
1580                                         last2=j;
1581                                         if (ASN1_STRING_cmp(str,str2) != 0)
1582                                                 goto again2;
1583                                         }
1584                                 if (j < 0)
1585                                         {
1586                                         BIO_printf(bio_err,"The %s field needed to be the same in the\nCA certificate (%s) and the request (%s)\n",cv->name,((str == NULL)?"NULL":(char *)str->data),((str2 == NULL)?"NULL":(char *)str2->data));
1587                                         goto err;
1588                                         }
1589                                 }
1590                         else
1591                                 {
1592                                 BIO_printf(bio_err,"%s:invalid type in 'policy' configuration\n",cv->value);
1593                                 goto err;
1594                                 }
1595
1596                         if (push != NULL)
1597                                 {
1598                                 if (!X509_NAME_add_entry(subject,push,
1599                                         X509_NAME_entry_count(subject),0))
1600                                         {
1601                                         if (push != NULL)
1602                                                 X509_NAME_ENTRY_free(push);
1603                                         BIO_printf(bio_err,"Malloc failure\n");
1604                                         goto err;
1605                                         }
1606                                 }
1607                         if (j < 0) break;
1608                         }
1609                 }
1610
1611         if (preserve)
1612                 {
1613                 X509_NAME_free(subject);
1614                 subject=X509_NAME_dup(X509_REQ_get_subject_name(req));
1615                 if (subject == NULL) goto err;
1616                 }
1617
1618         if (verbose)
1619                 BIO_printf(bio_err,"The subject name apears to be ok, checking data base for clashes\n");
1620
1621         row[DB_name]=X509_NAME_oneline(subject,NULL,0);
1622         row[DB_serial]=BN_bn2hex(serial);
1623         if ((row[DB_name] == NULL) || (row[DB_serial] == NULL))
1624                 {
1625                 BIO_printf(bio_err,"Malloc failure\n");
1626                 goto err;
1627                 }
1628
1629         rrow=TXT_DB_get_by_index(db,DB_name,row);
1630         if (rrow != NULL)
1631                 {
1632                 BIO_printf(bio_err,"ERROR:There is already a certificate for %s\n",
1633                         row[DB_name]);
1634                 }
1635         else
1636                 {
1637                 rrow=TXT_DB_get_by_index(db,DB_serial,row);
1638                 if (rrow != NULL)
1639                         {
1640                         BIO_printf(bio_err,"ERROR:Serial number %s has already been issued,\n",
1641                                 row[DB_serial]);
1642                         BIO_printf(bio_err,"      check the database/serial_file for corruption\n");
1643                         }
1644                 }
1645
1646         if (rrow != NULL)
1647                 {
1648                 BIO_printf(bio_err,
1649                         "The matching entry has the following details\n");
1650                 if (rrow[DB_type][0] == 'E')
1651                         p="Expired";
1652                 else if (rrow[DB_type][0] == 'R')
1653                         p="Revoked";
1654                 else if (rrow[DB_type][0] == 'V')
1655                         p="Valid";
1656                 else
1657                         p="\ninvalid type, Data base error\n";
1658                 BIO_printf(bio_err,"Type          :%s\n",p);;
1659                 if (rrow[DB_type][0] == 'R')
1660                         {
1661                         p=rrow[DB_exp_date]; if (p == NULL) p="undef";
1662                         BIO_printf(bio_err,"Was revoked on:%s\n",p);
1663                         }
1664                 p=rrow[DB_exp_date]; if (p == NULL) p="undef";
1665                 BIO_printf(bio_err,"Expires on    :%s\n",p);
1666                 p=rrow[DB_serial]; if (p == NULL) p="undef";
1667                 BIO_printf(bio_err,"Serial Number :%s\n",p);
1668                 p=rrow[DB_file]; if (p == NULL) p="undef";
1669                 BIO_printf(bio_err,"File name     :%s\n",p);
1670                 p=rrow[DB_name]; if (p == NULL) p="undef";
1671                 BIO_printf(bio_err,"Subject Name  :%s\n",p);
1672                 ok= -1; /* This is now a 'bad' error. */
1673                 goto err;
1674                 }
1675
1676         /* We are now totaly happy, lets make and sign the certificate */
1677         if (verbose)
1678                 BIO_printf(bio_err,"Everything appears to be ok, creating and signing the certificate\n");
1679
1680         if ((ret=X509_new()) == NULL) goto err;
1681         ci=ret->cert_info;
1682
1683 #ifdef X509_V3
1684         /* Make it an X509 v3 certificate. */
1685         if (!X509_set_version(x509,2)) goto err;
1686 #endif
1687
1688         if (BN_to_ASN1_INTEGER(serial,ci->serialNumber) == NULL)
1689                 goto err;
1690         if (!X509_set_issuer_name(ret,X509_get_subject_name(x509)))
1691                 goto err;
1692
1693         BIO_printf(bio_err,"Certificate is to be certified until ");
1694         if (strcmp(startdate,"today") == 0)
1695                 {
1696                 X509_gmtime_adj(X509_get_notBefore(ret),0);
1697                 X509_gmtime_adj(X509_get_notAfter(ret),(long)60*60*24*days);
1698                 }
1699         else
1700                 {
1701                 /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX*/
1702                 ASN1_UTCTIME_set_string(X509_get_notBefore(ret),startdate);
1703                 }
1704         ASN1_UTCTIME_print(bio_err,X509_get_notAfter(ret));
1705         BIO_printf(bio_err," (%d days)\n",days);
1706
1707         if (!X509_set_subject_name(ret,subject)) goto err;
1708
1709         pktmp=X509_REQ_get_pubkey(req);
1710         i = X509_set_pubkey(ret,pktmp);
1711         EVP_PKEY_free(pktmp);
1712         if (!i) goto err;
1713
1714         /* Lets add the extensions, if there are any */
1715         if (ext_sect)
1716                 {
1717                 X509V3_CTX ctx;
1718                 if (ci->version == NULL)
1719                         if ((ci->version=ASN1_INTEGER_new()) == NULL)
1720                                 goto err;
1721                 ASN1_INTEGER_set(ci->version,2); /* version 3 certificate */
1722
1723                 /* Free the current entries if any, there should not
1724                  * be any I belive */
1725                 if (ci->extensions != NULL)
1726                         sk_X509_EXTENSION_pop_free(ci->extensions,
1727                                                    X509_EXTENSION_free);
1728
1729                 ci->extensions = NULL;
1730
1731                 X509V3_set_ctx(&ctx, x509, ret, req, NULL, 0);
1732                 X509V3_set_conf_lhash(&ctx, lconf);
1733
1734                 if(!X509V3_EXT_add_conf(lconf, &ctx, ext_sect, ret)) goto err;
1735
1736                 }
1737
1738
1739         if (!batch)
1740                 {
1741                 BIO_printf(bio_err,"Sign the certificate? [y/n]:");
1742                 BIO_flush(bio_err);
1743                 buf[0]='\0';
1744                 fgets(buf,sizeof(buf)-1,stdin);
1745                 if (!((buf[0] == 'y') || (buf[0] == 'Y')))
1746                         {
1747                         BIO_printf(bio_err,"CERTIFICATE WILL NOT BE CERTIFIED\n");
1748                         ok=0;
1749                         goto err;
1750                         }
1751                 }
1752
1753
1754 #ifndef NO_DSA
1755         if (pkey->type == EVP_PKEY_DSA) dgst=EVP_dss1();
1756         pktmp=X509_get_pubkey(ret);
1757         if (EVP_PKEY_missing_parameters(pktmp) &&
1758                 !EVP_PKEY_missing_parameters(pkey))
1759                 EVP_PKEY_copy_parameters(pktmp,pkey);
1760         EVP_PKEY_free(pktmp);
1761 #endif
1762
1763         if (!X509_sign(ret,pkey,dgst))
1764                 goto err;
1765
1766         /* We now just add it to the database */
1767         row[DB_type]=(char *)Malloc(2);
1768
1769         tm=X509_get_notAfter(ret);
1770         row[DB_exp_date]=(char *)Malloc(tm->length+1);
1771         memcpy(row[DB_exp_date],tm->data,tm->length);
1772         row[DB_exp_date][tm->length]='\0';
1773
1774         row[DB_rev_date]=NULL;
1775
1776         /* row[DB_serial] done already */
1777         row[DB_file]=(char *)Malloc(8);
1778         /* row[DB_name] done already */
1779
1780         if ((row[DB_type] == NULL) || (row[DB_exp_date] == NULL) ||
1781                 (row[DB_file] == NULL))
1782                 {
1783                 BIO_printf(bio_err,"Malloc failure\n");
1784                 goto err;
1785                 }
1786         strcpy(row[DB_file],"unknown");
1787         row[DB_type][0]='V';
1788         row[DB_type][1]='\0';
1789
1790         if ((irow=(char **)Malloc(sizeof(char *)*(DB_NUMBER+1))) == NULL)
1791                 {
1792                 BIO_printf(bio_err,"Malloc failure\n");
1793                 goto err;
1794                 }
1795
1796         for (i=0; i<DB_NUMBER; i++)
1797                 {
1798                 irow[i]=row[i];
1799                 row[i]=NULL;
1800                 }
1801         irow[DB_NUMBER]=NULL;
1802
1803         if (!TXT_DB_insert(db,irow))
1804                 {
1805                 BIO_printf(bio_err,"failed to update database\n");
1806                 BIO_printf(bio_err,"TXT_DB error number %ld\n",db->error);
1807                 goto err;
1808                 }
1809         ok=1;
1810 err:
1811         for (i=0; i<DB_NUMBER; i++)
1812                 if (row[i] != NULL) Free(row[i]);
1813
1814         if (CAname != NULL)
1815                 X509_NAME_free(CAname);
1816         if (subject != NULL)
1817                 X509_NAME_free(subject);
1818         if (ok <= 0)
1819                 {
1820                 if (ret != NULL) X509_free(ret);
1821                 ret=NULL;
1822                 }
1823         else
1824                 *xret=ret;
1825         return(ok);
1826         }
1827
1828 static void write_new_certificate(BIO *bp, X509 *x, int output_der)
1829         {
1830         char *f;
1831         char buf[256];
1832
1833         if (output_der)
1834                 {
1835                 (void)i2d_X509_bio(bp,x);
1836                 return;
1837                 }
1838
1839         f=X509_NAME_oneline(X509_get_issuer_name(x),buf,256);
1840         BIO_printf(bp,"issuer :%s\n",f);
1841
1842         f=X509_NAME_oneline(X509_get_subject_name(x),buf,256);
1843         BIO_printf(bp,"subject:%s\n",f);
1844
1845         BIO_puts(bp,"serial :");
1846         i2a_ASN1_INTEGER(bp,x->cert_info->serialNumber);
1847         BIO_puts(bp,"\n\n");
1848         X509_print(bp,x);
1849         BIO_puts(bp,"\n");
1850         PEM_write_bio_X509(bp,x);
1851         BIO_puts(bp,"\n");
1852         }
1853
1854 static int certify_spkac(X509 **xret, char *infile, EVP_PKEY *pkey, X509 *x509,
1855              const EVP_MD *dgst, STACK *policy, TXT_DB *db, BIGNUM *serial,
1856              char *startdate, int days, char *ext_sect, LHASH *lconf, int verbose)
1857         {
1858         STACK *sk=NULL;
1859         LHASH *parms=NULL;
1860         X509_REQ *req=NULL;
1861         CONF_VALUE *cv=NULL;
1862         NETSCAPE_SPKI *spki = NULL;
1863         unsigned char *spki_der = NULL,*p;
1864         X509_REQ_INFO *ri;
1865         char *type,*buf;
1866         EVP_PKEY *pktmp=NULL;
1867         X509_NAME *n=NULL;
1868         X509_NAME_ENTRY *ne=NULL;
1869         int ok= -1,i,j;
1870         long errline;
1871         int nid;
1872
1873         /*
1874          * Load input file into a hash table.  (This is just an easy
1875          * way to read and parse the file, then put it into a convenient
1876          * STACK format).
1877          */
1878         parms=CONF_load(NULL,infile,&errline);
1879         if (parms == NULL)
1880                 {
1881                 BIO_printf(bio_err,"error on line %ld of %s\n",errline,infile);
1882                 ERR_print_errors(bio_err);
1883                 goto err;
1884                 }
1885
1886         sk=CONF_get_section(parms, "default");
1887         if (sk_num(sk) == 0)
1888                 {
1889                 BIO_printf(bio_err, "no name/value pairs found in %s\n", infile);
1890                 CONF_free(parms);
1891                 goto err;
1892                 }
1893
1894         /*
1895          * Now create a dummy X509 request structure.  We don't actually
1896          * have an X509 request, but we have many of the components
1897          * (a public key, various DN components).  The idea is that we
1898          * put these components into the right X509 request structure
1899          * and we can use the same code as if you had a real X509 request.
1900          */
1901         req=X509_REQ_new();
1902         if (req == NULL)
1903                 {
1904                 ERR_print_errors(bio_err);
1905                 goto err;
1906                 }
1907
1908         /*
1909          * Build up the subject name set.
1910          */
1911         ri=req->req_info;
1912         n = ri->subject;
1913
1914         for (i = 0; ; i++)
1915                 {
1916                 if ((int)sk_num(sk) <= i) break;
1917
1918                 cv=(CONF_VALUE *)sk_value(sk,i);
1919                 type=cv->name;
1920                 buf=cv->value;
1921
1922                 if ((nid=OBJ_txt2nid(type)) == NID_undef)
1923                         {
1924                         if (strcmp(type, "SPKAC") == 0)
1925                                 {
1926                                 spki_der=(unsigned char *)Malloc(
1927                                         strlen(cv->value)+1);
1928                                 if (spki_der == NULL)
1929                                         {
1930                                         BIO_printf(bio_err,"Malloc failure\n");
1931                                         goto err;
1932                                         }
1933                                 j = EVP_DecodeBlock(spki_der, (unsigned char *)cv->value,
1934                                         strlen(cv->value));
1935                                 if (j <= 0)
1936                                         {
1937                                         BIO_printf(bio_err, "Can't b64 decode SPKAC structure\n");
1938                                         goto err;
1939                                         }
1940
1941                                 p=spki_der;
1942                                 spki = d2i_NETSCAPE_SPKI(&spki, &p, j);
1943                                 Free(spki_der);
1944                                 spki_der = NULL;
1945                                 if (spki == NULL)
1946                                         {
1947                                         BIO_printf(bio_err,"unable to load Netscape SPKAC structure\n");
1948                                         ERR_print_errors(bio_err);
1949                                         goto err;
1950                                         }
1951                                 }
1952                         continue;
1953                         }
1954
1955                 j=ASN1_PRINTABLE_type((unsigned char *)buf,-1);
1956                 if (fix_data(nid, &j) == 0)
1957                         {
1958                         BIO_printf(bio_err,
1959                                 "invalid characters in string %s\n",buf);
1960                         goto err;
1961                         }
1962
1963                 if ((ne=X509_NAME_ENTRY_create_by_NID(&ne,nid,j,
1964                         (unsigned char *)buf,
1965                         strlen(buf))) == NULL)
1966                         goto err;
1967
1968                 if (!X509_NAME_add_entry(n,ne,X509_NAME_entry_count(n),0))
1969                         goto err;
1970                 }
1971         if (spki == NULL)
1972                 {
1973                 BIO_printf(bio_err,"Netscape SPKAC structure not found in %s\n",
1974                         infile);
1975                 goto err;
1976                 }
1977
1978         /*
1979          * Now extract the key from the SPKI structure.
1980          */
1981
1982         BIO_printf(bio_err,"Check that the SPKAC request matches the signature\n");
1983
1984         if ((pktmp=X509_PUBKEY_get(spki->spkac->pubkey)) == NULL)
1985                 {
1986                 BIO_printf(bio_err,"error unpacking SPKAC public key\n");
1987                 goto err;
1988                 }
1989
1990         j = NETSCAPE_SPKI_verify(spki, pktmp);
1991         if (j <= 0)
1992                 {
1993                 BIO_printf(bio_err,"signature verification failed on SPKAC public key\n");
1994                 goto err;
1995                 }
1996         BIO_printf(bio_err,"Signature ok\n");
1997
1998         X509_REQ_set_pubkey(req,pktmp);
1999         EVP_PKEY_free(pktmp);
2000         ok=do_body(xret,pkey,x509,dgst,policy,db,serial,startdate,
2001                    days,1,verbose,req,ext_sect,lconf);
2002 err:
2003         if (req != NULL) X509_REQ_free(req);
2004         if (parms != NULL) CONF_free(parms);
2005         if (spki_der != NULL) Free(spki_der);
2006         if (spki != NULL) NETSCAPE_SPKI_free(spki);
2007         if (ne != NULL) X509_NAME_ENTRY_free(ne);
2008
2009         return(ok);
2010         }
2011
2012 static int fix_data(int nid, int *type)
2013         {
2014         if (nid == NID_pkcs9_emailAddress)
2015                 *type=V_ASN1_IA5STRING;
2016         if ((nid == NID_commonName) && (*type == V_ASN1_IA5STRING))
2017                 *type=V_ASN1_T61STRING;
2018         if ((nid == NID_pkcs9_challengePassword) && (*type == V_ASN1_IA5STRING))
2019                 *type=V_ASN1_T61STRING;
2020         if ((nid == NID_pkcs9_unstructuredName) && (*type == V_ASN1_T61STRING))
2021                 return(0);
2022         if (nid == NID_pkcs9_unstructuredName)
2023                 *type=V_ASN1_IA5STRING;
2024         return(1);
2025         }
2026
2027 static int check_time_format(char *str)
2028         {
2029         ASN1_UTCTIME tm;
2030
2031         tm.data=(unsigned char *)str;
2032         tm.length=strlen(str);
2033         tm.type=V_ASN1_UTCTIME;
2034         return(ASN1_UTCTIME_check(&tm));
2035         }
2036
2037 static int add_oid_section(LHASH *hconf)
2038 {       
2039         char *p;
2040         STACK *sktmp;
2041         CONF_VALUE *cnf;
2042         int i;
2043         if(!(p=CONF_get_string(hconf,NULL,"oid_section"))) return 1;
2044         if(!(sktmp = CONF_get_section(hconf, p))) {
2045                 BIO_printf(bio_err, "problem loading oid section %s\n", p);
2046                 return 0;
2047         }
2048         for(i = 0; i < sk_num(sktmp); i++) {
2049                 cnf = (CONF_VALUE *)sk_value(sktmp, i);
2050                 if(OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
2051                         BIO_printf(bio_err, "problem creating object %s=%s\n",
2052                                                          cnf->name, cnf->value);
2053                         return 0;
2054                 }
2055         }
2056         return 1;
2057 }
2058
2059 static int do_revoke(X509 *x509, TXT_DB *db)
2060 {
2061         ASN1_UTCTIME *tm=NULL;
2062         char *row[DB_NUMBER],**rrow,**irow;
2063         int ok=-1,i;
2064
2065         for (i=0; i<DB_NUMBER; i++)
2066                 row[i]=NULL;
2067         row[DB_name]=X509_NAME_oneline(x509->cert_info->subject,NULL,0);
2068         row[DB_serial]=BN_bn2hex(ASN1_INTEGER_to_BN(x509->cert_info->serialNumber,NULL));
2069         if ((row[DB_name] == NULL) || (row[DB_serial] == NULL))
2070                 {
2071                 BIO_printf(bio_err,"Malloc failure\n");
2072                 goto err;
2073                 }
2074         rrow=TXT_DB_get_by_index(db,DB_name,row);
2075         if (rrow == NULL)
2076                 {
2077                 BIO_printf(bio_err,"Adding Entry to DB for %s\n", row[DB_name]);
2078
2079                 /* We now just add it to the database */
2080                 row[DB_type]=(char *)Malloc(2);
2081
2082                 tm=X509_get_notAfter(x509);
2083                 row[DB_exp_date]=(char *)Malloc(tm->length+1);
2084                 memcpy(row[DB_exp_date],tm->data,tm->length);
2085                 row[DB_exp_date][tm->length]='\0';
2086
2087                 row[DB_rev_date]=NULL;
2088
2089                 /* row[DB_serial] done already */
2090                 row[DB_file]=(char *)Malloc(8);
2091
2092                 /* row[DB_name] done already */
2093
2094                 if ((row[DB_type] == NULL) || (row[DB_exp_date] == NULL) ||
2095                         (row[DB_file] == NULL))
2096                         {
2097                         BIO_printf(bio_err,"Malloc failure\n");
2098                         goto err;
2099                         }
2100                 strcpy(row[DB_file],"unknown");
2101                 row[DB_type][0]='V';
2102                 row[DB_type][1]='\0';
2103
2104                 if ((irow=(char **)Malloc(sizeof(char *)*(DB_NUMBER+1))) == NULL)
2105                         {
2106                         BIO_printf(bio_err,"Malloc failure\n");
2107                         goto err;
2108                         }
2109
2110                 for (i=0; i<DB_NUMBER; i++)
2111                         {
2112                         irow[i]=row[i];
2113                         row[i]=NULL;
2114                         }
2115                 irow[DB_NUMBER]=NULL;
2116
2117                 if (!TXT_DB_insert(db,irow))
2118                         {
2119                         BIO_printf(bio_err,"failed to update database\n");
2120                         BIO_printf(bio_err,"TXT_DB error number %ld\n",db->error);
2121                         goto err;
2122                         }
2123
2124                 /* Revoke Certificate */
2125                 do_revoke(x509,db);
2126
2127                 ok=1;
2128                 goto err;
2129
2130                 }
2131         else if (index_serial_cmp(row,rrow))
2132                 {
2133                 BIO_printf(bio_err,"ERROR:no same serial number %s\n",
2134                            row[DB_serial]);
2135                 goto err;
2136                 }
2137         else if (rrow[DB_type][0]=='R')
2138                 {
2139                 BIO_printf(bio_err,"ERROR:Already revoked, serial number %s\n",
2140                            row[DB_serial]);
2141                 goto err;
2142                 }
2143         else
2144                 {
2145                 BIO_printf(bio_err,"Revoking Certificate %s.\n", rrow[DB_serial]);
2146                 tm=X509_gmtime_adj(tm,0);
2147                 rrow[DB_type][0]='R';
2148                 rrow[DB_type][1]='\0';
2149                 rrow[DB_rev_date]=(char *)Malloc(tm->length+1);
2150                 memcpy(rrow[DB_rev_date],tm->data,tm->length);
2151                 rrow[DB_rev_date][tm->length]='\0';
2152                 }
2153         ok=1;
2154 err:
2155         for (i=0; i<DB_NUMBER; i++)
2156                 {
2157                 if (row[i] != NULL) 
2158                         Free(row[i]);
2159                 }
2160         ASN1_UTCTIME_free(tm);
2161         return(ok);
2162 }
2163