Second round of fixing the OpenSSL perl/ stuff. It now at least compiled fine
[openssl.git] / apps / x509.c
1 /* apps/x509.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #ifdef NO_STDIO
63 #define APPS_WIN16
64 #endif
65 #include "apps.h"
66 #include "bio.h"
67 #include "asn1.h"
68 #include "err.h"
69 #include "bn.h"
70 #include "evp.h"
71 #include "x509.h"
72 #include "x509v3.h"
73 #include "objects.h"
74 #include "pem.h"
75
76 #undef PROG
77 #define PROG x509_main
78
79 #undef POSTFIX
80 #define POSTFIX ".srl"
81 #define DEF_DAYS        30
82
83 #define CERT_HDR        "certificate"
84
85 static char *x509_usage[]={
86 "usage: x509 args\n",
87 " -inform arg     - input format - default PEM (one of DER, NET or PEM)\n",
88 " -outform arg    - output format - default PEM (one of DER, NET or PEM\n",
89 " -keyform arg    - private key format - default PEM\n",
90 " -CAform arg     - CA format - default PEM\n",
91 " -CAkeyform arg  - CA key format - default PEM\n",
92 " -in arg         - input file - default stdin\n",
93 " -out arg        - output file - default stdout\n",
94 " -serial         - print serial number value\n",
95 " -hash           - print hash value\n",
96 " -subject        - print subject DN\n",
97 " -issuer         - print issuer DN\n",
98 " -startdate      - notBefore field\n",
99 " -enddate        - notAfter field\n",
100 " -dates          - both Before and After dates\n",
101 " -modulus        - print the RSA key modulus\n",
102 " -fingerprint    - print the certificate fingerprint\n",
103 " -noout          - no certificate output\n",
104
105 " -days arg       - How long till expiry of a signed certificate - def 30 days\n",
106 " -signkey arg    - self sign cert with arg\n",
107 " -x509toreq      - output a certification request object\n",
108 " -req            - input is a certificate request, sign and output.\n",
109 " -CA arg         - set the CA certificate, must be PEM format.\n",
110 " -CAkey arg      - set the CA key, must be PEM format\n",
111 "                   missing, it is asssumed to be in the CA file.\n",
112 " -CAcreateserial - create serial number file if it does not exist\n",
113 " -CAserial       - serial file\n",
114 " -text           - print the certificate in text form\n",
115 " -C              - print out C code forms\n",
116 " -md2/-md5/-sha1/-mdc2 - digest to do an RSA sign with\n",
117 NULL
118 };
119
120 #ifndef NOPROTO
121 static int MS_CALLBACK callb(int ok, X509_STORE_CTX *ctx);
122 static EVP_PKEY *load_key(char *file, int format);
123 static X509 *load_cert(char *file, int format);
124 static int sign (X509 *x, EVP_PKEY *pkey,int days,EVP_MD *digest);
125 static int x509_certify (X509_STORE *ctx,char *CAfile, EVP_MD *digest,X509 *x,
126         X509 *xca, EVP_PKEY *pkey,char *serial, int create, int days);
127 #else
128 static int MS_CALLBACK callb();
129 static EVP_PKEY *load_key();
130 static X509 *load_cert();
131 static int sign ();
132 static int x509_certify ();
133 #endif
134
135 static int reqfile=0;
136
137 int MAIN(argc, argv)
138 int argc;
139 char **argv;
140         {
141         int ret=1;
142         X509_REQ *req=NULL;
143         X509 *x=NULL,*xca=NULL;
144         EVP_PKEY *Upkey=NULL,*CApkey=NULL;
145         int i,num,badops=0;
146         BIO *out=NULL;
147         BIO *STDout=NULL;
148         int informat,outformat,keyformat,CAformat,CAkeyformat;
149         char *infile=NULL,*outfile=NULL,*keyfile=NULL,*CAfile=NULL;
150         char *CAkeyfile=NULL,*CAserial=NULL;
151         int text=0,serial=0,hash=0,subject=0,issuer=0,startdate=0,enddate=0;
152         int noout=0,sign_flag=0,CA_flag=0,CA_createserial=0;
153         int C=0;
154         int x509req=0,days=DEF_DAYS,modulus=0;
155         char **pp;
156         X509_STORE *ctx=NULL;
157         X509_REQ *rq=NULL;
158         int fingerprint=0;
159         char buf[256];
160         EVP_MD *md_alg,*digest=EVP_md5();
161
162         reqfile=0;
163
164         apps_startup();
165
166         if (bio_err == NULL)
167                 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
168         STDout=BIO_new_fp(stdout,BIO_NOCLOSE);
169
170         informat=FORMAT_PEM;
171         outformat=FORMAT_PEM;
172         keyformat=FORMAT_PEM;
173         CAformat=FORMAT_PEM;
174         CAkeyformat=FORMAT_PEM;
175
176         ctx=X509_STORE_new();
177         if (ctx == NULL) goto end;
178         X509_STORE_set_verify_cb_func(ctx,callb);
179
180         argc--;
181         argv++;
182         num=0;
183         while (argc >= 1)
184                 {
185                 if      (strcmp(*argv,"-inform") == 0)
186                         {
187                         if (--argc < 1) goto bad;
188                         informat=str2fmt(*(++argv));
189                         }
190                 else if (strcmp(*argv,"-outform") == 0)
191                         {
192                         if (--argc < 1) goto bad;
193                         outformat=str2fmt(*(++argv));
194                         }
195                 else if (strcmp(*argv,"-keyform") == 0)
196                         {
197                         if (--argc < 1) goto bad;
198                         keyformat=str2fmt(*(++argv));
199                         }
200                 else if (strcmp(*argv,"-req") == 0)
201                         reqfile=1;
202                 else if (strcmp(*argv,"-CAform") == 0)
203                         {
204                         if (--argc < 1) goto bad;
205                         CAformat=str2fmt(*(++argv));
206                         }
207                 else if (strcmp(*argv,"-CAkeyform") == 0)
208                         {
209                         if (--argc < 1) goto bad;
210                         CAformat=str2fmt(*(++argv));
211                         }
212                 else if (strcmp(*argv,"-days") == 0)
213                         {
214                         if (--argc < 1) goto bad;
215                         days=atoi(*(++argv));
216                         if (days == 0)
217                                 {
218                                 BIO_printf(STDout,"bad number of days\n");
219                                 goto bad;
220                                 }
221                         }
222                 else if (strcmp(*argv,"-in") == 0)
223                         {
224                         if (--argc < 1) goto bad;
225                         infile= *(++argv);
226                         }
227                 else if (strcmp(*argv,"-out") == 0)
228                         {
229                         if (--argc < 1) goto bad;
230                         outfile= *(++argv);
231                         }
232                 else if (strcmp(*argv,"-signkey") == 0)
233                         {
234                         if (--argc < 1) goto bad;
235                         keyfile= *(++argv);
236                         sign_flag= ++num;
237                         }
238                 else if (strcmp(*argv,"-CA") == 0)
239                         {
240                         if (--argc < 1) goto bad;
241                         CAfile= *(++argv);
242                         CA_flag= ++num;
243                         }
244                 else if (strcmp(*argv,"-CAkey") == 0)
245                         {
246                         if (--argc < 1) goto bad;
247                         CAkeyfile= *(++argv);
248                         }
249                 else if (strcmp(*argv,"-CAserial") == 0)
250                         {
251                         if (--argc < 1) goto bad;
252                         CAserial= *(++argv);
253                         }
254                 else if (strcmp(*argv,"-C") == 0)
255                         C= ++num;
256                 else if (strcmp(*argv,"-serial") == 0)
257                         serial= ++num;
258                 else if (strcmp(*argv,"-modulus") == 0)
259                         modulus= ++num;
260                 else if (strcmp(*argv,"-x509toreq") == 0)
261                         x509req= ++num;
262                 else if (strcmp(*argv,"-text") == 0)
263                         text= ++num;
264                 else if (strcmp(*argv,"-hash") == 0)
265                         hash= ++num;
266                 else if (strcmp(*argv,"-subject") == 0)
267                         subject= ++num;
268                 else if (strcmp(*argv,"-issuer") == 0)
269                         issuer= ++num;
270                 else if (strcmp(*argv,"-fingerprint") == 0)
271                         fingerprint= ++num;
272                 else if (strcmp(*argv,"-dates") == 0)
273                         {
274                         startdate= ++num;
275                         enddate= ++num;
276                         }
277                 else if (strcmp(*argv,"-startdate") == 0)
278                         startdate= ++num;
279                 else if (strcmp(*argv,"-enddate") == 0)
280                         enddate= ++num;
281                 else if (strcmp(*argv,"-noout") == 0)
282                         noout= ++num;
283                 else if (strcmp(*argv,"-CAcreateserial") == 0)
284                         CA_createserial= ++num;
285                 else if ((md_alg=EVP_get_digestbyname(&((*argv)[1]))) != NULL)
286                         {
287                         /* ok */
288                         digest=md_alg;
289                         }
290                 else
291                         {
292                         BIO_printf(bio_err,"unknown option %s\n",*argv);
293                         badops=1;
294                         break;
295                         }
296                 argc--;
297                 argv++;
298                 }
299
300         if (badops)
301                 {
302 bad:
303                 for (pp=x509_usage; (*pp != NULL); pp++)
304                         BIO_printf(bio_err,*pp);
305                 goto end;
306                 }
307
308         ERR_load_crypto_strings();
309         X509V3_add_standard_extensions();
310
311         if (!X509_STORE_set_default_paths(ctx))
312                 {
313                 ERR_print_errors(bio_err);
314                 goto end;
315                 }
316
317         if ((CAkeyfile == NULL) && (CA_flag) && (CAformat == FORMAT_PEM))
318                 { CAkeyfile=CAfile; }
319         else if ((CA_flag) && (CAkeyfile == NULL))
320                 {
321                 BIO_printf(bio_err,"need to specify a CAkey if using the CA command\n");
322                 goto end;
323                 }
324
325         if (reqfile)
326                 {
327                 EVP_PKEY *pkey;
328                 X509_CINF *ci;
329                 BIO *in;
330
331                 if (!sign_flag && !CA_flag)
332                         {
333                         BIO_printf(bio_err,"We need a private key to sign with\n");
334                         goto end;
335                         }
336                 in=BIO_new(BIO_s_file());
337                 if (in == NULL)
338                         {
339                         ERR_print_errors(bio_err);
340                         goto end;
341                         }
342
343                 if (infile == NULL)
344                         BIO_set_fp(in,stdin,BIO_NOCLOSE|BIO_FP_TEXT);
345                 else
346                         {
347                         if (BIO_read_filename(in,infile) <= 0)
348                                 {
349                                 perror(infile);
350                                 goto end;
351                                 }
352                         }
353                 req=PEM_read_bio_X509_REQ(in,NULL,NULL);
354                 BIO_free(in);
355
356                 if (req == NULL) { perror(infile); goto end; }
357
358                 if (    (req->req_info == NULL) ||
359                         (req->req_info->pubkey == NULL) ||
360                         (req->req_info->pubkey->public_key == NULL) ||
361                         (req->req_info->pubkey->public_key->data == NULL))
362                         {
363                         BIO_printf(bio_err,"The certificate request appears to corrupted\n");
364                         BIO_printf(bio_err,"It does not contain a public key\n");
365                         goto end;
366                         }
367                 if ((pkey=X509_REQ_get_pubkey(req)) == NULL)
368                         {
369                         BIO_printf(bio_err,"error unpacking public key\n");
370                         goto end;
371                         }
372                 i=X509_REQ_verify(req,pkey);
373                 EVP_PKEY_free(pkey);
374                 if (i < 0)
375                         {
376                         BIO_printf(bio_err,"Signature verification error\n");
377                         ERR_print_errors(bio_err);
378                         goto end;
379                         }
380                 if (i == 0)
381                         {
382                         BIO_printf(bio_err,"Signature did not match the certificate request\n");
383                         goto end;
384                         }
385                 else
386                         BIO_printf(bio_err,"Signature ok\n");
387                 
388                 X509_NAME_oneline(req->req_info->subject,buf,256);
389                 BIO_printf(bio_err,"subject=%s\n",buf);
390
391                 if ((x=X509_new()) == NULL) goto end;
392                 ci=x->cert_info;
393
394                 if (!ASN1_INTEGER_set(X509_get_serialNumber(x),0)) goto end;
395                 if (!X509_set_issuer_name(x,req->req_info->subject)) goto end;
396                 if (!X509_set_subject_name(x,req->req_info->subject)) goto end;
397
398                 X509_gmtime_adj(X509_get_notBefore(x),0);
399                 X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days);
400
401 #if 0
402                 X509_PUBKEY_free(ci->key);
403                 ci->key=req->req_info->pubkey;
404                 req->req_info->pubkey=NULL;
405 #else
406                 pkey = X509_REQ_get_pubkey(req);
407                 X509_set_pubkey(x,pkey);
408                 EVP_PKEY_free(pkey);
409 #endif
410                 }
411         else
412                 x=load_cert(infile,informat);
413
414         if (x == NULL) goto end;
415         if (CA_flag)
416                 {
417                 xca=load_cert(CAfile,CAformat);
418                 if (xca == NULL) goto end;
419                 }
420
421         if (!noout || text)
422                 {
423                 OBJ_create("2.99999.3",
424                         "SET.ex3","SET x509v3 extension 3");
425
426                 out=BIO_new(BIO_s_file());
427                 if (out == NULL)
428                         {
429                         ERR_print_errors(bio_err);
430                         goto end;
431                         }
432                 if (outfile == NULL)
433                         BIO_set_fp(out,stdout,BIO_NOCLOSE);
434                 else
435                         {
436                         if (BIO_write_filename(out,outfile) <= 0)
437                                 {
438                                 perror(outfile);
439                                 goto end;
440                                 }
441                         }
442                 }
443
444         if (num)
445                 {
446                 for (i=1; i<=num; i++)
447                         {
448                         if (issuer == i)
449                                 {
450                                 X509_NAME_oneline(X509_get_issuer_name(x),
451                                         buf,256);
452                                 BIO_printf(STDout,"issuer= %s\n",buf);
453                                 }
454                         else if (subject == i) 
455                                 {
456                                 X509_NAME_oneline(X509_get_subject_name(x),
457                                         buf,256);
458                                 BIO_printf(STDout,"subject=%s\n",buf);
459                                 }
460                         else if (serial == i)
461                                 {
462                                 BIO_printf(STDout,"serial=");
463                                 i2a_ASN1_INTEGER(STDout,x->cert_info->serialNumber);
464                                 BIO_printf(STDout,"\n");
465                                 }
466                         else if (hash == i)
467                                 {
468                                 BIO_printf(STDout,"%08lx\n",X509_subject_name_hash(x));
469                                 }
470                         else
471                                 if (modulus == i)
472                                 {
473                                 EVP_PKEY *pkey;
474
475                                 pkey=X509_get_pubkey(x);
476                                 if (pkey == NULL)
477                                         {
478                                         BIO_printf(bio_err,"Modulus=unavailable\n");
479                                         ERR_print_errors(bio_err);
480                                         goto end;
481                                         }
482                                 BIO_printf(STDout,"Modulus=");
483 #ifndef NO_RSA
484                                 if (pkey->type == EVP_PKEY_RSA)
485                                         BN_print(STDout,pkey->pkey.rsa->n);
486                                 else
487 #endif
488 #ifndef NO_DSA
489                                 if (pkey->type == EVP_PKEY_DSA)
490                                         BN_print(STDout,pkey->pkey.dsa->pub_key);
491                                 else
492 #endif
493                                         BIO_printf(STDout,"Wrong Algorithm type");
494                                 BIO_printf(STDout,"\n");
495                                 EVP_PKEY_free(pkey);
496                                 }
497                         else
498                                 if (C == i)
499                                 {
500                                 unsigned char *d;
501                                 char *m;
502                                 int y,z;
503
504                                 X509_NAME_oneline(X509_get_subject_name(x),
505                                         buf,256);
506                                 BIO_printf(STDout,"/* subject:%s */\n",buf);
507                                 m=X509_NAME_oneline(
508                                         X509_get_issuer_name(x),buf,256);
509                                 BIO_printf(STDout,"/* issuer :%s */\n",buf);
510
511                                 z=i2d_X509(x,NULL);
512                                 m=Malloc(z);
513
514                                 d=(unsigned char *)m;
515                                 z=i2d_X509_NAME(X509_get_subject_name(x),&d);
516                                 BIO_printf(STDout,"unsigned char XXX_subject_name[%d]={\n",z);
517                                 d=(unsigned char *)m;
518                                 for (y=0; y<z; y++)
519                                         {
520                                         BIO_printf(STDout,"0x%02X,",d[y]);
521                                         if ((y & 0x0f) == 0x0f) BIO_printf(STDout,"\n");
522                                         }
523                                 if (y%16 != 0) BIO_printf(STDout,"\n");
524                                 BIO_printf(STDout,"};\n");
525
526                                 z=i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x),&d);
527                                 BIO_printf(STDout,"unsigned char XXX_public_key[%d]={\n",z);
528                                 d=(unsigned char *)m;
529                                 for (y=0; y<z; y++)
530                                         {
531                                         BIO_printf(STDout,"0x%02X,",d[y]);
532                                         if ((y & 0x0f) == 0x0f)
533                                                 BIO_printf(STDout,"\n");
534                                         }
535                                 if (y%16 != 0) BIO_printf(STDout,"\n");
536                                 BIO_printf(STDout,"};\n");
537
538                                 z=i2d_X509(x,&d);
539                                 BIO_printf(STDout,"unsigned char XXX_certificate[%d]={\n",z);
540                                 d=(unsigned char *)m;
541                                 for (y=0; y<z; y++)
542                                         {
543                                         BIO_printf(STDout,"0x%02X,",d[y]);
544                                         if ((y & 0x0f) == 0x0f)
545                                                 BIO_printf(STDout,"\n");
546                                         }
547                                 if (y%16 != 0) BIO_printf(STDout,"\n");
548                                 BIO_printf(STDout,"};\n");
549
550                                 Free(m);
551                                 }
552                         else if (text == i)
553                                 {
554                                 X509_print(out,x);
555                                 }
556                         else if (startdate == i)
557                                 {
558                                 BIO_puts(STDout,"notBefore=");
559                                 ASN1_TIME_print(STDout,X509_get_notBefore(x));
560                                 BIO_puts(STDout,"\n");
561                                 }
562                         else if (enddate == i)
563                                 {
564                                 BIO_puts(STDout,"notAfter=");
565                                 ASN1_TIME_print(STDout,X509_get_notAfter(x));
566                                 BIO_puts(STDout,"\n");
567                                 }
568                         else if (fingerprint == i)
569                                 {
570                                 int j;
571                                 unsigned int n;
572                                 unsigned char md[EVP_MAX_MD_SIZE];
573
574                                 if (!X509_digest(x,EVP_md5(),md,&n))
575                                         {
576                                         BIO_printf(bio_err,"out of memory\n");
577                                         goto end;
578                                         }
579                                 BIO_printf(STDout,"MD5 Fingerprint=");
580                                 for (j=0; j<(int)n; j++)
581                                         {
582                                         BIO_printf(STDout,"%02X%c",md[j],
583                                                 (j+1 == (int)n)
584                                                 ?'\n':':');
585                                         }
586                                 }
587
588                         /* should be in the library */
589                         else if ((sign_flag == i) && (x509req == 0))
590                                 {
591                                 BIO_printf(bio_err,"Getting Private key\n");
592                                 if (Upkey == NULL)
593                                         {
594                                         Upkey=load_key(keyfile,keyformat);
595                                         if (Upkey == NULL) goto end;
596                                         }
597 #ifndef NO_DSA
598                                 if (Upkey->type == EVP_PKEY_DSA)
599                                         digest=EVP_dss1();
600 #endif
601
602                                 if (!sign(x,Upkey,days,digest)) goto end;
603                                 }
604                         else if (CA_flag == i)
605                                 {
606                                 BIO_printf(bio_err,"Getting CA Private Key\n");
607                                 if (CAkeyfile != NULL)
608                                         {
609                                         CApkey=load_key(CAkeyfile,CAkeyformat);
610                                         if (CApkey == NULL) goto end;
611                                         }
612 #ifndef NO_DSA
613                                 if (CApkey->type == EVP_PKEY_DSA)
614                                         digest=EVP_dss1();
615 #endif
616                                 
617                                 if (!x509_certify(ctx,CAfile,digest,x,xca,
618                                         CApkey,
619                                         CAserial,CA_createserial,days))
620                                         goto end;
621                                 }
622                         else if (x509req == i)
623                                 {
624                                 EVP_PKEY *pk;
625
626                                 BIO_printf(bio_err,"Getting request Private Key\n");
627                                 if (keyfile == NULL)
628                                         {
629                                         BIO_printf(bio_err,"no request key file specified\n");
630                                         goto end;
631                                         }
632                                 else
633                                         {
634                                         pk=load_key(keyfile,FORMAT_PEM);
635                                         if (pk == NULL) goto end;
636                                         }
637
638                                 BIO_printf(bio_err,"Generating certificate request\n");
639
640                                 rq=X509_to_X509_REQ(x,pk,EVP_md5());
641                                 EVP_PKEY_free(pk);
642                                 if (rq == NULL)
643                                         {
644                                         ERR_print_errors(bio_err);
645                                         goto end;
646                                         }
647                                 if (!noout)
648                                         {
649                                         X509_REQ_print(out,rq);
650                                         PEM_write_bio_X509_REQ(out,rq);
651                                         }
652                                 noout=1;
653                                 }
654                         }
655                 }
656
657         if (noout)
658                 {
659                 ret=0;
660                 goto end;
661                 }
662
663         if      (outformat == FORMAT_ASN1)
664                 i=i2d_X509_bio(out,x);
665         else if (outformat == FORMAT_PEM)
666                 i=PEM_write_bio_X509(out,x);
667         else if (outformat == FORMAT_NETSCAPE)
668                 {
669                 ASN1_HEADER ah;
670                 ASN1_OCTET_STRING os;
671
672                 os.data=(unsigned char *)CERT_HDR;
673                 os.length=strlen(CERT_HDR);
674                 ah.header= &os;
675                 ah.data=(char *)x;
676                 ah.meth=X509_asn1_meth();
677
678                 /* no macro for this one yet */
679                 i=ASN1_i2d_bio(i2d_ASN1_HEADER,out,(unsigned char *)&ah);
680                 }
681         else    {
682                 BIO_printf(bio_err,"bad output format specified for outfile\n");
683                 goto end;
684                 }
685         if (!i) {
686                 BIO_printf(bio_err,"unable to write certificate\n");
687                 ERR_print_errors(bio_err);
688                 goto end;
689                 }
690         ret=0;
691 end:
692         OBJ_cleanup();
693         if (out != NULL) BIO_free(out);
694         if (STDout != NULL) BIO_free(STDout);
695         if (ctx != NULL) X509_STORE_free(ctx);
696         if (req != NULL) X509_REQ_free(req);
697         if (x != NULL) X509_free(x);
698         if (xca != NULL) X509_free(xca);
699         if (Upkey != NULL) EVP_PKEY_free(Upkey);
700         if (CApkey != NULL) EVP_PKEY_free(CApkey);
701         if (rq != NULL) X509_REQ_free(rq);
702         X509V3_EXT_cleanup();
703         EXIT(ret);
704         }
705
706 static int x509_certify(ctx,CAfile,digest,x,xca,pkey,serialfile,create,days)
707 X509_STORE *ctx;
708 char *CAfile;
709 EVP_MD *digest;
710 X509 *x;
711 X509 *xca;
712 EVP_PKEY *pkey;
713 char *serialfile;
714 int create;
715 int days;
716         {
717         int ret=0;
718         BIO *io=NULL;
719         MS_STATIC char buf2[1024];
720         char *buf=NULL,*p;
721         BIGNUM *serial=NULL;
722         ASN1_INTEGER *bs=NULL,bs2;
723         X509_STORE_CTX xsc;
724         EVP_PKEY *upkey;
725
726         upkey = X509_get_pubkey(xca);
727         EVP_PKEY_copy_parameters(upkey,pkey);
728         EVP_PKEY_free(upkey);
729
730         X509_STORE_CTX_init(&xsc,ctx,x,NULL);
731         buf=(char *)Malloc(EVP_PKEY_size(pkey)*2+
732                 ((serialfile == NULL)
733                         ?(strlen(CAfile)+strlen(POSTFIX)+1)
734                         :(strlen(serialfile)))+1);
735         if (buf == NULL) { BIO_printf(bio_err,"out of mem\n"); goto end; }
736         if (serialfile == NULL)
737                 {
738                 strcpy(buf,CAfile);
739                 for (p=buf; *p; p++)
740                         if (*p == '.')
741                                 {
742                                 *p='\0';
743                                 break;
744                                 }
745                 strcat(buf,POSTFIX);
746                 }
747         else
748                 strcpy(buf,serialfile);
749         serial=BN_new();
750         bs=ASN1_INTEGER_new();
751         if ((serial == NULL) || (bs == NULL))
752                 {
753                 ERR_print_errors(bio_err);
754                 goto end;
755                 }
756
757         io=BIO_new(BIO_s_file());
758         if (io == NULL)
759                 {
760                 ERR_print_errors(bio_err);
761                 goto end;
762                 }
763         
764         if (BIO_read_filename(io,buf) <= 0)
765                 {
766                 if (!create)
767                         {
768                         perror(buf);
769                         goto end;
770                         }
771                 else
772                         {
773                         ASN1_INTEGER_set(bs,0);
774                         BN_zero(serial);
775                         }
776                 }
777         else 
778                 {
779                 if (!a2i_ASN1_INTEGER(io,bs,buf2,1024))
780                         {
781                         BIO_printf(bio_err,"unable to load serial number from %s\n",buf);
782                         ERR_print_errors(bio_err);
783                         goto end;
784                         }
785                 else
786                         {
787                         serial=BN_bin2bn(bs->data,bs->length,serial);
788                         if (serial == NULL)
789                                 {
790                                 BIO_printf(bio_err,"error converting bin 2 bn");
791                                 goto end;
792                                 }
793                         }
794                 }
795
796         if (!BN_add_word(serial,1))
797                 { BIO_printf(bio_err,"add_word failure\n"); goto end; }
798         bs2.data=(unsigned char *)buf2;
799         bs2.length=BN_bn2bin(serial,bs2.data);
800
801         if (BIO_write_filename(io,buf) <= 0)
802                 {
803                 BIO_printf(bio_err,"error attempting to write serial number file\n");
804                 perror(buf);
805                 goto end;
806                 }
807         i2a_ASN1_INTEGER(io,&bs2);
808         BIO_puts(io,"\n");
809         BIO_free(io);
810         io=NULL;
811         
812         if (!X509_STORE_add_cert(ctx,x)) goto end;
813
814         /* NOTE: this certificate can/should be self signed, unless it was
815          * a certificate request in which case it is not. */
816         X509_STORE_CTX_set_cert(&xsc,x);
817         if (!reqfile && !X509_verify_cert(&xsc))
818                 goto end;
819
820         if (!X509_check_private_key(xca,pkey))
821                 {
822                 BIO_printf(bio_err,"CA certificate and CA private key do not match\n");
823                 goto end;
824                 }
825
826         if (!X509_set_issuer_name(x,X509_get_subject_name(xca))) goto end;
827         if (!X509_set_serialNumber(x,bs)) goto end;
828
829         if (X509_gmtime_adj(X509_get_notBefore(x),0L) == NULL)
830                 goto end;
831
832         /* hardwired expired */
833         if (X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days) == NULL)
834                 goto end;
835
836         /* don't save DSA parameters in child if parent has them
837          * and the parents and the childs are the same. */
838         upkey=X509_get_pubkey(x);
839         if (!EVP_PKEY_missing_parameters(pkey) &&
840                 (EVP_PKEY_cmp_parameters(pkey,upkey) == 0))
841                 {
842                 EVP_PKEY_save_parameters(upkey,0);
843                 /* Force a re-write */
844                 X509_set_pubkey(x,upkey);
845                 }
846         EVP_PKEY_free(upkey);
847
848         if (!X509_sign(x,pkey,digest)) goto end;
849         ret=1;
850 end:
851         X509_STORE_CTX_cleanup(&xsc);
852         if (!ret)
853                 ERR_print_errors(bio_err);
854         if (buf != NULL) Free(buf);
855         if (bs != NULL) ASN1_INTEGER_free(bs);
856         if (io != NULL) BIO_free(io);
857         if (serial != NULL) BN_free(serial);
858         return(ret);
859         }
860
861 static int MS_CALLBACK callb(ok, ctx)
862 int ok;
863 X509_STORE_CTX *ctx;
864         {
865         char buf[256];
866         int err;
867         X509 *err_cert;
868
869         /* it is ok to use a self signed certificate
870          * This case will catch both the initial ok == 0 and the
871          * final ok == 1 calls to this function */
872         err=X509_STORE_CTX_get_error(ctx);
873         if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
874                 return(1);
875
876         /* BAD we should have gotten an error.  Normally if everything
877          * worked X509_STORE_CTX_get_error(ctx) will still be set to
878          * DEPTH_ZERO_SELF_.... */
879         if (ok)
880                 {
881                 BIO_printf(bio_err,"error with certificate to be certified - should be self signed\n");
882                 return(0);
883                 }
884         else
885                 {
886                 err_cert=X509_STORE_CTX_get_current_cert(ctx);
887                 X509_NAME_oneline(X509_get_subject_name(err_cert),buf,256);
888                 BIO_printf(bio_err,"%s\n",buf);
889                 BIO_printf(bio_err,"error with certificate - error %d at depth %d\n%s\n",
890                         err,X509_STORE_CTX_get_error_depth(ctx),
891                         X509_verify_cert_error_string(err));
892                 return(1);
893                 }
894         }
895
896 static EVP_PKEY *load_key(file, format)
897 char *file;
898 int format;
899         {
900         BIO *key=NULL;
901         EVP_PKEY *pkey=NULL;
902
903         if (file == NULL)
904                 {
905                 BIO_printf(bio_err,"no keyfile specified\n");
906                 goto end;
907                 }
908         key=BIO_new(BIO_s_file());
909         if (key == NULL)
910                 {
911                 ERR_print_errors(bio_err);
912                 goto end;
913                 }
914         if (BIO_read_filename(key,file) <= 0)
915                 {
916                 perror(file);
917                 goto end;
918                 }
919 #ifndef NO_RSA
920         if      (format == FORMAT_ASN1)
921                 {
922                 RSA *rsa;
923
924                 rsa=d2i_RSAPrivateKey_bio(key,NULL);
925                 if (rsa != NULL)
926                         {
927                         if ((pkey=EVP_PKEY_new()) != NULL)
928                                 EVP_PKEY_assign_RSA(pkey,rsa);
929                         else
930                                 RSA_free(rsa);
931                         }
932                 }
933         else
934 #endif
935                 if (format == FORMAT_PEM)
936                 {
937                 pkey=PEM_read_bio_PrivateKey(key,NULL,NULL);
938                 }
939         else
940                 {
941                 BIO_printf(bio_err,"bad input format specified for key\n");
942                 goto end;
943                 }
944 end:
945         if (key != NULL) BIO_free(key);
946         if (pkey == NULL)
947                 BIO_printf(bio_err,"unable to load Private Key\n");
948         return(pkey);
949         }
950
951 static X509 *load_cert(file, format)
952 char *file;
953 int format;
954         {
955         ASN1_HEADER *ah=NULL;
956         BUF_MEM *buf=NULL;
957         X509 *x=NULL;
958         BIO *cert;
959
960         if ((cert=BIO_new(BIO_s_file())) == NULL)
961                 {
962                 ERR_print_errors(bio_err);
963                 goto end;
964                 }
965
966         if (file == NULL)
967                 BIO_set_fp(cert,stdin,BIO_NOCLOSE);
968         else
969                 {
970                 if (BIO_read_filename(cert,file) <= 0)
971                         {
972                         perror(file);
973                         goto end;
974                         }
975                 }
976         if      (format == FORMAT_ASN1)
977                 x=d2i_X509_bio(cert,NULL);
978         else if (format == FORMAT_NETSCAPE)
979                 {
980                 unsigned char *p,*op;
981                 int size=0,i;
982
983                 /* We sort of have to do it this way because it is sort of nice
984                  * to read the header first and check it, then
985                  * try to read the certificate */
986                 buf=BUF_MEM_new();
987                 for (;;)
988                         {
989                         if ((buf == NULL) || (!BUF_MEM_grow(buf,size+1024*10)))
990                                 goto end;
991                         i=BIO_read(cert,&(buf->data[size]),1024*10);
992                         size+=i;
993                         if (i == 0) break;
994                         if (i < 0)
995                                 {
996                                 perror("reading certificate");
997                                 goto end;
998                                 }
999                         }
1000                 p=(unsigned char *)buf->data;
1001                 op=p;
1002
1003                 /* First load the header */
1004                 if ((ah=d2i_ASN1_HEADER(NULL,&p,(long)size)) == NULL)
1005                         goto end;
1006                 if ((ah->header == NULL) || (ah->header->data == NULL) ||
1007                         (strncmp(CERT_HDR,(char *)ah->header->data,
1008                         ah->header->length) != 0))
1009                         {
1010                         BIO_printf(bio_err,"Error reading header on certificate\n");
1011                         goto end;
1012                         }
1013                 /* header is ok, so now read the object */
1014                 p=op;
1015                 ah->meth=X509_asn1_meth();
1016                 if ((ah=d2i_ASN1_HEADER(&ah,&p,(long)size)) == NULL)
1017                         goto end;
1018                 x=(X509 *)ah->data;
1019                 ah->data=NULL;
1020                 }
1021         else if (format == FORMAT_PEM)
1022                 x=PEM_read_bio_X509(cert,NULL,NULL);
1023         else    {
1024                 BIO_printf(bio_err,"bad input format specified for input cert\n");
1025                 goto end;
1026                 }
1027 end:
1028         if (x == NULL)
1029                 {
1030                 BIO_printf(bio_err,"unable to load certificate\n");
1031                 ERR_print_errors(bio_err);
1032                 }
1033         if (ah != NULL) ASN1_HEADER_free(ah);
1034         if (cert != NULL) BIO_free(cert);
1035         if (buf != NULL) BUF_MEM_free(buf);
1036         return(x);
1037         }
1038
1039 /* self sign */
1040 static int sign(x, pkey, days, digest)
1041 X509 *x;
1042 EVP_PKEY *pkey;
1043 int days;
1044 EVP_MD *digest;
1045         {
1046
1047         EVP_PKEY *pktmp;
1048
1049         pktmp = X509_get_pubkey(x);
1050         EVP_PKEY_copy_parameters(pktmp,pkey);
1051         EVP_PKEY_save_parameters(pktmp,1);
1052         EVP_PKEY_free(pktmp);
1053
1054         if (!X509_set_issuer_name(x,X509_get_subject_name(x))) goto err;
1055         if (X509_gmtime_adj(X509_get_notBefore(x),0) == NULL) goto err;
1056
1057         /* Lets just make it 12:00am GMT, Jan 1 1970 */
1058         /* memcpy(x->cert_info->validity->notBefore,"700101120000Z",13); */
1059         /* 28 days to be certified */
1060
1061         if (X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days) == NULL)
1062                 goto err;
1063
1064         if (!X509_set_pubkey(x,pkey)) goto err;
1065         if (!X509_sign(x,pkey,digest)) goto err;
1066         return(1);
1067 err:
1068         ERR_print_errors(bio_err);
1069         return(0);
1070         }