2a7188f121d412f2c36be4fa8e6f1ef880e367fe
[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,const EVP_MD *digest);
125 static int x509_certify (X509_STORE *ctx,char *CAfile,const EVP_MD *digest,
126                          X509 *x,X509 *xca,EVP_PKEY *pkey,char *serial,
127                          int create,int days);
128 #else
129 static int MS_CALLBACK callb();
130 static EVP_PKEY *load_key();
131 static X509 *load_cert();
132 static int sign ();
133 static int x509_certify ();
134 #endif
135
136 static int reqfile=0;
137
138 int MAIN(argc, argv)
139 int argc;
140 char **argv;
141         {
142         int ret=1;
143         X509_REQ *req=NULL;
144         X509 *x=NULL,*xca=NULL;
145         EVP_PKEY *Upkey=NULL,*CApkey=NULL;
146         int i,num,badops=0;
147         BIO *out=NULL;
148         BIO *STDout=NULL;
149         int informat,outformat,keyformat,CAformat,CAkeyformat;
150         char *infile=NULL,*outfile=NULL,*keyfile=NULL,*CAfile=NULL;
151         char *CAkeyfile=NULL,*CAserial=NULL;
152         int text=0,serial=0,hash=0,subject=0,issuer=0,startdate=0,enddate=0;
153         int noout=0,sign_flag=0,CA_flag=0,CA_createserial=0;
154         int C=0;
155         int x509req=0,days=DEF_DAYS,modulus=0;
156         char **pp;
157         X509_STORE *ctx=NULL;
158         X509_REQ *rq=NULL;
159         int fingerprint=0;
160         char buf[256];
161         const EVP_MD *md_alg,*digest=EVP_md5();
162
163         reqfile=0;
164
165         apps_startup();
166
167         if (bio_err == NULL)
168                 bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
169         STDout=BIO_new_fp(stdout,BIO_NOCLOSE);
170
171         informat=FORMAT_PEM;
172         outformat=FORMAT_PEM;
173         keyformat=FORMAT_PEM;
174         CAformat=FORMAT_PEM;
175         CAkeyformat=FORMAT_PEM;
176
177         ctx=X509_STORE_new();
178         if (ctx == NULL) goto end;
179         X509_STORE_set_verify_cb_func(ctx,callb);
180
181         argc--;
182         argv++;
183         num=0;
184         while (argc >= 1)
185                 {
186                 if      (strcmp(*argv,"-inform") == 0)
187                         {
188                         if (--argc < 1) goto bad;
189                         informat=str2fmt(*(++argv));
190                         }
191                 else if (strcmp(*argv,"-outform") == 0)
192                         {
193                         if (--argc < 1) goto bad;
194                         outformat=str2fmt(*(++argv));
195                         }
196                 else if (strcmp(*argv,"-keyform") == 0)
197                         {
198                         if (--argc < 1) goto bad;
199                         keyformat=str2fmt(*(++argv));
200                         }
201                 else if (strcmp(*argv,"-req") == 0)
202                         reqfile=1;
203                 else if (strcmp(*argv,"-CAform") == 0)
204                         {
205                         if (--argc < 1) goto bad;
206                         CAformat=str2fmt(*(++argv));
207                         }
208                 else if (strcmp(*argv,"-CAkeyform") == 0)
209                         {
210                         if (--argc < 1) goto bad;
211                         CAformat=str2fmt(*(++argv));
212                         }
213                 else if (strcmp(*argv,"-days") == 0)
214                         {
215                         if (--argc < 1) goto bad;
216                         days=atoi(*(++argv));
217                         if (days == 0)
218                                 {
219                                 BIO_printf(STDout,"bad number of days\n");
220                                 goto bad;
221                                 }
222                         }
223                 else if (strcmp(*argv,"-in") == 0)
224                         {
225                         if (--argc < 1) goto bad;
226                         infile= *(++argv);
227                         }
228                 else if (strcmp(*argv,"-out") == 0)
229                         {
230                         if (--argc < 1) goto bad;
231                         outfile= *(++argv);
232                         }
233                 else if (strcmp(*argv,"-signkey") == 0)
234                         {
235                         if (--argc < 1) goto bad;
236                         keyfile= *(++argv);
237                         sign_flag= ++num;
238                         }
239                 else if (strcmp(*argv,"-CA") == 0)
240                         {
241                         if (--argc < 1) goto bad;
242                         CAfile= *(++argv);
243                         CA_flag= ++num;
244                         }
245                 else if (strcmp(*argv,"-CAkey") == 0)
246                         {
247                         if (--argc < 1) goto bad;
248                         CAkeyfile= *(++argv);
249                         }
250                 else if (strcmp(*argv,"-CAserial") == 0)
251                         {
252                         if (--argc < 1) goto bad;
253                         CAserial= *(++argv);
254                         }
255                 else if (strcmp(*argv,"-C") == 0)
256                         C= ++num;
257                 else if (strcmp(*argv,"-serial") == 0)
258                         serial= ++num;
259                 else if (strcmp(*argv,"-modulus") == 0)
260                         modulus= ++num;
261                 else if (strcmp(*argv,"-x509toreq") == 0)
262                         x509req= ++num;
263                 else if (strcmp(*argv,"-text") == 0)
264                         text= ++num;
265                 else if (strcmp(*argv,"-hash") == 0)
266                         hash= ++num;
267                 else if (strcmp(*argv,"-subject") == 0)
268                         subject= ++num;
269                 else if (strcmp(*argv,"-issuer") == 0)
270                         issuer= ++num;
271                 else if (strcmp(*argv,"-fingerprint") == 0)
272                         fingerprint= ++num;
273                 else if (strcmp(*argv,"-dates") == 0)
274                         {
275                         startdate= ++num;
276                         enddate= ++num;
277                         }
278                 else if (strcmp(*argv,"-startdate") == 0)
279                         startdate= ++num;
280                 else if (strcmp(*argv,"-enddate") == 0)
281                         enddate= ++num;
282                 else if (strcmp(*argv,"-noout") == 0)
283                         noout= ++num;
284                 else if (strcmp(*argv,"-CAcreateserial") == 0)
285                         CA_createserial= ++num;
286                 else if ((md_alg=EVP_get_digestbyname(&((*argv)[1]))) != NULL)
287                         {
288                         /* ok */
289                         digest=md_alg;
290                         }
291                 else
292                         {
293                         BIO_printf(bio_err,"unknown option %s\n",*argv);
294                         badops=1;
295                         break;
296                         }
297                 argc--;
298                 argv++;
299                 }
300
301         if (badops)
302                 {
303 bad:
304                 for (pp=x509_usage; (*pp != NULL); pp++)
305                         BIO_printf(bio_err,*pp);
306                 goto end;
307                 }
308
309         ERR_load_crypto_strings();
310         X509V3_add_standard_extensions();
311
312         if (!X509_STORE_set_default_paths(ctx))
313                 {
314                 ERR_print_errors(bio_err);
315                 goto end;
316                 }
317
318         if ((CAkeyfile == NULL) && (CA_flag) && (CAformat == FORMAT_PEM))
319                 { CAkeyfile=CAfile; }
320         else if ((CA_flag) && (CAkeyfile == NULL))
321                 {
322                 BIO_printf(bio_err,"need to specify a CAkey if using the CA command\n");
323                 goto end;
324                 }
325
326         if (reqfile)
327                 {
328                 EVP_PKEY *pkey;
329                 X509_CINF *ci;
330                 BIO *in;
331
332                 if (!sign_flag && !CA_flag)
333                         {
334                         BIO_printf(bio_err,"We need a private key to sign with\n");
335                         goto end;
336                         }
337                 in=BIO_new(BIO_s_file());
338                 if (in == NULL)
339                         {
340                         ERR_print_errors(bio_err);
341                         goto end;
342                         }
343
344                 if (infile == NULL)
345                         BIO_set_fp(in,stdin,BIO_NOCLOSE|BIO_FP_TEXT);
346                 else
347                         {
348                         if (BIO_read_filename(in,infile) <= 0)
349                                 {
350                                 perror(infile);
351                                 goto end;
352                                 }
353                         }
354                 req=PEM_read_bio_X509_REQ(in,NULL,NULL);
355                 BIO_free(in);
356
357                 if (req == NULL) { perror(infile); goto end; }
358
359                 if (    (req->req_info == NULL) ||
360                         (req->req_info->pubkey == NULL) ||
361                         (req->req_info->pubkey->public_key == NULL) ||
362                         (req->req_info->pubkey->public_key->data == NULL))
363                         {
364                         BIO_printf(bio_err,"The certificate request appears to corrupted\n");
365                         BIO_printf(bio_err,"It does not contain a public key\n");
366                         goto end;
367                         }
368                 if ((pkey=X509_REQ_get_pubkey(req)) == NULL)
369                         {
370                         BIO_printf(bio_err,"error unpacking public key\n");
371                         goto end;
372                         }
373                 i=X509_REQ_verify(req,pkey);
374                 EVP_PKEY_free(pkey);
375                 if (i < 0)
376                         {
377                         BIO_printf(bio_err,"Signature verification error\n");
378                         ERR_print_errors(bio_err);
379                         goto end;
380                         }
381                 if (i == 0)
382                         {
383                         BIO_printf(bio_err,"Signature did not match the certificate request\n");
384                         goto end;
385                         }
386                 else
387                         BIO_printf(bio_err,"Signature ok\n");
388                 
389                 X509_NAME_oneline(req->req_info->subject,buf,256);
390                 BIO_printf(bio_err,"subject=%s\n",buf);
391
392                 if ((x=X509_new()) == NULL) goto end;
393                 ci=x->cert_info;
394
395                 if (!ASN1_INTEGER_set(X509_get_serialNumber(x),0)) goto end;
396                 if (!X509_set_issuer_name(x,req->req_info->subject)) goto end;
397                 if (!X509_set_subject_name(x,req->req_info->subject)) goto end;
398
399                 X509_gmtime_adj(X509_get_notBefore(x),0);
400                 X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days);
401
402 #if 0
403                 X509_PUBKEY_free(ci->key);
404                 ci->key=req->req_info->pubkey;
405                 req->req_info->pubkey=NULL;
406 #else
407                 pkey = X509_REQ_get_pubkey(req);
408                 X509_set_pubkey(x,pkey);
409                 EVP_PKEY_free(pkey);
410 #endif
411                 }
412         else
413                 x=load_cert(infile,informat);
414
415         if (x == NULL) goto end;
416         if (CA_flag)
417                 {
418                 xca=load_cert(CAfile,CAformat);
419                 if (xca == NULL) goto end;
420                 }
421
422         if (!noout || text)
423                 {
424                 OBJ_create("2.99999.3",
425                         "SET.ex3","SET x509v3 extension 3");
426
427                 out=BIO_new(BIO_s_file());
428                 if (out == NULL)
429                         {
430                         ERR_print_errors(bio_err);
431                         goto end;
432                         }
433                 if (outfile == NULL)
434                         BIO_set_fp(out,stdout,BIO_NOCLOSE);
435                 else
436                         {
437                         if (BIO_write_filename(out,outfile) <= 0)
438                                 {
439                                 perror(outfile);
440                                 goto end;
441                                 }
442                         }
443                 }
444
445         if (num)
446                 {
447                 for (i=1; i<=num; i++)
448                         {
449                         if (issuer == i)
450                                 {
451                                 X509_NAME_oneline(X509_get_issuer_name(x),
452                                         buf,256);
453                                 BIO_printf(STDout,"issuer= %s\n",buf);
454                                 }
455                         else if (subject == i) 
456                                 {
457                                 X509_NAME_oneline(X509_get_subject_name(x),
458                                         buf,256);
459                                 BIO_printf(STDout,"subject=%s\n",buf);
460                                 }
461                         else if (serial == i)
462                                 {
463                                 BIO_printf(STDout,"serial=");
464                                 i2a_ASN1_INTEGER(STDout,x->cert_info->serialNumber);
465                                 BIO_printf(STDout,"\n");
466                                 }
467                         else if (hash == i)
468                                 {
469                                 BIO_printf(STDout,"%08lx\n",X509_subject_name_hash(x));
470                                 }
471                         else
472                                 if (modulus == i)
473                                 {
474                                 EVP_PKEY *pkey;
475
476                                 pkey=X509_get_pubkey(x);
477                                 if (pkey == NULL)
478                                         {
479                                         BIO_printf(bio_err,"Modulus=unavailable\n");
480                                         ERR_print_errors(bio_err);
481                                         goto end;
482                                         }
483                                 BIO_printf(STDout,"Modulus=");
484 #ifndef NO_RSA
485                                 if (pkey->type == EVP_PKEY_RSA)
486                                         BN_print(STDout,pkey->pkey.rsa->n);
487                                 else
488 #endif
489 #ifndef NO_DSA
490                                 if (pkey->type == EVP_PKEY_DSA)
491                                         BN_print(STDout,pkey->pkey.dsa->pub_key);
492                                 else
493 #endif
494                                         BIO_printf(STDout,"Wrong Algorithm type");
495                                 BIO_printf(STDout,"\n");
496                                 EVP_PKEY_free(pkey);
497                                 }
498                         else
499                                 if (C == i)
500                                 {
501                                 unsigned char *d;
502                                 char *m;
503                                 int y,z;
504
505                                 X509_NAME_oneline(X509_get_subject_name(x),
506                                         buf,256);
507                                 BIO_printf(STDout,"/* subject:%s */\n",buf);
508                                 m=X509_NAME_oneline(
509                                         X509_get_issuer_name(x),buf,256);
510                                 BIO_printf(STDout,"/* issuer :%s */\n",buf);
511
512                                 z=i2d_X509(x,NULL);
513                                 m=Malloc(z);
514
515                                 d=(unsigned char *)m;
516                                 z=i2d_X509_NAME(X509_get_subject_name(x),&d);
517                                 BIO_printf(STDout,"unsigned char XXX_subject_name[%d]={\n",z);
518                                 d=(unsigned char *)m;
519                                 for (y=0; y<z; y++)
520                                         {
521                                         BIO_printf(STDout,"0x%02X,",d[y]);
522                                         if ((y & 0x0f) == 0x0f) BIO_printf(STDout,"\n");
523                                         }
524                                 if (y%16 != 0) BIO_printf(STDout,"\n");
525                                 BIO_printf(STDout,"};\n");
526
527                                 z=i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x),&d);
528                                 BIO_printf(STDout,"unsigned char XXX_public_key[%d]={\n",z);
529                                 d=(unsigned char *)m;
530                                 for (y=0; y<z; y++)
531                                         {
532                                         BIO_printf(STDout,"0x%02X,",d[y]);
533                                         if ((y & 0x0f) == 0x0f)
534                                                 BIO_printf(STDout,"\n");
535                                         }
536                                 if (y%16 != 0) BIO_printf(STDout,"\n");
537                                 BIO_printf(STDout,"};\n");
538
539                                 z=i2d_X509(x,&d);
540                                 BIO_printf(STDout,"unsigned char XXX_certificate[%d]={\n",z);
541                                 d=(unsigned char *)m;
542                                 for (y=0; y<z; y++)
543                                         {
544                                         BIO_printf(STDout,"0x%02X,",d[y]);
545                                         if ((y & 0x0f) == 0x0f)
546                                                 BIO_printf(STDout,"\n");
547                                         }
548                                 if (y%16 != 0) BIO_printf(STDout,"\n");
549                                 BIO_printf(STDout,"};\n");
550
551                                 Free(m);
552                                 }
553                         else if (text == i)
554                                 {
555                                 X509_print(out,x);
556                                 }
557                         else if (startdate == i)
558                                 {
559                                 BIO_puts(STDout,"notBefore=");
560                                 ASN1_TIME_print(STDout,X509_get_notBefore(x));
561                                 BIO_puts(STDout,"\n");
562                                 }
563                         else if (enddate == i)
564                                 {
565                                 BIO_puts(STDout,"notAfter=");
566                                 ASN1_TIME_print(STDout,X509_get_notAfter(x));
567                                 BIO_puts(STDout,"\n");
568                                 }
569                         else if (fingerprint == i)
570                                 {
571                                 int j;
572                                 unsigned int n;
573                                 unsigned char md[EVP_MAX_MD_SIZE];
574
575                                 if (!X509_digest(x,EVP_md5(),md,&n))
576                                         {
577                                         BIO_printf(bio_err,"out of memory\n");
578                                         goto end;
579                                         }
580                                 BIO_printf(STDout,"MD5 Fingerprint=");
581                                 for (j=0; j<(int)n; j++)
582                                         {
583                                         BIO_printf(STDout,"%02X%c",md[j],
584                                                 (j+1 == (int)n)
585                                                 ?'\n':':');
586                                         }
587                                 }
588
589                         /* should be in the library */
590                         else if ((sign_flag == i) && (x509req == 0))
591                                 {
592                                 BIO_printf(bio_err,"Getting Private key\n");
593                                 if (Upkey == NULL)
594                                         {
595                                         Upkey=load_key(keyfile,keyformat);
596                                         if (Upkey == NULL) goto end;
597                                         }
598 #ifndef NO_DSA
599                                 if (Upkey->type == EVP_PKEY_DSA)
600                                         digest=EVP_dss1();
601 #endif
602
603                                 if (!sign(x,Upkey,days,digest)) goto end;
604                                 }
605                         else if (CA_flag == i)
606                                 {
607                                 BIO_printf(bio_err,"Getting CA Private Key\n");
608                                 if (CAkeyfile != NULL)
609                                         {
610                                         CApkey=load_key(CAkeyfile,CAkeyformat);
611                                         if (CApkey == NULL) goto end;
612                                         }
613 #ifndef NO_DSA
614                                 if (CApkey->type == EVP_PKEY_DSA)
615                                         digest=EVP_dss1();
616 #endif
617                                 
618                                 if (!x509_certify(ctx,CAfile,digest,x,xca,
619                                         CApkey,
620                                         CAserial,CA_createserial,days))
621                                         goto end;
622                                 }
623                         else if (x509req == i)
624                                 {
625                                 EVP_PKEY *pk;
626
627                                 BIO_printf(bio_err,"Getting request Private Key\n");
628                                 if (keyfile == NULL)
629                                         {
630                                         BIO_printf(bio_err,"no request key file specified\n");
631                                         goto end;
632                                         }
633                                 else
634                                         {
635                                         pk=load_key(keyfile,FORMAT_PEM);
636                                         if (pk == NULL) goto end;
637                                         }
638
639                                 BIO_printf(bio_err,"Generating certificate request\n");
640
641                                 rq=X509_to_X509_REQ(x,pk,EVP_md5());
642                                 EVP_PKEY_free(pk);
643                                 if (rq == NULL)
644                                         {
645                                         ERR_print_errors(bio_err);
646                                         goto end;
647                                         }
648                                 if (!noout)
649                                         {
650                                         X509_REQ_print(out,rq);
651                                         PEM_write_bio_X509_REQ(out,rq);
652                                         }
653                                 noout=1;
654                                 }
655                         }
656                 }
657
658         if (noout)
659                 {
660                 ret=0;
661                 goto end;
662                 }
663
664         if      (outformat == FORMAT_ASN1)
665                 i=i2d_X509_bio(out,x);
666         else if (outformat == FORMAT_PEM)
667                 i=PEM_write_bio_X509(out,x);
668         else if (outformat == FORMAT_NETSCAPE)
669                 {
670                 ASN1_HEADER ah;
671                 ASN1_OCTET_STRING os;
672
673                 os.data=(unsigned char *)CERT_HDR;
674                 os.length=strlen(CERT_HDR);
675                 ah.header= &os;
676                 ah.data=(char *)x;
677                 ah.meth=X509_asn1_meth();
678
679                 /* no macro for this one yet */
680                 i=ASN1_i2d_bio(i2d_ASN1_HEADER,out,(unsigned char *)&ah);
681                 }
682         else    {
683                 BIO_printf(bio_err,"bad output format specified for outfile\n");
684                 goto end;
685                 }
686         if (!i) {
687                 BIO_printf(bio_err,"unable to write certificate\n");
688                 ERR_print_errors(bio_err);
689                 goto end;
690                 }
691         ret=0;
692 end:
693         OBJ_cleanup();
694         if (out != NULL) BIO_free(out);
695         if (STDout != NULL) BIO_free(STDout);
696         if (ctx != NULL) X509_STORE_free(ctx);
697         if (req != NULL) X509_REQ_free(req);
698         if (x != NULL) X509_free(x);
699         if (xca != NULL) X509_free(xca);
700         if (Upkey != NULL) EVP_PKEY_free(Upkey);
701         if (CApkey != NULL) EVP_PKEY_free(CApkey);
702         if (rq != NULL) X509_REQ_free(rq);
703         X509V3_EXT_cleanup();
704         EXIT(ret);
705         }
706
707 static int x509_certify(ctx,CAfile,digest,x,xca,pkey,serialfile,create,days)
708 X509_STORE *ctx;
709 char *CAfile;
710 const EVP_MD *digest;
711 X509 *x;
712 X509 *xca;
713 EVP_PKEY *pkey;
714 char *serialfile;
715 int create;
716 int days;
717         {
718         int ret=0;
719         BIO *io=NULL;
720         MS_STATIC char buf2[1024];
721         char *buf=NULL,*p;
722         BIGNUM *serial=NULL;
723         ASN1_INTEGER *bs=NULL,bs2;
724         X509_STORE_CTX xsc;
725         EVP_PKEY *upkey;
726
727         upkey = X509_get_pubkey(xca);
728         EVP_PKEY_copy_parameters(upkey,pkey);
729         EVP_PKEY_free(upkey);
730
731         X509_STORE_CTX_init(&xsc,ctx,x,NULL);
732         buf=(char *)Malloc(EVP_PKEY_size(pkey)*2+
733                 ((serialfile == NULL)
734                         ?(strlen(CAfile)+strlen(POSTFIX)+1)
735                         :(strlen(serialfile)))+1);
736         if (buf == NULL) { BIO_printf(bio_err,"out of mem\n"); goto end; }
737         if (serialfile == NULL)
738                 {
739                 strcpy(buf,CAfile);
740                 for (p=buf; *p; p++)
741                         if (*p == '.')
742                                 {
743                                 *p='\0';
744                                 break;
745                                 }
746                 strcat(buf,POSTFIX);
747                 }
748         else
749                 strcpy(buf,serialfile);
750         serial=BN_new();
751         bs=ASN1_INTEGER_new();
752         if ((serial == NULL) || (bs == NULL))
753                 {
754                 ERR_print_errors(bio_err);
755                 goto end;
756                 }
757
758         io=BIO_new(BIO_s_file());
759         if (io == NULL)
760                 {
761                 ERR_print_errors(bio_err);
762                 goto end;
763                 }
764         
765         if (BIO_read_filename(io,buf) <= 0)
766                 {
767                 if (!create)
768                         {
769                         perror(buf);
770                         goto end;
771                         }
772                 else
773                         {
774                         ASN1_INTEGER_set(bs,0);
775                         BN_zero(serial);
776                         }
777                 }
778         else 
779                 {
780                 if (!a2i_ASN1_INTEGER(io,bs,buf2,1024))
781                         {
782                         BIO_printf(bio_err,"unable to load serial number from %s\n",buf);
783                         ERR_print_errors(bio_err);
784                         goto end;
785                         }
786                 else
787                         {
788                         serial=BN_bin2bn(bs->data,bs->length,serial);
789                         if (serial == NULL)
790                                 {
791                                 BIO_printf(bio_err,"error converting bin 2 bn");
792                                 goto end;
793                                 }
794                         }
795                 }
796
797         if (!BN_add_word(serial,1))
798                 { BIO_printf(bio_err,"add_word failure\n"); goto end; }
799         bs2.data=(unsigned char *)buf2;
800         bs2.length=BN_bn2bin(serial,bs2.data);
801
802         if (BIO_write_filename(io,buf) <= 0)
803                 {
804                 BIO_printf(bio_err,"error attempting to write serial number file\n");
805                 perror(buf);
806                 goto end;
807                 }
808         i2a_ASN1_INTEGER(io,&bs2);
809         BIO_puts(io,"\n");
810         BIO_free(io);
811         io=NULL;
812         
813         if (!X509_STORE_add_cert(ctx,x)) goto end;
814
815         /* NOTE: this certificate can/should be self signed, unless it was
816          * a certificate request in which case it is not. */
817         X509_STORE_CTX_set_cert(&xsc,x);
818         if (!reqfile && !X509_verify_cert(&xsc))
819                 goto end;
820
821         if (!X509_check_private_key(xca,pkey))
822                 {
823                 BIO_printf(bio_err,"CA certificate and CA private key do not match\n");
824                 goto end;
825                 }
826
827         if (!X509_set_issuer_name(x,X509_get_subject_name(xca))) goto end;
828         if (!X509_set_serialNumber(x,bs)) goto end;
829
830         if (X509_gmtime_adj(X509_get_notBefore(x),0L) == NULL)
831                 goto end;
832
833         /* hardwired expired */
834         if (X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days) == NULL)
835                 goto end;
836
837         /* don't save DSA parameters in child if parent has them
838          * and the parents and the childs are the same. */
839         upkey=X509_get_pubkey(x);
840         if (!EVP_PKEY_missing_parameters(pkey) &&
841                 (EVP_PKEY_cmp_parameters(pkey,upkey) == 0))
842                 {
843                 EVP_PKEY_save_parameters(upkey,0);
844                 /* Force a re-write */
845                 X509_set_pubkey(x,upkey);
846                 }
847         EVP_PKEY_free(upkey);
848
849         if (!X509_sign(x,pkey,digest)) goto end;
850         ret=1;
851 end:
852         X509_STORE_CTX_cleanup(&xsc);
853         if (!ret)
854                 ERR_print_errors(bio_err);
855         if (buf != NULL) Free(buf);
856         if (bs != NULL) ASN1_INTEGER_free(bs);
857         if (io != NULL) BIO_free(io);
858         if (serial != NULL) BN_free(serial);
859         return(ret);
860         }
861
862 static int MS_CALLBACK callb(ok, ctx)
863 int ok;
864 X509_STORE_CTX *ctx;
865         {
866         char buf[256];
867         int err;
868         X509 *err_cert;
869
870         /* it is ok to use a self signed certificate
871          * This case will catch both the initial ok == 0 and the
872          * final ok == 1 calls to this function */
873         err=X509_STORE_CTX_get_error(ctx);
874         if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
875                 return(1);
876
877         /* BAD we should have gotten an error.  Normally if everything
878          * worked X509_STORE_CTX_get_error(ctx) will still be set to
879          * DEPTH_ZERO_SELF_.... */
880         if (ok)
881                 {
882                 BIO_printf(bio_err,"error with certificate to be certified - should be self signed\n");
883                 return(0);
884                 }
885         else
886                 {
887                 err_cert=X509_STORE_CTX_get_current_cert(ctx);
888                 X509_NAME_oneline(X509_get_subject_name(err_cert),buf,256);
889                 BIO_printf(bio_err,"%s\n",buf);
890                 BIO_printf(bio_err,"error with certificate - error %d at depth %d\n%s\n",
891                         err,X509_STORE_CTX_get_error_depth(ctx),
892                         X509_verify_cert_error_string(err));
893                 return(1);
894                 }
895         }
896
897 static EVP_PKEY *load_key(file, format)
898 char *file;
899 int format;
900         {
901         BIO *key=NULL;
902         EVP_PKEY *pkey=NULL;
903
904         if (file == NULL)
905                 {
906                 BIO_printf(bio_err,"no keyfile specified\n");
907                 goto end;
908                 }
909         key=BIO_new(BIO_s_file());
910         if (key == NULL)
911                 {
912                 ERR_print_errors(bio_err);
913                 goto end;
914                 }
915         if (BIO_read_filename(key,file) <= 0)
916                 {
917                 perror(file);
918                 goto end;
919                 }
920 #ifndef NO_RSA
921         if      (format == FORMAT_ASN1)
922                 {
923                 RSA *rsa;
924
925                 rsa=d2i_RSAPrivateKey_bio(key,NULL);
926                 if (rsa != NULL)
927                         {
928                         if ((pkey=EVP_PKEY_new()) != NULL)
929                                 EVP_PKEY_assign_RSA(pkey,rsa);
930                         else
931                                 RSA_free(rsa);
932                         }
933                 }
934         else
935 #endif
936                 if (format == FORMAT_PEM)
937                 {
938                 pkey=PEM_read_bio_PrivateKey(key,NULL,NULL);
939                 }
940         else
941                 {
942                 BIO_printf(bio_err,"bad input format specified for key\n");
943                 goto end;
944                 }
945 end:
946         if (key != NULL) BIO_free(key);
947         if (pkey == NULL)
948                 BIO_printf(bio_err,"unable to load Private Key\n");
949         return(pkey);
950         }
951
952 static X509 *load_cert(file, format)
953 char *file;
954 int format;
955         {
956         ASN1_HEADER *ah=NULL;
957         BUF_MEM *buf=NULL;
958         X509 *x=NULL;
959         BIO *cert;
960
961         if ((cert=BIO_new(BIO_s_file())) == NULL)
962                 {
963                 ERR_print_errors(bio_err);
964                 goto end;
965                 }
966
967         if (file == NULL)
968                 BIO_set_fp(cert,stdin,BIO_NOCLOSE);
969         else
970                 {
971                 if (BIO_read_filename(cert,file) <= 0)
972                         {
973                         perror(file);
974                         goto end;
975                         }
976                 }
977         if      (format == FORMAT_ASN1)
978                 x=d2i_X509_bio(cert,NULL);
979         else if (format == FORMAT_NETSCAPE)
980                 {
981                 unsigned char *p,*op;
982                 int size=0,i;
983
984                 /* We sort of have to do it this way because it is sort of nice
985                  * to read the header first and check it, then
986                  * try to read the certificate */
987                 buf=BUF_MEM_new();
988                 for (;;)
989                         {
990                         if ((buf == NULL) || (!BUF_MEM_grow(buf,size+1024*10)))
991                                 goto end;
992                         i=BIO_read(cert,&(buf->data[size]),1024*10);
993                         size+=i;
994                         if (i == 0) break;
995                         if (i < 0)
996                                 {
997                                 perror("reading certificate");
998                                 goto end;
999                                 }
1000                         }
1001                 p=(unsigned char *)buf->data;
1002                 op=p;
1003
1004                 /* First load the header */
1005                 if ((ah=d2i_ASN1_HEADER(NULL,&p,(long)size)) == NULL)
1006                         goto end;
1007                 if ((ah->header == NULL) || (ah->header->data == NULL) ||
1008                         (strncmp(CERT_HDR,(char *)ah->header->data,
1009                         ah->header->length) != 0))
1010                         {
1011                         BIO_printf(bio_err,"Error reading header on certificate\n");
1012                         goto end;
1013                         }
1014                 /* header is ok, so now read the object */
1015                 p=op;
1016                 ah->meth=X509_asn1_meth();
1017                 if ((ah=d2i_ASN1_HEADER(&ah,&p,(long)size)) == NULL)
1018                         goto end;
1019                 x=(X509 *)ah->data;
1020                 ah->data=NULL;
1021                 }
1022         else if (format == FORMAT_PEM)
1023                 x=PEM_read_bio_X509(cert,NULL,NULL);
1024         else    {
1025                 BIO_printf(bio_err,"bad input format specified for input cert\n");
1026                 goto end;
1027                 }
1028 end:
1029         if (x == NULL)
1030                 {
1031                 BIO_printf(bio_err,"unable to load certificate\n");
1032                 ERR_print_errors(bio_err);
1033                 }
1034         if (ah != NULL) ASN1_HEADER_free(ah);
1035         if (cert != NULL) BIO_free(cert);
1036         if (buf != NULL) BUF_MEM_free(buf);
1037         return(x);
1038         }
1039
1040 /* self sign */
1041 static int sign(x, pkey, days, digest)
1042 X509 *x;
1043 EVP_PKEY *pkey;
1044 int days;
1045 const EVP_MD *digest;
1046         {
1047
1048         EVP_PKEY *pktmp;
1049
1050         pktmp = X509_get_pubkey(x);
1051         EVP_PKEY_copy_parameters(pktmp,pkey);
1052         EVP_PKEY_save_parameters(pktmp,1);
1053         EVP_PKEY_free(pktmp);
1054
1055         if (!X509_set_issuer_name(x,X509_get_subject_name(x))) goto err;
1056         if (X509_gmtime_adj(X509_get_notBefore(x),0) == NULL) goto err;
1057
1058         /* Lets just make it 12:00am GMT, Jan 1 1970 */
1059         /* memcpy(x->cert_info->validity->notBefore,"700101120000Z",13); */
1060         /* 28 days to be certified */
1061
1062         if (X509_gmtime_adj(X509_get_notAfter(x),(long)60*60*24*days) == NULL)
1063                 goto err;
1064
1065         if (!X509_set_pubkey(x,pkey)) goto err;
1066         if (!X509_sign(x,pkey,digest)) goto err;
1067         return(1);
1068 err:
1069         ERR_print_errors(bio_err);
1070         return(0);
1071         }