2 /* Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com)
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.
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).
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.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
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)"
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
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.]
59 /* The PPKI stuff has been donated by Jeff Barber <jeffb@issl.atl.hp.com> */
64 #include <sys/types.h>
84 #define BASE_SECTION "ca"
85 #define CONFIG_FILE "lib/ssleay.cnf"
87 #define ENV_DEFAULT_CA "default_ca"
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"
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"
108 #define ENV_DATABASE "database"
111 #define DB_exp_date 1
112 #define DB_rev_date 2
113 #define DB_serial 3 /* index - unique */
115 #define DB_name 5 /* index - unique for active */
118 #define DB_TYPE_REV 'R'
119 #define DB_TYPE_EXP 'E'
120 #define DB_TYPE_VAL 'V'
122 static char *ca_usage[]={
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",
149 extern int EF_PROTECT_FREE;
150 extern int EF_PROTECT_BELOW;
151 extern int EF_ALIGNMENT;
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);
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();
197 static char *key=NULL;
198 static char *section=NULL;
200 static int preserve=0;
201 static int msie_hack=0;
217 char *configfile=NULL;
223 char *spkac_file=NULL;
228 char *serialfile=NULL;
229 char *extensions=NULL;
235 BIO *in=NULL,*out=NULL,*Sout=NULL,*Cout=NULL;
239 X509_CRL_INFO *ci=NULL;
240 X509_REVOKED *r=NULL;
246 STACK *extensions_sk=NULL;
251 MS_STATIC char buf[3][BSIZE];
261 X509v3_add_netscape_extensions();
265 if ((bio_err=BIO_new(BIO_s_file())) != NULL)
266 BIO_set_fp(bio_err,stderr,BIO_NOCLOSE);
272 if (strcmp(*argv,"-verbose") == 0)
274 else if (strcmp(*argv,"-config") == 0)
276 if (--argc < 1) goto bad;
277 configfile= *(++argv);
279 else if (strcmp(*argv,"-name") == 0)
281 if (--argc < 1) goto bad;
284 else if (strcmp(*argv,"-days") == 0)
286 if (--argc < 1) goto bad;
287 days=atoi(*(++argv));
289 else if (strcmp(*argv,"-md") == 0)
291 if (--argc < 1) goto bad;
294 else if (strcmp(*argv,"-policy") == 0)
296 if (--argc < 1) goto bad;
299 else if (strcmp(*argv,"-keyfile") == 0)
301 if (--argc < 1) goto bad;
304 else if (strcmp(*argv,"-key") == 0)
306 if (--argc < 1) goto bad;
309 else if (strcmp(*argv,"-cert") == 0)
311 if (--argc < 1) goto bad;
314 else if (strcmp(*argv,"-in") == 0)
316 if (--argc < 1) goto bad;
320 else if (strcmp(*argv,"-out") == 0)
322 if (--argc < 1) goto bad;
325 else if (strcmp(*argv,"-outdir") == 0)
327 if (--argc < 1) goto bad;
330 else if (strcmp(*argv,"-batch") == 0)
332 else if (strcmp(*argv,"-preserveDN") == 0)
334 else if (strcmp(*argv,"-gencrl") == 0)
336 else if (strcmp(*argv,"-msie_hack") == 0)
338 else if (strcmp(*argv,"-crldays") == 0)
340 if (--argc < 1) goto bad;
341 crldays= atol(*(++argv));
343 else if (strcmp(*argv,"-crlhours") == 0)
345 if (--argc < 1) goto bad;
346 crlhours= atol(*(++argv));
348 else if (strcmp(*argv,"-infiles") == 0)
355 else if (strcmp(*argv, "-spkac") == 0)
357 if (--argc < 1) goto bad;
358 spkac_file = *(++argv);
364 BIO_printf(bio_err,"unknown option %s\n",*argv);
374 for (pp=ca_usage; (*pp != NULL); pp++)
375 BIO_printf(bio_err,*pp);
379 ERR_load_crypto_strings();
381 /*****************************************************************/
382 if (configfile == NULL)
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));
388 strcat(buf[0],CONFIG_FILE);
392 BIO_printf(bio_err,"Using configuration from %s\n",configfile);
393 if ((conf=CONF_load(NULL,configfile,&errorline)) == NULL)
396 BIO_printf(bio_err,"error loading the config file '%s'\n",
399 BIO_printf(bio_err,"error on line %ld of config file '%s'\n"
400 ,errorline,configfile);
404 /* Lets get the config section we are using */
407 section=CONF_get_string(conf,BASE_SECTION,ENV_DEFAULT_CA);
410 lookup_fail(BASE_SECTION,ENV_DEFAULT_CA);
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))
421 ERR_print_errors(bio_err);
425 /*****************************************************************/
426 /* we definitly need an public key, so lets get it */
428 if ((keyfile == NULL) && ((keyfile=CONF_get_string(conf,
429 section,ENV_PRIVATE_KEY)) == NULL))
431 lookup_fail(section,ENV_PRIVATE_KEY);
434 if (BIO_read_filename(in,keyfile) <= 0)
437 BIO_printf(bio_err,"trying to load CA private key\n");
441 pkey=PEM_read_bio_PrivateKey(in,NULL,NULL);
444 pkey=PEM_read_bio_PrivateKey(in,NULL,key_callback);
445 memset(key,0,strlen(key));
449 BIO_printf(bio_err,"unable to load CA private key\n");
453 /*****************************************************************/
454 /* we need a certificate */
455 if ((certfile == NULL) && ((certfile=CONF_get_string(conf,
456 section,ENV_CERTIFICATE)) == NULL))
458 lookup_fail(section,ENV_CERTIFICATE);
461 if (BIO_read_filename(in,certfile) <= 0)
464 BIO_printf(bio_err,"trying to load CA certificate\n");
467 x509=PEM_read_bio_X509(in,NULL,NULL);
470 BIO_printf(bio_err,"unable to load CA certificate\n");
474 f=CONF_get_string(conf,BASE_SECTION,ENV_PRESERVE);
475 if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
477 f=CONF_get_string(conf,BASE_SECTION,ENV_MSIE_HACK);
478 if ((f != NULL) && ((*f == 'y') || (*f == 'Y')))
481 /*****************************************************************/
482 /* lookup where to write new certificates */
483 if ((outdir == NULL) && (req))
487 if ((outdir=CONF_get_string(conf,section,ENV_NEW_CERTS_DIR))
490 BIO_printf(bio_err,"there needs to be defined a directory for new certificate to be placed in\n");
493 if (access(outdir,R_OK|W_OK|X_OK) != 0)
495 BIO_printf(bio_err,"I am unable to acces the %s directory\n",outdir);
500 if (stat(outdir,&sb) != 0)
502 BIO_printf(bio_err,"unable to stat(%s)\n",outdir);
506 if (!(sb.st_mode & S_IFDIR))
508 BIO_printf(bio_err,"%s need to be a directory\n",outdir);
514 /*****************************************************************/
515 /* we need to load the database file */
516 if ((dbfile=CONF_get_string(conf,section,ENV_DATABASE)) == NULL)
518 lookup_fail(section,ENV_DATABASE);
521 if (BIO_read_filename(in,dbfile) <= 0)
524 BIO_printf(bio_err,"unable to open '%s'\n",dbfile);
527 db=TXT_DB_read(in,DB_NUMBER);
528 if (db == NULL) goto err;
530 /* Lets check some fields */
531 for (i=0; i<sk_num(db->data); i++)
533 pp=(char **)sk_value(db->data,i);
534 if ((pp[DB_type][0] != DB_TYPE_REV) &&
535 (pp[DB_rev_date][0] != '\0'))
537 BIO_printf(bio_err,"entry %d: not, revoked yet has a revokation date\n",i+1);
540 if ((pp[DB_type][0] == DB_TYPE_REV) &&
541 !check_time_format(pp[DB_rev_date]))
543 BIO_printf(bio_err,"entry %d: invalid revokation date\n",
547 if (!check_time_format(pp[DB_exp_date]))
549 BIO_printf(bio_err,"entry %d: invalid expiry date\n",i+1);
554 if ((j&1) || (j < 2))
556 BIO_printf(bio_err,"entry %d: bad serial number length (%d)\n",i+1,j);
561 if (!( ((*p >= '0') && (*p <= '9')) ||
562 ((*p >= 'A') && (*p <= 'F')) ||
563 ((*p >= 'a') && (*p <= 'f'))) )
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);
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",
577 BIO_printf(bio_err,"generating indexs\n");
580 if (!TXT_DB_create_index(db,DB_serial,NULL,index_serial_hash,
583 BIO_printf(bio_err,"error creating serial number index:(%ld,%ld,%ld)\n",db->error,db->arg1,db->arg2);
587 if (!TXT_DB_create_index(db,DB_name,index_name_qual,index_name_hash,
590 BIO_printf(bio_err,"error creating name index:(%ld,%ld,%ld)\n",
591 db->error,db->arg1,db->arg2);
595 /*****************************************************************/
601 if (BIO_write_filename(Sout,outfile) <= 0)
608 BIO_set_fp(Sout,stdout,BIO_NOCLOSE);
613 if ((md == NULL) && ((md=CONF_get_string(conf,
614 section,ENV_DEFAULT_MD)) == NULL))
616 lookup_fail(section,ENV_DEFAULT_MD);
619 if ((dgst=EVP_get_digestbyname(md)) == NULL)
621 BIO_printf(bio_err,"%s is an unsupported message digest type\n",md);
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))
630 lookup_fail(section,ENV_POLICY);
634 BIO_printf(bio_err,"policy is %s\n",policy);
636 if ((serialfile=CONF_get_string(conf,section,ENV_SERIAL))
639 lookup_fail(section,ENV_SERIAL);
643 if ((extensions=CONF_get_string(conf,section,ENV_EXTENSIONS))
646 if ((extensions_sk=load_extensions(extensions)) == NULL)
652 days=(int)CONF_get_number(conf,section,
657 BIO_printf(bio_err,"cannot lookup how many days to certify for\n");
661 if ((serial=load_serial(serialfile)) == NULL)
663 BIO_printf(bio_err,"error while loading serial number\n");
668 if ((f=BN_bn2ascii(serial)) == NULL) goto err;
669 BIO_printf(bio_err,"next serial number is %s\n",f);
673 if ((attribs=CONF_get_section(conf,policy)) == NULL)
675 BIO_printf(bio_err,"unable to find 'section' for %s\n",policy);
679 if ((cert_sk=sk_new_null()) == NULL)
681 BIO_printf(bio_err,"Malloc failure\n");
684 if (spkac_file != NULL)
687 j=certify_spkac(&x,spkac_file,pkey,x509,dgst,attribs,db,
688 serial,days,extensions_sk,verbose);
693 BIO_printf(bio_err,"\n");
694 if (!BN_add_word(serial,1)) goto err;
695 if (!sk_push(cert_sk,(char *)x))
697 BIO_printf(bio_err,"Malloc failure\n");
710 j=certify(&x,infile,pkey,x509,dgst,attribs,db,
711 serial,days,batch,extensions_sk,verbose);
716 BIO_printf(bio_err,"\n");
717 if (!BN_add_word(serial,1)) goto err;
718 if (!sk_push(cert_sk,(char *)x))
720 BIO_printf(bio_err,"Malloc failure\n");
725 for (i=0; i<argc; i++)
728 j=certify(&x,argv[i],pkey,x509,dgst,attribs,db,
729 serial,days,batch,extensions_sk,verbose);
734 BIO_printf(bio_err,"\n");
735 if (!BN_add_word(serial,1)) goto err;
736 if (!sk_push(cert_sk,(char *)x))
738 BIO_printf(bio_err,"Malloc failure\n");
743 /* we have a stack of newly certified certificates
744 * and a data base and serial number that need
747 if (sk_num(cert_sk) > 0)
751 BIO_printf(bio_err,"\n%d out of %d certificate requests certified, commit? [y/n]",total_done,total);
754 fgets(buf[0],10,stdin);
755 if ((buf[0][0] != 'y') && (buf[0][0] != 'Y'))
757 BIO_printf(bio_err,"CERTIFICATION CANCELED\n");
763 BIO_printf(bio_err,"Write out database with %d new entries\n",sk_num(cert_sk));
765 strncpy(buf[0],serialfile,BSIZE-4);
766 strcat(buf[0],".new");
768 if (!save_serial(buf[0],serial)) goto err;
770 strncpy(buf[1],dbfile,BSIZE-4);
771 strcat(buf[1],".new");
772 if (BIO_write_filename(out,buf[1]) <= 0)
775 BIO_printf(bio_err,"unable to open '%s'\n",dbfile);
778 l=TXT_DB_write(out,db);
779 if (l <= 0) goto err;
783 BIO_printf(bio_err,"writing new certificates\n");
784 for (i=0; i<sk_num(cert_sk); i++)
789 x=(X509 *)sk_value(cert_sk,i);
791 j=x->cert_info->serialNumber->length;
792 p=(char *)x->cert_info->serialNumber->data;
794 strncpy(buf[2],outdir,BSIZE-(j*2)-6);
796 n=(unsigned char *)&(buf[2][strlen(buf[2])]);
801 sprintf((char *)n,"%02X",*(p++));
810 *(n++)='.'; *(n++)='p'; *(n++)='e'; *(n++)='m';
813 BIO_printf(bio_err,"writing %s\n",buf[2]);
815 if (BIO_write_filename(Cout,buf[2]) <= 0)
820 write_new_certificate(Cout,x, 0);
821 write_new_certificate(Sout,x, output_der);
826 /* Rename the database and the serial file */
827 strncpy(buf[2],serialfile,BSIZE-4);
828 strcat(buf[2],".old");
833 if (rename(serialfile,buf[2]) < 0)
835 BIO_printf(bio_err,"unabel to rename %s to %s\n",
840 if (rename(buf[0],serialfile) < 0)
842 BIO_printf(bio_err,"unabel to rename %s to %s\n",
845 rename(buf[2],serialfile);
849 strncpy(buf[2],dbfile,BSIZE-4);
850 strcat(buf[2],".old");
851 if (rename(dbfile,buf[2]) < 0)
853 BIO_printf(bio_err,"unabel to rename %s to %s\n",
858 if (rename(buf[1],dbfile) < 0)
860 BIO_printf(bio_err,"unabel to rename %s to %s\n",
863 rename(buf[2],dbfile);
866 BIO_printf(bio_err,"Data Base Updated\n");
870 /*****************************************************************/
873 if ((hex=BIO_new(BIO_s_mem())) == NULL) goto err;
875 if (!crldays && !crlhours)
877 crldays=CONF_get_number(conf,section,
878 ENV_DEFAULT_CRL_DAYS);
879 crlhours=CONF_get_number(conf,section,
880 ENV_DEFAULT_CRL_HOURS);
882 if ((crldays == 0) && (crlhours == 0))
884 BIO_printf(bio_err,"cannot lookup how long until the next CRL is issuer\n");
888 if (verbose) BIO_printf(bio_err,"making CRL\n");
889 if ((crl=X509_CRL_new()) == NULL) goto err;
891 X509_NAME_free(ci->issuer);
892 ci->issuer=X509_NAME_dup(x509->cert_info->subject);
893 if (ci->issuer == NULL) goto err;
895 X509_gmtime_adj(ci->lastUpdate,0);
896 X509_gmtime_adj(ci->nextUpdate,(crldays*24+crlhours)*60*60);
898 for (i=0; i<sk_num(db->data); i++)
900 pp=(char **)sk_value(db->data,i);
901 if (pp[DB_type][0] == DB_TYPE_REV)
903 if ((r=X509_REVOKED_new()) == NULL) goto err;
904 ASN1_STRING_set((ASN1_STRING *)
906 (unsigned char *)pp[DB_rev_date],
907 strlen(pp[DB_rev_date]));
908 /* strcpy(r->revocationDate,pp[DB_rev_date]);*/
911 if (!BIO_puts(hex,pp[DB_serial]))
913 if (!a2i_ASN1_INTEGER(hex,r->serialNumber,
914 buf[0],BSIZE)) goto err;
916 sk_push(ci->revoked,(char *)r);
919 /* sort the data so it will be written in serial
921 sk_find(ci->revoked,NULL);
922 for (i=0; i<sk_num(ci->revoked); i++)
924 r=(X509_REVOKED *)sk_value(ci->revoked,i);
928 /* we how have a CRL */
929 if (verbose) BIO_printf(bio_err,"signing CRL\n");
932 if ((dgst=EVP_get_digestbyname(md)) == NULL)
934 BIO_printf(bio_err,"%s is an unsupported message digest type\n",md);
940 if (!X509_CRL_sign(crl,pkey,dgst)) goto err;
942 PEM_write_bio_X509_CRL(Sout,crl);
944 /*****************************************************************/
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);
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);
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();
968 static void lookup_fail(name,tag)
972 BIO_printf(bio_err,"variable lookup failed for %s::%s\n",name,tag);
975 static int MS_CALLBACK key_callback(buf,len,verify)
981 if (key == NULL) return(0);
988 static unsigned long index_serial_hash(a)
994 while (*n == '0') n++;
995 return(lh_strhash(n));
998 static int index_serial_cmp(a,b)
1004 for (aa=a[DB_serial]; *aa == '0'; aa++);
1005 for (bb=b[DB_serial]; *bb == '0'; bb++);
1006 return(strcmp(aa,bb));
1009 static unsigned long index_name_hash(a)
1011 { return(lh_strhash(a[DB_name])); }
1013 static int index_name_qual(a)
1015 { return(a[0][0] == 'V'); }
1017 static int index_name_cmp(a,b)
1020 { return(strcmp(a[DB_name],b[DB_name])); }
1022 static BIGNUM *load_serial(serialfile)
1027 MS_STATIC char buf[1024];
1028 ASN1_INTEGER *ai=NULL;
1030 if ((in=BIO_new(BIO_s_file())) == NULL)
1032 ERR_print_errors(bio_err);
1036 if (BIO_read_filename(in,serialfile) <= 0)
1041 ai=ASN1_INTEGER_new();
1042 if (ai == NULL) goto err;
1043 if (!a2i_ASN1_INTEGER(in,ai,buf,1024))
1045 BIO_printf(bio_err,"unable to load number from %s\n",
1049 ret=ASN1_INTEGER_to_BN(ai,NULL);
1052 BIO_printf(bio_err,"error converting number from bin to BIGNUM");
1056 if (in != NULL) BIO_free(in);
1057 if (ai != NULL) ASN1_INTEGER_free(ai);
1061 static int save_serial(serialfile,serial)
1067 ASN1_INTEGER *ai=NULL;
1069 out=BIO_new(BIO_s_file());
1072 ERR_print_errors(bio_err);
1075 if (BIO_write_filename(out,serialfile) <= 0)
1081 if ((ai=BN_to_ASN1_INTEGER(serial,NULL)) == NULL)
1083 BIO_printf(bio_err,"error converting serial to ASN.1 format\n");
1086 i2a_ASN1_INTEGER(out,ai);
1090 if (out != NULL) BIO_free(out);
1091 if (ai != NULL) ASN1_INTEGER_free(ai);
1095 static int certify(xret,infile,pkey,x509,dgst,policy,db,serial,days,
1096 batch,extensions,verbose)
1112 EVP_PKEY *pktmp=NULL;
1115 in=BIO_new(BIO_s_file());
1117 if (BIO_read_filename(in,infile) <= 0)
1122 if ((req=PEM_read_bio_X509_REQ(in,NULL,NULL)) == NULL)
1124 BIO_printf(bio_err,"Error reading certificate request in %s\n",
1129 X509_REQ_print(bio_err,req);
1131 BIO_printf(bio_err,"Check that the request matches the signature\n");
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))
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");
1142 if ((pktmp=X509_REQ_get_pubkey(req)) == NULL)
1144 BIO_printf(bio_err,"error unpacking public key\n");
1147 i=X509_REQ_verify(req,pktmp);
1151 BIO_printf(bio_err,"Signature verification problems....\n");
1157 BIO_printf(bio_err,"Signature did not match the certificate request\n");
1161 BIO_printf(bio_err,"Signature ok\n");
1163 ok=do_body(xret,pkey,x509,dgst,policy,db,serial,days,batch,verbose,req,
1167 if (req != NULL) X509_REQ_free(req);
1168 if (in != NULL) BIO_free(in);
1172 static int do_body(xret,pkey,x509,dgst,policy,db,serial,days,batch,verbose,req,
1187 X509_NAME *name=NULL,*CAname=NULL,*subject=NULL;
1189 ASN1_STRING *str,*str2;
1193 X509_NAME_ENTRY *ne;
1194 X509_NAME_ENTRY *tne,*push;
1195 X509_EXTENSION *ex=NULL;
1197 int ok= -1,i,j,last,nid;
1200 char *row[DB_NUMBER],**rrow,**irow=NULL;
1203 for (i=0; i<DB_NUMBER; i++)
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++)
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);
1215 for (j=22-j; j>0; j--)
1219 BIO_puts(bio_err,buf);
1223 /* assume all type should be strings */
1224 nid=OBJ_obj2nid(ne->object);
1226 if (str->type == V_ASN1_UNIVERSALSTRING)
1227 ASN1_UNIVERSALSTRING_to_string(str);
1229 if ((str->type == V_ASN1_IA5STRING) &&
1230 (nid != NID_pkcs9_emailAddress))
1231 str->type=V_ASN1_T61STRING;
1233 if ((nid == NID_pkcs9_emailAddress) &&
1234 (str->type == V_ASN1_PRINTABLESTRING))
1235 str->type=V_ASN1_IA5STRING;
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:'");
1247 BIO_printf(bio_err,"ASN.1 %2d:'",str->type);
1249 /* check some things */
1250 if ((OBJ_obj2nid(obj) == NID_pkcs9_emailAddress) &&
1251 (str->type != V_ASN1_IA5STRING))
1253 BIO_printf(bio_err,"\nemailAddress type needs to be of type IA5STRING\n");
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)))
1262 BIO_printf(bio_err,"\nThe string contains characters that are illegal for the ASN.1 type\n");
1266 p=(char *)str->data;
1267 for (j=str->length; j>0; j--)
1269 if ((*p >= ' ') && (*p <= '~'))
1270 BIO_printf(bio_err,"%c",*p);
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+'@');
1278 BIO_printf(bio_err,"'\n");
1281 /* Ok, now we check the 'policy' stuff. */
1282 if ((subject=X509_NAME_new()) == NULL)
1284 BIO_printf(bio_err,"Malloc failure\n");
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;
1293 for (i=0; i<sk_num(policy); i++)
1295 cv=(CONF_VALUE *)sk_value(policy,i); /* get the object id */
1296 if ((j=OBJ_txt2nid(cv->name)) == NID_undef)
1298 BIO_printf(bio_err,"%s:unknown object type in 'policy' configuration\n",cv->name);
1306 /* lookup the object in the supplied name list */
1307 j=X509_NAME_get_index_by_OBJ(name,obj,last);
1310 if (last != -1) break;
1315 tne=X509_NAME_get_entry(name,j);
1319 /* depending on the 'policy', decide what to do. */
1321 if (strcmp(cv->value,"optional") == 0)
1326 else if (strcmp(cv->value,"supplied") == 0)
1330 BIO_printf(bio_err,"The %s field needed to be supplied and was missing\n",cv->name);
1336 else if (strcmp(cv->value,"match") == 0)
1342 BIO_printf(bio_err,"The mandatory %s field was missing\n",cv->name);
1349 j=X509_NAME_get_index_by_OBJ(CAname,obj,last2);
1350 if ((j < 0) && (last2 == -1))
1352 BIO_printf(bio_err,"The %s field does not exist in the CA certificate,\nthe 'policy' is misconfigured\n",cv->name);
1357 push=X509_NAME_get_entry(CAname,j);
1358 str=X509_NAME_ENTRY_get_data(tne);
1359 str2=X509_NAME_ENTRY_get_data(push);
1361 if (ASN1_STRING_cmp(str,str2) != 0)
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));
1372 BIO_printf(bio_err,"%s:invalid type in 'policy' configuration\n",cv->value);
1378 if (!X509_NAME_add_entry(subject,push,
1379 X509_NAME_entry_count(subject),0))
1382 X509_NAME_ENTRY_free(push);
1383 BIO_printf(bio_err,"Malloc failure\n");
1393 X509_NAME_free(subject);
1394 subject=X509_NAME_dup(X509_REQ_get_subject_name(req));
1395 if (subject == NULL) goto err;
1399 BIO_printf(bio_err,"The subject name apears to be ok, checking data base for clashes\n");
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))
1405 BIO_printf(bio_err,"Malloc failure\n");
1409 rrow=TXT_DB_get_by_index(db,DB_name,row);
1412 BIO_printf(bio_err,"ERROR:There is already a certificate for %s\n",
1417 rrow=TXT_DB_get_by_index(db,DB_serial,row);
1420 BIO_printf(bio_err,"ERROR:Serial number %s has already been issued,\n",
1422 BIO_printf(bio_err," check the database/serial_file for corruption\n");
1429 "The matching entry has the following details\n");
1430 if (rrow[DB_type][0] == 'E')
1432 else if (rrow[DB_type][0] == 'R')
1434 else if (rrow[DB_type][0] == 'V')
1437 p="\ninvalid type, Data base error\n";
1438 BIO_printf(bio_err,"Type :%s\n",p);;
1439 if (rrow[DB_type][0] == 'R')
1441 p=rrow[DB_exp_date]; if (p == NULL) p="undef";
1442 BIO_printf(bio_err,"Was revoked on:%s\n",p);
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. */
1456 /* We are now totaly happy, lets make and sign the certificate */
1458 BIO_printf(bio_err,"Everything appears to be ok, creating and signing the certificate\n");
1460 if ((ret=X509_new()) == NULL) goto err;
1464 /* Make it an X509 v3 certificate. */
1465 if (!X509_set_version(x509,2)) goto err;
1468 if (BN_to_ASN1_INTEGER(serial,ci->serialNumber) == NULL)
1470 if (!X509_set_issuer_name(ret,X509_get_subject_name(x509)))
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);
1479 if (!X509_set_subject_name(ret,subject)) goto err;
1481 pktmp=X509_REQ_get_pubkey(req);
1482 if (!X509_set_pubkey(ret,pktmp)) goto err;
1484 /* Lets add the extensions, if there are any */
1485 if ((extensions != NULL) && (sk_num(extensions) > 0))
1487 if (ci->version == NULL)
1488 if ((ci->version=ASN1_INTEGER_new()) == NULL)
1490 ASN1_INTEGER_set(ci->version,2); /* version 3 certificate */
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);
1497 if ((ci->extensions=sk_new_null()) == NULL)
1500 /* Lets 'copy' in the new ones */
1501 for (i=0; i<sk_num(extensions); i++)
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;
1513 BIO_printf(bio_err,"Sign the certificate? [y/n]:");
1516 fgets(buf,sizeof(buf)-1,stdin);
1517 if (!((buf[0] == 'y') || (buf[0] == 'Y')))
1519 BIO_printf(bio_err,"CERTIFICATE WILL NOT BE CERTIFIED\n");
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);
1532 if (!X509_sign(ret,pkey,dgst))
1535 /* We now just add it to the database */
1536 row[DB_type]=(char *)Malloc(2);
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';
1543 row[DB_rev_date]=NULL;
1545 /* row[DB_serial] done already */
1546 row[DB_file]=(char *)Malloc(8);
1547 /* row[DB_name] done already */
1549 if ((row[DB_type] == NULL) || (row[DB_exp_date] == NULL) ||
1550 (row[DB_file] == NULL))
1552 BIO_printf(bio_err,"Malloc failure\n");
1555 strcpy(row[DB_file],"unknown");
1556 row[DB_type][0]='V';
1557 row[DB_type][1]='\0';
1559 if ((irow=(char **)Malloc(sizeof(char *)*(DB_NUMBER+1))) == NULL)
1561 BIO_printf(bio_err,"Malloc failure\n");
1565 for (i=0; i<DB_NUMBER; i++)
1570 irow[DB_NUMBER]=NULL;
1572 if (!TXT_DB_insert(db,irow))
1574 BIO_printf(bio_err,"failed to update database\n");
1575 BIO_printf(bio_err,"TXT_DB error number %ld\n",db->error);
1580 for (i=0; i<DB_NUMBER; i++)
1581 if (row[i] != NULL) Free(row[i]);
1584 X509_NAME_free(CAname);
1585 if (subject != NULL)
1586 X509_NAME_free(subject);
1589 if (ret != NULL) X509_free(ret);
1597 static void write_new_certificate(bp,x, output_der)
1607 (void)i2d_X509_bio(bp,x);
1611 f=X509_NAME_oneline(X509_get_issuer_name(x),buf,256);
1612 BIO_printf(bp,"issuer :%s\n",f);
1614 f=X509_NAME_oneline(X509_get_subject_name(x),buf,256);
1615 BIO_printf(bp,"subject:%s\n",f);
1617 BIO_puts(bp,"serial :");
1618 i2a_ASN1_INTEGER(bp,x->cert_info->serialNumber);
1619 BIO_puts(bp,"\n\n");
1622 PEM_write_bio_X509(bp,x);
1626 static int certify_spkac(xret,infile,pkey,x509,dgst,policy,db,serial,days,
1643 CONF_VALUE *cv=NULL;
1644 NETSCAPE_SPKI *spki = NULL;
1645 unsigned char *spki_der = NULL,*p;
1648 EVP_PKEY *pktmp=NULL;
1650 X509_NAME_ENTRY *ne=NULL;
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
1660 parms=CONF_load(NULL,infile,&errline);
1663 BIO_printf(bio_err,"error on line %ld of %s\n",errline,infile);
1664 ERR_print_errors(bio_err);
1668 sk=CONF_get_section(parms, "default");
1669 if (sk_num(sk) == 0)
1671 BIO_printf(bio_err, "no name/value pairs found in %s\n", infile);
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.
1686 ERR_print_errors(bio_err);
1691 * Build up the subject name set.
1698 if ((int)sk_num(sk) <= i) break;
1700 cv=(CONF_VALUE *)sk_value(sk,i);
1704 if ((nid=OBJ_txt2nid(type)) == NID_undef)
1706 if (strcmp(type, "SPKAC") == 0)
1708 spki_der=(unsigned char *)Malloc(
1709 strlen(cv->value)+1);
1710 if (spki_der == NULL)
1712 BIO_printf(bio_err,"Malloc failure\n");
1715 j = EVP_DecodeBlock(spki_der, (unsigned char *)cv->value,
1719 BIO_printf(bio_err, "Can't b64 decode SPKAC structure\n");
1724 spki = d2i_NETSCAPE_SPKI(&spki, &p, j);
1729 BIO_printf(bio_err,"unable to load Netscape SPKAC structure\n");
1730 ERR_print_errors(bio_err);
1737 j=ASN1_PRINTABLE_type((unsigned char *)buf,-1);
1738 if (fix_data(nid, &j) == 0)
1741 "invalid characters in string %s\n",buf);
1745 if ((ne=X509_NAME_ENTRY_create_by_NID(&ne,nid,j,
1746 (unsigned char *)buf,
1747 strlen(buf))) == NULL)
1750 if (!X509_NAME_add_entry(n,ne,X509_NAME_entry_count(n),0))
1755 BIO_printf(bio_err,"Netscape SPKAC structure not found in %s\n",
1761 * Now extract the key from the SPKI structure.
1764 BIO_printf(bio_err,"Check that the SPKAC request matches the signature\n");
1766 if ((pktmp=X509_PUBKEY_get(spki->spkac->pubkey)) == NULL)
1768 BIO_printf(bio_err,"error unpacking SPKAC public key\n");
1772 j = NETSCAPE_SPKI_verify(spki, pktmp);
1775 BIO_printf(bio_err,"signature verification failed on SPKAC public key\n");
1778 BIO_printf(bio_err,"Signature ok\n");
1780 X509_REQ_set_pubkey(req,pktmp);
1781 ok=do_body(xret,pkey,x509,dgst,policy,db,serial,days,1,verbose,req,
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);
1793 static int fix_data(nid,type)
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))
1805 if (nid == NID_pkcs9_unstructuredName)
1806 *type=V_ASN1_IA5STRING;
1811 static STACK *load_extensions(sec)
1817 ASN1_OCTET_STRING *str=NULL;
1818 ASN1_STRING *tmp=NULL;
1827 if ((ext=CONF_get_section(conf,sec)) == NULL)
1829 BIO_printf(bio_err,"unable to find extension section called '%s'\n",sec);
1833 if ((ret=sk_new_null()) == NULL) return(NULL);
1835 for (i=0; i<sk_num(ext); i++)
1837 cv=(CONF_VALUE *)sk_value(ext,i); /* get the object id */
1838 if ((nid=OBJ_txt2nid(cv->name)) == NID_undef)
1840 BIO_printf(bio_err,"%s:unknown object type in section, '%s'\n",sec,cv->name);
1844 pack_type=X509v3_pack_type_by_NID(nid);
1845 data_type=X509v3_data_type_by_NID(nid);
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'))
1853 if (data_type == V_ASN1_UNDEF)
1855 BIO_printf(bio_err,"data type for extension %s is unknown\n",cv->name);
1859 if ((mem=BIO_new(BIO_s_mem())) == NULL)
1861 if (((buf=BUF_MEM_new()) == NULL) ||
1862 !BUF_MEM_grow(buf,128))
1864 if ((tmp=ASN1_STRING_new()) == NULL) goto err;
1867 BIO_write(mem,(char *)&(ptr[2]),len-2);
1868 if (!a2i_ASN1_STRING(mem,tmp,buf->data,buf->max))
1876 case X509_EXT_PACK_STRING:
1877 if ((str=X509v3_pack_string(&str,
1878 data_type,ptr,len)) == NULL)
1881 case X509_EXT_PACK_UNKNOWN:
1883 BIO_printf(bio_err,"Don't know how to pack extension %s\n",cv->name);
1888 if ((x=X509_EXTENSION_create_by_NID(NULL,nid,0,str)) == NULL)
1890 sk_push(ret,(char *)x);
1896 if (ret != NULL) sk_pop_free(ret,X509_EXTENSION_free);
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);
1906 static int check_time_format(str)
1911 tm.data=(unsigned char *)str;
1912 tm.length=strlen(str);
1913 tm.type=V_ASN1_UTCTIME;
1914 return(ASN1_UTCTIME_check(&tm));