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