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